2013-09-03 3 views
0

정수 (음수 및 양수)를 배열에 추가하려면 연습 문제를 내 교과서에서하고 있습니다. 나는 사용자가 배열에 숫자를 입력하는 것을 끝내기 전에 끝내기를 원한다.배열에 정수를 입력하고 한계에 도달하기 전에 입력을 종료합니다.

내가 가지고 올 한 일이 있습니다 :

사용자가 문자열에 저장되어있는 번호를 입력합니다. keepLooping이 true이고 인덱스가 < 인 경우 배열의 크기입니다. 그것은 토큰으로 토큰을 구문 분석하고 문자열을 int 배열에 배치합니다.

이 작업을 수행하는 쉬운 방법이 있어야합니다 나는 내 코드가 작동을 얻을 수없는, 어떤 도움이 많이 주시면 감사하겠습니다 :

// Create Objects to use in program 
    Scanner keyboard = new Scanner(System.in); 
    int[] arrayOfNumbers = new int[50]; 


    // Prompt for input 
    System.out.println("Enter upto 50 integers separated by a space."); 
    System.out.println("Type x to signal no more integers to enter."); 

    int index = 0; 
    boolean keepLooping = true; 

    while (index < arrayOfNumbers.length && keepLooping) { 
     String numToAdd = keyboard.nextLine(); 

     if (numToAdd.equals("x") || numToAdd.equals("X")) { 
      keepLooping = false; 
     } 

     if (!numToAdd.equals("x") || !numToAdd.equals("X")) { 
      arrayOfNumbers[index] = Integer.parseInt(numToAdd); 
     } 
    } 

    // DEBUG, Print Array 
    for (int k=0; k < arrayOfNumbers.length; k++) { 
     System.out.println(arrayOfNumbers[k]); 
    } 
+8

'절대 변경 index'. –

+0

그리고 ** 오류 ** 무엇입니까? –

+1

while 루프에서 인덱스 ++ 증가 with – newuser

답변

2

를 사용하여 프로그램 단계별 디버깅하는 경우 (예 : 스테핑 Eclipse에서 F6)를 사용하면 index의 값이 변경되지 않는다는 것을 알았을 것입니다. 빠른 수정은 다음과 같습니다

while (index < arrayOfNumbers.length && keepLooping) { 
    String numToAdd = keyboard.nextLine(); 

    if (numToAdd.equals("x") || numToAdd.equals("X")) { 
     keepLooping = false; 
    } 

    if (!numToAdd.equals("x") || !numToAdd.equals("X")) { 
     arrayOfNumbers[index] = Integer.parseInt(numToAdd); 
    } 

    index++; 
} 


그러나 물론

이 단지 충전-의 배열 문제를 해결합니다. 그런 다음 우려 사항을 프로그래밍하는 데있어 우수 사례가 제공됩니다.이 내용은 나머지 답변에서 모두 다루고 있습니다. 루프 밖으로

0
int index = 0; 
boolean keepLooping = true; 

while (index < arrayOfNumbers.length && keepLooping) { 
    String numToAdd = keyboard.nextLine(); 

    if (numToAdd.equalsIgnoreCase("x")) { // Use EqualsIgnoreCase to shorten it 
     keepLooping = false; 
    } else { // Use an else statement instead of evaluating the inverse 
     arrayOfNumbers[index] = Integer.parseInt(numToAdd); 
    } 
    index++; // Increment the index to avoid eternal loop and actually fill the array 
} 
2
당신은 for 루프 조금 단순화 할 수

break 종료합니다 :

for (int index = 0; index < arrayOfNumbers.length; ++index) { 
    String numToAdd = keyboard.nextLine(); 

    if (numToAdd.equals("x") || numToAdd.equals("X")) { 
    break; 
    } 
    arrayOfNumbers[index] = Integer.parseInt(numToAdd); 
} 
관련 문제