2012-10-21 4 views
1

왜 루프에서 벗어나는 지 알 수 없습니다. 여기 내 프로그램이 있습니다 :Java에서 while 루프가 깨어짐

public static void main(String[] args) { 

    Scanner input = new Scanner (System.in); 

    double tution, rate, r, t, realpay, multiply, start; 
    start = 0; 

    while(start != -1) 
    { 
     System.out.print("Press 1 to start, -1 to end: "); 
     start = input.nextDouble(); 

     System.out.print("Please enter the current tution fee for the year: "); 
     tution = input.nextDouble(); 

     System.out.print("Enter in the amount of interest: "); 
     rate = input.nextDouble(); 

     r = 1 + rate; 

     System.out.print("Please enter the number of years: "); 
     t = input.nextDouble(); 
     multiply = Math.pow(r,t); 
     realpay = tution * multiply; 

     System.out.println("the cost of your tution fee: " + realpay); 

     if (start == -1) 
     { 
      break; 
     } 
    } 
} 

당신은 저에게 뭐가 잘못 됐는지 말해 줄 수 있습니까?

답변

7

당신은 시작 읽은 후 휴식을 이동해야

start = input.nextDouble(); 
if (start == -1) { 
    break; 
} 

그렇지 않은 프로그램을 계속하고 사용자가 입력 한 경우에도 -1

4

테스트를 루프의 끝에서 중단됩니다

if (start == -1) { 
    break; 
} 

은 즉시 완료해야합니다.

start = input.nextDouble(); 

실제로 루프의 본문을 실행 한 후에 만 ​​while 루프에서 벗어났습니다.

startdouble으로 선언하고 ==으로 값을 테스트하여 가능한 문제점을 인식하십시오. 그러한 변수의 경우에는 바람직하게는 int으로 선언해야합니다.

+0

죄송합니다. 나는 AmitD에 의한 이전의 답을 보지 못했다. –

+0

정말 고마워요! –

0

If 블록을 while 루프 외부로 이동하십시오. -1을 읽었을 때 if 블록에 while 루프가 들어가기 때문에 깨지지 않을 것입니다.

외부로 이동하면 깨질 수 있습니다.

관련 문제