如何将输入结合在 while循环下?
try {
System.out.println("Keep selecting the ingrients that you want until you press (0)");
int ingrientsID = Integer.parseInt(br.readLine());
while (!"0".equals(ingrientsID )) {
System.out.println("One more?");
ingrientsID = Integer.parseInt(br.readLine());
if (ingrientsID == 0) {
break;
}
}
答案 0 :(得分:0)
您正尝试执行以下操作:
int ingrientsID = Integer.parseInt(br.readLine());
while (ingrientsID != 0) {
System.out.println("One more?");
ingrientsID = Integer.parseInt(br.readLine());
// no breaks needed for ingrientsID == 0 as loop condition will
// automatic stop iterate for ingrientsID == 0
// do more stuffs
}
答案 1 :(得分:0)
boolean flag=true;
System.out.println("Keep selecting the ingrients that you want until you press (0)");
int ingrientsID = 0,temp=0;
while (flag) {//until user enters 0
temp=Integer.parseInt(br.readLine());
ingrientsID += temp;//to sum each input that you type
if (temp==0) {//is user enters 0 then
flag=false;
}
else
System.out.println("One more?");
}
System.out.println("sum: "+ingrientsID);//final result
答案 2 :(得分:0)
以下是代码和一些评论。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
//import java.util.Scanner;
public class Ingredients {
public static void main(String [] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//or Scanner scan = new Scanner(System.in);
int ingredientID=0;
int sumOfIngredients=0;
System.out.println("Keep selecting the ingrients that you want until you press (0)");
//use do while to make it run at least once
do{
//get input, add to sumofIngredients
ingredientID=Integer.parseInt(br.readLine());
//or ingredientID= scan.nextInt(); if you're using scanner
//add the ingredient
sumOfIngredients+=ingredientID;
//I don't think you need to ask "one more?".
//You have given the instruction (to keep selecting the ingredients till the user presses 0 )
}while(ingredientID!=0);
//print the ingredients!
System.out.println("sum of ingredients: "+ sumOfIngredients);
}
}
请不要忘记下次使用“作业”标签;)