如何在Java中获取扫描仪以读取字符串? [英] How do I get the Scanner in java to read a string?
本文介绍了如何在Java中获取扫描仪以读取字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当用户输入q时,如何退出程序? 扫描仪有问题吗?
How would I get my program to quit when the user enters q? Is there something wrong with the scanner?
我的代码
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);
}
}
推荐答案
我在您的代码中主要看到两个问题:
I can see mainly two problems in your code:
- 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 finddo-while
most appropriate for such a case as it always executes the statements within thedo
block at least once. 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 anint
).
请注意,当您尝试解析无法解析为int
(例如"a"
)的字符串时,会得到一个需要处理的NumberFormatException
(例如,显示错误消息,更改某些状态)等).
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.).
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
这篇关于如何在Java中获取扫描仪以读取字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文