[英]i want to display every number entered in my while loop.so how can i do this
must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows eg say the user enters 3 numbers 10 + 12+ 3=25必须创建一个 java 应用程序,该应用程序将确定并显示用户输入的数字总和。总和必须在用户想要的时间内进行。当程序结束时,总和必须显示如下,例如,假设用户输入 3 个数字 10 + 12+ 3=25
and you must use a while loop你必须使用一个 while 循环
Here's a function to do just that.这是一个 function 来做到这一点。 Just call the function whenever you need.
只需随时拨打 function。
Ex: System.out.println(parseSum("10 + 12+ 3"))
→ 25
例如:
System.out.println(parseSum("10 + 12+ 3"))
→ 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. while 循环本质上是一个 for 循环。 Is there a specific reason why you needed it to be a while loop?
是否有特定原因需要它成为 while 循环?
There is a lot of ways to achieve this.有很多方法可以实现这一点。 Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
这是一个可以改进的代码示例(例如,如果用户未输入数字,则捕获 InputMismatchException)。 Please for the next time, post what you have tried and where you stuck on.
下次请发布您尝试过的内容以及坚持的地方。
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.