2011-06-12 3 views
-1

마지막 println에 문제가 있습니다. 이전 문자열이 인쇄 된 횟수를 인쇄하고 모든 숫자를 함께 추가하기를 원합니다. 따라서 사용자가 "3"을 입력하면 3 번 인쇄하고 6 개의 숫자를 합쳐 6을 얻습니다. 내가 어떻게 할 수 있는지 아는 사람 있습니까? 아니면 내가 뭘 잘못하고있는거야?Java 메서드에서 while 루프를 사용하고 추가 기능을 인쇄하는 방법은 무엇입니까?

import java.util.Scanner; 

    public class LoveCS { 
     public static void main(String[] args) { 
      int limit; 
      Scanner scan = new Scanner(System.in); 
      System.out.println("How many times should the string be printed? "); 
      limit = scan.nextInt(); 
      int count = 1; 
      while (count <= limit){ 
       System.out.println(+count+"I love hot chocolate!!"); 
       count++;  
      } 
      sum+=limit; 
      System.out.println("Java printed this message: "+ limit+ " times." + "The sum of the numbers from 1 to " + (count-1) + " is " sum); 

     } 
    } 
+0

신 댕 형식 미안하지만 난 아주 경험입니다 – hvgotcodes

답변

0

합계에 추가하는 위치는 루프 외부에 있으므로 마지막 비트 만 가져옵니다. 루프로 이동하면 작동합니다. 어쨌든 합계는 어디에서 선언하고 있습니까? 대신 while 루프의

+0

물건 : 마지막 줄의 변경을 의미합니다이 사용

. 내가 합계를 어떻게 선언하겠습니까? – Chickadee

+0

나는 + + = limit으로 선언했다. – Chickadee

+0

한계를 "int"로 사용한 것과 같은 방식으로 모든 변수의 타입을 선언해야한다. sum을 사용하려면 루프 앞에 선언 한 다음 루프 내부에서 sum에 count를 추가해야합니다. – Lincoded

0
import java.util.Scanner; 

public class LoveCS { 

    public static void main(String[] args) { 
     int limit; 
     Scanner scan = new Scanner(System.in); 
     System.out.println("How many times should the string be printed? "); 
     limit = scan.nextInt(); 
     int count = 1; 
     int sum = 0; 
     while (count <= limit) { 
      sum += count; 
      System.out.println("I love hot chocolate!!"); 
      count++; 
     } 
     System.out.println("Java printed this message: " + limit + " times." + "The sum of the numbers from 1 to " + (count - 1) + " is " + sum); 
    } 
} 
0

:

int count = 1; 
while (count <= limit) { 
    // code inside loop 
    count++; 
} 

그것은 for 루프를 사용하는 청소기입니다 :

for (int count = 1; count <= limit, count++) { 
    // code inside loop 
} 

덜 코드의를하고 루프를 제어 무엇 분명하게 = 이하 버그.

..."The sum of the numbers from 1 to " + limit + " is"... // change (count - 1) to limit 
관련 문제