为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 65 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信