如何在Java中使用Scanner读取字符串?

huangapple go评论111阅读模式
英文:

How do I get the Scanner in java to read a string?

问题

  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args) {
  4. String input;
  5. Scanner scan = new Scanner(System.in);
  6. System.out.println("Enter your age, or enter 'q' to quit the program.");
  7. input = scan.next();
  8. if (input.equalsIgnoreCase("q")) {
  9. return;
  10. }
  11. int age = Integer.parseInt(input);
  12. System.out.println("Your age is " + age);
  13. }
  14. }
英文:

How would I get my program to quit when the user enters q?
Is there something wrong with the scanner?


My code

  1. import java.util.*;
  2. public class Main{
  3. public static void main(String []args){
  4. int age;
  5. Scanner scan = new Scanner(System.in);
  6. System.out.println("Enter your age, or enter 'q' to quit the program.");
  7. age = scan.nextInt();
  8. if(age.equals("q") || age.equals("Q")){
  9. return 0;
  10. }
  11. System.out.println("Your age is " + age);
  12. }
  13. }

答案1

得分: 0

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

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

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

  1. import java.util.Scanner;
  2. public class Main {
  3. public static void main(String[] args) {
  4. int age;
  5. String input;
  6. Scanner scan = new Scanner(System.in);
  7. boolean valid;
  8. do {
  9. // 假设输入是有效的
  10. valid = true;
  11. System.out.print("输入你的年龄,或输入 'q' 退出程序: ");
  12. input = scan.nextLine();
  13. if (!(input.equals("q") || input.equals("Q"))) {
  14. try {
  15. // 尝试将输入解析为整数
  16. age = Integer.parseInt(input);
  17. System.out.println("你的年龄是 " + age);
  18. } catch (NumberFormatException e) {
  19. System.out.println("无效输入");
  20. // 将 valid 的值更改为 false
  21. valid = false;
  22. }
  23. }
  24. } while (!valid || !(input.equals("q") || input.equals("Q")));
  25. }
  26. }

一个示例运行:

  1. 输入你的年龄,或输入 'q' 退出程序: a
  2. 无效输入
  3. 输入你的年龄,或输入 'q' 退出程序: 12.5
  4. 无效输入
  5. 输入你的年龄,或输入 'q' 退出程序: 14
  6. 你的年龄是 14
  7. 输入你的年龄,或输入 'q' 退出程序: 56
  8. 你的年龄是 56
  9. 输入你的年龄,或输入 'q' 退出程序: q
英文:

I can see mainly two problems in your code:

  1. It lacks a loop to repeat asking for age again. There can be many ways (for, while, do-while) to write a loop but I find do-while most appropriate for such a case as it always executes the statements within the do block at least once.
  2. age is of type, int and therefore it can not be compared with a string e.g. your code, age.equals("q") is not correct. A good way to handle such a situation is to get the input into a variable of type, String and check the value if it should allow/disallow processing it (e.g. trying to parse it into an int).

Note that when you try to parse a string which can not be parsed into an int (e.g. "a"), you get a NumberFormatException which you need to handle (e.g. show an error message, change some state etc.).

  1. import java.util.Scanner;
  2. public class Main {
  3. public static void main(String[] args) {
  4. int age;
  5. String input;
  6. Scanner scan = new Scanner(System.in);
  7. boolean valid;
  8. do {
  9. // Start with the assumption that input will be valid
  10. valid = true;
  11. System.out.print("Enter your age, or enter 'q' to quit the program: ");
  12. input = scan.nextLine();
  13. if (!(input.equals("q") || input.equals("Q"))) {
  14. try {
  15. // Try to parse input into an int
  16. age = Integer.parseInt(input);
  17. System.out.println("Your age is " + age);
  18. } catch (NumberFormatException e) {
  19. System.out.println("Invalid input");
  20. // Change the value of valid to false
  21. valid = false;
  22. }
  23. }
  24. } while (!valid || !(input.equals("q") || input.equals("Q")));
  25. }
  26. }

A sample run:

  1. Enter your age, or enter 'q' to quit the program: a
  2. Invalid input
  3. Enter your age, or enter 'q' to quit the program: 12.5
  4. Invalid input
  5. Enter your age, or enter 'q' to quit the program: 14
  6. Your age is 14
  7. Enter your age, or enter 'q' to quit the program: 56
  8. Your age is 56
  9. Enter your age, or enter 'q' to quit the program: q

huangapple
  • 本文由 发表于 2020年10月17日 05:33:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64396673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定