2013-04-12 5 views
1

나는 책상 주문 데이터를 지속적으로 받아들이고 길이가 36 인치 이상이고 적어도 하나의 서랍이있는 오크 책상에 대한 모든 관련 정보를 표시하는 프로그램을 만들어야합니다.루프가 한 번 이상 실행되지 않음

import java.util.*; 

public class MangMaxB 
{ 
    public static void main(String[] args) 
    { 
     Scanner input = new Scanner(System.in); 
     char ans; 
     int orderNum=0, length=0, width=0, numDrawer=0, price=1000; 
     String name; 

     System.out.print("Do you wish to enter Oak " + 
         "desk order data? (y/n)"); 
     ans = input.nextLine().charAt(0); 

     while (ans != 'n') 
     { 
      System.out.print("Enter customer name: "); 
      name=input.nextLine(); 

      System.out.print("Enter order number: "); 
      orderNum=input.nextInt();  

      System.out.print("Enter length and width of Oak desk" + 
         " separated by a space: "); 
      length = input.nextInt(); 
      width = input.nextInt(); 

      System.out.print("Enter number of drawer/s: "); 
      numDrawer=input.nextInt(); 

      if ((length>36)&&(numDrawer>=1)) 
      { 
       if ((length*width)>750) 
       { 
        price+= 250; 
       } 

       price+= (numDrawer*100); 
       price+= 300; 

       System.out.println("\nOak desk order information:\n" 
         + "Order number: " + orderNum + "\n" 
         + "Customer name: " + name + "\n" 
         + "Length: " + length + ", width: " 
         + width + ", surface: " + (length*width) 
         + "\n" + "Number of drawer/s: " + numDrawer 
         + "\nPrice of the desk is P " + price); 
      } 

      else 
      { 
       System.out.println("\nOak desk order isn't over 36 " + 
         "inches long and doesn't have a drawer"); 
      } 

      System.out.print("Any more items? (y/n) "); 
      ans = input.nextLine().charAt(0); 
     } 
    } 
} 

데이터를 입력하고 표시 할 수 있지만 루프이므로 두 번째 시도에서 작동하지 않았습니다. "문자열 색인이 범위를 벗어 : controlStruc.MangMaxB.main에서 java.lang.String.charAt (알 수없는 소스) 에서 0 java.lang.StringIndexOutOfBoundsException"

그것은 "스레드에서 예외"주요 말한다

어떻게 해결할 수 있습니까?

+0

왜'String' 객체를 다루지 않는가? 'String'에서'char'을 얻는 데 진짜 포인트가 없습니다. 어쨌든, 그것은 그것이 작동해야하는 것처럼 나에게 보인다, 당신은 그것이 묻힐 때 당신이 문자를 입력 했습니까? 을 입력했다면을 입력하면'String'의 위치 0에'char'가 없습니다. – Quetzalcoatl

+0

글쎄, 그것은 마치'input.nextLine()'이 루프의 끝에있는 빈 문자열 인 것처럼 보입니다. –

+0

@SamIam 그것은 왜 여기에 진짜 질문입니까? * 빈 문자열입니다. – berry120

답변

0

는 아래와 같이 사용하세요,

System.out.print("Any more items? (y/n) "); 
input = new Scanner(System.in); 
ans = input.nextLine().charAt(0); 

input.nextLine()는 빈 문자열을 반환 beacuse, 그렇게 할 때 0 번째 char 가져 오기 시도 StringIndexOutOfBoundsException input.nextLine() 호출하기 전에 문자열을 얻어야합니다

+0

-1 : 새 스캐너 할당은 불필요한 오버 헤드이므로 여기에서 문제의 실제 원인을 피할 수 있습니다. – berry120

0

그냥 Enter 키를 누르십니까?

ans = input.nextLine().charAt(0); 

은 빈 문자열 일 때이 오류가 발생합니다. 귀하의 예외는 분명히 당신에게 이것을 말하고 있습니다. "nextLine"이 빈 문자열인지 아닌지 확인해야합니다.

+0

어쩌면이 검사는 좋은 습관 일 것입니다. 그러나 이것은 문제가 아닙니다. 문제는 nextInt() 호출 이후로 nextLine()이 항상 (사용자가 올바른 입력을 입력하는 경우) 즉시 반환한다는 것입니다. 스캐너가 정수가있는 행의 끝을 구문 분석하지 못하게합니다. – berry120

+0

예 Enter 키를 누릅니다. 어떻게 해결할 수 있습니까? 고객 이름을 입력하면 오류가 발생합니다. –

+0

아, 감사합니다. @ berry120 –

6

nextInt() 줄 끝을 읽지 않습니다. 바로 다음 정수입니다. 해당 줄의 나머지 부분을 읽으려면 nextInt() 뒤에 nextLine()으로 전화해야합니다.

현재, 그렇게하지 않으므로 마지막 nextLine() 메서드는 정수 뒤에 빈 줄을 읽은 다음 빈 문자열을 즉시 반환하여 예외를 발생시킵니다. 트릭해야 여기 nextLine() 전화를 넣어이 경우

:

System.out.print("Enter number of drawer/s: "); 
numDrawer=input.nextInt(); 
input.nextLine(); //Added nextLine() call 
+0

input.nextLine();을 추가합니까? input.nextInt(); 뒤에 나오는 모든 행에서. ?? –

+0

@DohaKik이 예제에서는 지정한 줄에 추가하는 것만이 필요하다고 생각합니다. – berry120

0

분명히 d에 따라 ocumentaion :

nextLine()-Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

nextInt() - 코드에서 Scans the next token of the input as an int.

그리고 이제부터는 ans = input.nextLine()''char(0)StringIndexOutOfBoundsException에 대한 선도을 반환합니다.

+0

nextLine()에 대한 두 번째 참조가 실제로 nextInt()가 될 것입니까? – berry120

+0

@ berry120 고마워! 나는 같은 것을 편집했다. – abc

관련 문제