2017-03-31 10 views
1

ユーザーが複数の値を入力し、入力を中止する場合は-1を入力するループを作成します。私はそれがセンチネルを使用する必要があることを知っているが、私はどのようにわからない。Java whileループの中に値を追加して、センチネルを使用して停止します

Scanner myInput = new Scanner(System.in); 
int total = 0; 
int count = 0; 

while(values >= 0) 
{ 
    int values; 
    total += values; 
    count ++; 

    System.out.println("Please input your value, type - 1 to stop entering values."); 
    values = myInput.nextInt();  
} 

System.out.println ("The sum of all your values is " + total); 

答えて

0

私はあなたの主な問題はvalueswhileループ内で宣言されていることだと思います。ループの前に宣言を入れてみてください。プットアウト

int values = 0; 
while(values >= 0) 
{ 
    ... 
} 
0
import java.util.Scanner; 
class Demo{ 


    public static void main(String args[]){ 
       java.util.Scanner myInput = new java.util.Scanner(System.in); 

       int total = 0; int count = 0; 
       int values=0; 

       while(values >= 0) 

       { 


         total += values; count ++; 

         System.out.println("Please input your value, type - 1 to stop entering values."); values = myInput.nextInt(); 

       } 

       System.out.println ("The sum of all your values is " + total); 
     } 

} 
0
public static void main(String[] args) { 
    Scanner myInput = new Scanner(System.in); 
    System.out.println("Please input your value, type - 1 to stop entering values."); 
    int values = 0; 
    int total = 0; 

    while (values >= 0) { 
     total += values; 
     values = myInput.nextInt(); 
    } 
    System.out.println("The sum of all your values is " + total); 
    myInput.close(); 
} 

次のようになります:
output

関連する問題