2012-07-31 3 views
-4

가능한 중복 : 내가가 추가 될 입력 한 모든 숫자를 원하는
Taking average of user input number자바 루프를 중지

for (int n1 = in.nextInt(); n1 >= 0; n1 = in.nextInt()) 
    { 
      int total = 0; 
      int count = 0; 

      while (n1 >= 0) 
      { 
        n1 = in.nextInt(); 
        total = total + n1; 
        count = count + 1; 

      } 
      out.println(total); 
      out.println(count); 
    } 

이 코드가 정확한지? 마지막 2 개의 입력 만 추가합니다. 사용자가 음수를 입력 할 때까지 계속 루프를 유지 한 다음 루프를 멈추고 내 총계와 횟수를 출력합니다. 다음과 같이

Scanner in = new Scanner(System.in); 
Printstream out = System.out; 
+0

정확히 달성하기를 원하십니까? 왜 하나의 while 루프에서 그것을 할 수 없습니까? –

+7

ㅎ, 이전의 [이것을 요약하는 의사 코드] (http://stackoverflow.com/a/11732204/851273)는 충분하지 않았습니다. –

+0

Jon Lin의 위의 링크는 과제와 비슷한 질문처럼 보입니다. 위 링크에서 언급 한 의사 코드로 구현해보십시오. – hungr

답변

2
int total = 0; 
int count = 0; 

while (true) { 
    int n = in.nextInt(); 
    if (n < 0) 
     break; 
    total += n; 
    count ++; 
} 
out.println(total); 
out.println(count); 
0

코드는해야한다.

int total = 0; 
int count = 0; 
int n1; 

try 
{ 
    while((n1=Integer.parseInt(in.nextLine()))>=0) 
    { 
     total = total + n1; 
     count = count + 1; 
    } 
} 
catch(Exception e) 
{ 
    System.out.println(e.toString()); 
} 

out.println("Total  = "+total); 
out.println("Count  = "+count); 

Format df=new DecimalFormat("#.##"); 
out.println("Average = "+df.format((double)total/count)); 
관련 문제