2014-11-28 1 views
1

그래, 내가 배열 인벤토리 프로그램의 일부분 일 뿐이므로 사용자가 잘못된 번호를 입력했을 때 번호를 다시 입력하라는 메시지가 표시되는 while 루프는 실행되지 않습니다. 잘못된 번호를 입력하면 프로그램이 종료됩니다 ... 나는 몇 가지 방법을 시도했지만 둘 다 작동하지 않습니다. 이것은 내가 지금 어디에 있는지, 어떤 아이디어입니까 ??Java 프로그램 루프가 사용자를 실행하고 프롬프트하지 않습니까?

감사합니다.

public class InventorySystem { 

    public static void main(String[] args) { 
     String[] newItemInfo = new String[1000]; 
     String[] itemDescription = new String[1000]; 
     int[] itemPrice = new int[1000]; 
     int choice; 
     boolean isValid; 
     int itemChoice; 

     Scanner inputDevice = new Scanner(System.in); 
     System.out.println("*****Raider Inventory System*****"); 
     System.out.println("1. Enter a new item"); 
     System.out.println("2. View Item Information"); 
     System.out.println("3. View a list of all items"); 
     System.out.println("9. End Program\n"); 
     System.out.println("Please enter your selection: "); 
     choice = inputDevice.nextInt(); 

     if (choice == 1 || choice == 2 || choice == 3 || choice == 9) { 
      isValid = true; 
     } else { 
      isValid = false; 
     } 

**  while (isValid = false) { 
      System.out.println("Invalid entry, please enter either 1, 2, 3, or 9 for menu options."); 
**  } 

     for (int x = 0; x < 1000; ++x) { 
      if (choice == 1) { 
       System.out.println("Please enter the name if the item: "); 
       newItemInfo[x] = inputDevice.nextLine(); 
       System.out.println("Please enter the item description: "); 
       itemDescription[x] = inputDevice.nextLine(); 
       System.out.println("Please enter item price: "); 
       itemPrice[x] = inputDevice.nextInt(); 
      } 
     } 

     if (choice == 2) { 
      System.out.println("***Show item Description***"); 
      System.out.println("0. "); 
      System.out.println("please enter the item number ot view details: "); 
      itemChoice = inputDevice.nextInt(); 
     } 

     if (choice == 3) { 
      System.out.println("****Item List Report****"); 
     } 

     if (choice == 9) { 
      System.exit(0); 
     } 
    } 
} 

답변

1

while (isValid = false)하지 마십시오. 거짓으로 설정하고 있습니다!

대신 while (isValid == false)을하지 않는다, 또한

while (!isValid) { 

} 

을 - 그 추한 코드입니다.

다음으로 루프 내에서 isValid를 변경하십시오.

while (!isValid) { 

    // get input from user in here 

    // test input and check if is valid. If so, set isValid = true; 

    // something must set isValid to true in here, else it will 
    // loop forever  
} 

그렇지 않으면 무한 루프에 빠질 수 있습니다. 여기서 배워야 할 교훈은 마치 뇌에서 실행하는 것처럼 정신적으로 코드를 통과하는 것입니다. 이렇게하면 논리 오류를 발견 할 수 있습니다. 당신의 라인

while(isValid = false) 

=에서

+0

코드에 따라 op 코드는 무한 루프가됩니다. –

+0

@KickButtowski : 알아요. 그래서 그는 루프 내부에서 isValid를 변경한다고 제안한 것입니다. –

2

은 당신이하지 생각하지 않습니다. Java에서는 =이라는 단일 문자는 을 의미하고 오른쪽의 표현식은 왼쪽의 변수에 지정합니다. 그것은 이 아니고은 양면을 비교하는 것을 의미합니다.

그래서 오히려이 작성해야 :

while (isValid == false) 

참고 이중 ==합니다. 이 코드는 작동하지만 더욱 아름답게 쓸 수 있습니다 :

while (!isValid) 

!하지을 의미한다.

관련 문제