[英]Can't figure out of how to stop the application when a specific String value match a specific condition
It's my first time posting some topic on this website, and running on a problem that I can't get over it.这是我第一次在这个网站上发布一些主题,并且遇到了一个我无法克服的问题。 The following problem that I'm stunning into is as followed:我令人震惊的以下问题如下:
When the total calculation of the above decimal numbers meets a specific target amount, print: "Congratulations" if not, print:"Calculation error", after they input the string word: "Ready".当上述十进制数的总计算达到特定的目标量时,打印:“Congratulations”,否则打印:“Calculation error”,输入字符串word:“Ready”后。 when a user inputs a string called: "I Quit!", the application will exit and prints: "Quitter".当用户输入名为“I Quit!”的字符串时,应用程序将退出并打印:“Quitter”。
Here is the Java code that I currently have:这是我目前拥有的 Java 代码:
public static void goal(double targetAmount) {
Scanner sc = new Scanner(System.in);
double total = 0;
while (scanner.hasNextDouble()) {
double input= sc.nextDouble();
total += input;
}
String inputString = sc.next();
}
I'm looking forward to see your response.我期待着看到你的回应。 Hope I've formulate my question properly?希望我已经正确地提出了我的问题?
You can use System.exit()
to exit the program.您可以使用System.exit()
退出程序。
case "I Quit!":
System.out.println("Quitter");
System.exit();
I think the problem is the input
you read using scanner.next()
, because scanner.next()
reads the input till the next blank character .我认为这个问题是input
您阅读使用scanner.next()
因为scanner.next()
读取输入,直到下一个空白字符。 Which means it will just read I
when you enter I Quit!
这意味着当您输入I Quit!
时,它只会读取I
I Quit!
. .
Printing the output of the variable input
shows the problem:打印变量input
的输出显示问题:
public static void main(String[] args) {
salarisdoel(100);
}
public static void salarisdoel(double targetAmount) {
Scanner scanner= new Scanner(System.in);
double total = 0;
while (scanner.hasNextDouble()) {
double inputMoney= scanner.nextDouble();
total += inputMoney;
}
String input = scanner.next();
System.out.println(input);//print to check what was read from the console
switch (input) {
case "I Quit!":
System.out.println("Quitter");
break;
case "Ready":
if (total>= targetAmount) {
System.out.println("Congratulations");
} else {
System.out.println("Calculation Error");
}
break;
default:
System.out.println("Something went wrong. Try again!");
break;
}
}
If you use a string without a blank space for quitting (eg "I_Quit!"
) it will work.如果您使用没有空格的字符串退出(例如"I_Quit!"
),它将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.