【问题标题】:How do I get the Scanner in java to read a string? [closed]如何让 Java 中的 Scanner 读取字符串? [关闭]
【发布时间】:2020-10-16 21:33:40
【问题描述】:

当用户输入 q 时如何让我的程序退出? 扫描仪有问题吗?


我的代码

import java.util.*;
public class Main{

         public static void main(String []args){
             
             int age;
             
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter your age, or enter 'q' to quit the program.");
            age = scan.nextInt();
            
            
            if(age.equals("q") || age.equals("Q")){
                
                return 0;
                
            }
            
            
            
            System.out.println("Your age is " + age);
            
            
            
         }
    
    }

【问题讨论】:

标签: java string loops integer java.util.scanner


【解决方案1】:

我在您的代码中主要看到两个问题:

  1. 它缺少重复询问年龄的循环。有很多方法(forwhiledo-while)来编写循环,但我发现do-while 最适合这种情况,因为它总是至少执行一次do 块中的语句。
  2. age 属于 int 类型,因此不能与字符串进行比较,例如您的代码age.equals("q") 不正确。处理这种情况的一个好方法是将输入转换为 String 类型的变量,并检查该值是否应该允许/禁止对其进行处理(例如,尝试将其解析为 int)。

请注意,当您尝试解析无法解析为int 的字符串时(例如"a"),您会得到一个需要处理的NumberFormatException(例如,显示错误消息,更改某些状态)等等)。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int age;
        String input;
        Scanner scan = new Scanner(System.in);
        boolean valid;

        do {
            // Start with the assumption that input will be valid
            valid = true;
            System.out.print("Enter your age, or enter 'q' to quit the program: ");
            input = scan.nextLine();

            if (!(input.equals("q") || input.equals("Q"))) {
                try {
                    // Try to parse input into an int
                    age = Integer.parseInt(input);
                    System.out.println("Your age is " + age);
                } catch (NumberFormatException e) {
                    System.out.println("Invalid input");
                    // Change the value of valid to false
                    valid = false;
                }
            }
        } while (!valid || !(input.equals("q") || input.equals("Q")));
    }
}

示例运行:

Enter your age, or enter 'q' to quit the program: a
Invalid input
Enter your age, or enter 'q' to quit the program: 12.5
Invalid input
Enter your age, or enter 'q' to quit the program: 14
Your age is 14
Enter your age, or enter 'q' to quit the program: 56
Your age is 56
Enter your age, or enter 'q' to quit the program: q

【讨论】:

猜你喜欢
  • 2010-11-30
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
相关资源
最近更新 更多