第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

java掃描儀僅在檢測(cè)到整數(shù)時(shí)才繼續(xù)

java掃描儀僅在檢測(cè)到整數(shù)時(shí)才繼續(xù)

一只斗牛犬 2023-08-04 15:29:19
我正在使用java中的掃描儀,并且僅在檢測(cè)到用戶選擇的整數(shù)時(shí)才嘗試讓程序繼續(xù),但我編寫(xiě)的代碼沒(méi)有提供該功能。這是我的代碼: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: ");此代碼在運(yùn)行時(shí)要求輸入一個(gè)數(shù)字。例如,如果您輸入一個(gè)字母,它會(huì)顯示一個(gè)空行,直到您輸入另一個(gè)字母,然后它會(huì)說(shuō)請(qǐng)輸入一個(gè)數(shù)字。我不明白為什么它沒(méi)有說(shuō),一旦出現(xiàn)字母或除整數(shù)之外的任何內(nèi)容,請(qǐng)輸入數(shù)字
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊

只需使用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來(lái)終止該行,但我更喜歡單獨(dú)解析int,如上所述。它更清晰、更詳細(xì)。


查看完整回答
反對(duì) 回復(fù) 2023-08-04
  • 1 回答
  • 0 關(guān)注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)