[英]i want to display every number entered in my while loop.so how can i do this
必須創建一個 java 應用程序,該應用程序將確定並顯示用戶輸入的數字總和。總和必須在用戶想要的時間內進行。當程序結束時,總和必須顯示如下,例如,假設用戶輸入 3 個數字 10 + 12+ 3=25
你必須使用一個 while 循環
這是一個 function 來做到這一點。 只需隨時撥打 function。
例如: 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;
}
while 循環本質上是一個 for 循環。 是否有特定原因需要它成為 while 循環?
有很多方法可以實現這一點。 這是一個可以改進的代碼示例(例如,如果用戶未輸入數字,則捕獲 InputMismatchException)。 下次請發布您嘗試過的內容以及堅持的地方。
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.