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

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

java掃描儀僅在檢測到整數時才繼續

java掃描儀僅在檢測到整數時才繼續

一只斗牛犬 2023-08-04 15:29:19
我正在使用java中的掃描儀,并且僅在檢測到用戶選擇的整數時才嘗試讓程序繼續,但我編寫的代碼沒有提供該功能。這是我的代碼:import java.util.Scanner;/** * * @author Ansel */public class Test {    public static void main(String[] args) {        Scanner scan = new Scanner (System.in);        AddressBook ad1 = new AddressBook();        String firstName="";        String lastName="";        String key="";        String street="";        String city="";        String county="";        String postalCode="";        String mNumber="";        int choice=0;      do{        System.out.println("********************************************************************************");        System.out.println("Welcome to the Address book. Please pick from the options below.\n");        System.out.println("1.Add user \n2.Remove user \n3.Edit user \n4.List Contact \n5.Sort contacts \n6.Exit");          System.out.print("Please enter a choice: ");          int reloop = 0;        do {         try {             scan.nextLine();             choice = scan.nextInt();              reloop ++;         } catch (Exception e) {       System.out.println ("Please enter a number!");  }} while(reloop == 0);        if(choice==1){            //Add user            System.out.print("Please enter firstname: ");            firstName=scan.next();            System.out.print("Please enter lastname: ");            lastName=scan.next();            scan.nextLine();            System.out.print("Please enter street:");            street=scan.nextLine();            System.out.print("Please enter city: ");            city=scan.next();            System.out.print("Please enter county: ");此代碼在運行時要求輸入一個數字。例如,如果您輸入一個字母,它會顯示一個空行,直到您輸入另一個字母,然后它會說請輸入一個數字。我不明白為什么它沒有說,一旦出現字母或除整數之外的任何內容,請輸入數字
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

只需使用Scanner.nextLine和Integer.parseInt即可避免混亂。


Scanner scan = new Scanner(System.in);

int choice = 0;

System.out.print("Please enter a choice: ");

int reloop = 0;

do {

  try {

    String input = scan.nextLine(); // Scan the next line from System.in

    choice = Integer.parseInt(input); // Try to parse it as an int

    reloop++;

  } catch (Exception e) {

    System.out.println("Please enter a number!");

  }

} while (reloop == 0);

您也可以使用nextLineafter everynextInt來終止該行,但我更喜歡單獨解析int,如上所述。它更清晰、更詳細。


查看完整回答
反對 回復 2023-08-04
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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