尝试编写用户输入本周费用的程序。 问题在于我希望程序在输入不可接受的输入时重新询问用户。我想出了如何检测负值,但在尝试捕获输入不匹配异常时(如果输入了字符或字符串),循环只是无限地运行,要求“星期一费用:” 我该怎样做才能让用户有机会回答?我试了一下;但是那个do while循环也爆发了,我不想要。
到目前为止,这是我的代码:
import java.util.Scanner;
public class BarGraph{
public static void main (String[] args){
Scanner myScanner;
myScanner = new Scanner(System.in);
double mon, tues, wed, thurs, fri, sat, sun;
do{
try{
System.out.print("Expenses for Monday: ");
mon = myScanner.nextDouble();
}catch( Exception e){
mon = -1;
}
}while(mon<0);
System.out.println(mon);
}
}
感谢您的帮助
答案 0 :(得分:2)
对nextDouble()
的来电不会消耗double
中的非Scanner
。你需要像
if (myScanner.hasNextDouble()) {
mon = myScanner.nextDouble();
} else {
System.out.printf("%s is not a double.%n", myScanner.next());
}
另外,我建议您将该逻辑提取到方法中。像,
static double getExpensesForDay(Scanner scanner, String day) {
while (true) {
System.out.printf("Expenses for %s: ", day);
System.out.flush();
if (scanner.hasNextDouble()) {
return scanner.nextDouble();
}
System.out.printf("%s is not a double.%n", scanner.nextLine());
}
}
然后你可以称之为
public static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
double mon = getExpensesForDay(myScanner, "Monday");
double tues = getExpensesForDay(myScanner, "Tuesday");
double wed = getExpensesForDay(myScanner, "Wednesday");
double thurs = getExpensesForDay(myScanner, "Thursday");
double fri = getExpensesForDay(myScanner, "Friday");
double sat = getExpensesForDay(myScanner, "Saturday");
double sun = getExpensesForDay(myScanner, "Sunday");
// ...
}
答案 1 :(得分:1)
这是因为当扫描程序无法解析double值时,它总是会进入catch块。 这符合你的条件
mon<0
它总是得到-1值,它会导致无限循环 你可能把你的情况弄错了
while(mon>0)
答案 2 :(得分:1)
你可以使用myScanner.nextLine();在开始下一个循环之前转储缓存中所有不必要的字符
import java.util.Scanner;
public class BarGraph {
public static void main(String[] args) {
Scanner myScanner;
myScanner = new Scanner(System.in);
double mon, tues, wed, thurs, fri, sat, sun;
do {
try {
System.out.print("Expenses for Monday: ");
mon = myScanner.nextDouble();
} catch (Exception e) {
mon = -1;
myScanner.nextLine();
}
} while (mon < 0);
System.out.println(mon);
}
}
答案 3 :(得分:0)
替换
mon = myScanner.nextDouble();
以下
mon = Double.parseDouble(myScanner.next());
答案 4 :(得分:0)
您可以尝试以下代码。它将通过整个阵列。您可以根据需要添加更多验证。
import java.util.Scanner;
public class BarGraph
{
public static void main(String[] args)
{
System.out.println("Welcome to Expenses Program: " + "\n");
week();
}
public static void week()
{
Scanner myScanner;
myScanner = new Scanner(System.in);
String [] day = new String[] {"mon", "tues", "wed", "thurs", "fri", "sat", "sun"};
for (String days : day)
{
System.out.println("Expenses for " + days + ":");
float exp = myScanner.nextFloat();
}
}
}