java扫描仪仅在检测到整数时才继续

我正在使用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: ");


此代码在运行时要求输入一个数字。例如,如果您输入一个字母,它会显示一个空行,直到您输入另一个字母,然后它会说请输入一个数字。我不明白为什么它没有说,一旦出现字母或除整数之外的任何内容,请输入数字


一只斗牛犬
浏览 68回答 1
1回答

泛舟湖上清波郎朗

只需使用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,如上所述。它更清晰、更详细。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java