亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從用戶輸入錯誤的地方重復輸入?

如何從用戶輸入錯誤的地方重復輸入?

qq_遁去的一_1 2021-08-06 10:58:32
我有一些二傳手。問題是,我想從用戶準確輸入錯誤輸入的地方啟動程序。例如:如果用戶提出了錯誤的輸入street問題,它將不會name再次從street. 我知道這個選項,但實施起來很糟糕。boolean isBadInput = true;    while (isBadInput) {        try {            System.out.print("name: ");            client.setName(input.next());            isBadInput = false;        } catch (InputMismatchException e) {            System.out.println("bad input, try again");        }    }    isBadInput = true;    while (isBadInput) {        try {            System.out.print("surname: ");            client.setSurname(input.next());            isBadInput = false;        } catch (InputMismatchException e) {            System.out.println("bad input, try again");        }    }    isBadInput = true;    // and so on    System.out.print("city: ");    client.setCity(input.next());    System.out.print("rent date: ");    client.setRentDate(input.next());    System.out.print("street: ");    client.setStreet(input.next());    System.out.print("pesel number: ");    client.setPeselNumber(input.nextLong());    System.out.print("house number: ");    client.setHouseNumber(input.nextInt());如您所見,我需要編寫大量的 try/catch 塊才能做到這一點。還有其他選擇嗎?我不想做這樣的事情:boolean isBadInput = true;    while (isBadInput) {        try {            System.out.print("name: ");            client.setName(input.next());            System.out.print("surname: ");            client.setSurname(input.next());            System.out.print("city: ");            client.setCity(input.next());            System.out.print("rent date: ");            client.setRentDate(input.next());            System.out.print("street: ");            client.setStreet(input.next());            System.out.print("pesel number: ");            client.setPeselNumber(input.nextLong());            System.out.print("house number: ");            client.setHouseNumber(input.nextInt());        } catch (InputMismatchException e) {            System.out.println("bad input, try again");        }    }因為程序name每次都會重復。
查看完整描述

2 回答

?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

如果您檢查輸入是否錯誤的邏輯是基于異常的,您可以輕松地將讀取輸入部分移動到一個單獨的方法中。


public String readInput(Scanner scn, String label) {


    String returnValue = "";

    while (true) {

        try {

            System.out.print(label + ": ");

            returnValue  = scn.next();

            break;               

        } catch (Exception e) {

            System.out.println("Value you entered is bad, please try again");               

        }

    }

    return returnValue;

}


查看完整回答
反對 回復 2021-08-06
  • 2 回答
  • 0 關注
  • 179 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號