2014-10-06 2 views
-3

저는 java를 처음 사용하고 다차원 배열 검색 방법을 쓰려고했습니다. 내 코드는 찾은 요소에 대해 작동하지만 일치하지 않는 요소를 입력하면 아무 것도 출력하지 않습니다. 제 코드에 어떤 문제가 있는지 말해주세요. 지역 변수는 사용하기 전에 초기화해야하기 때문에배열 요소 검색

import java.util.Scanner; 
public class ArraySearch { 
public static void main (String[] args){ 
    Scanner input = new Scanner(System.in); 

    //lets create the array 
    int [] [] arrayOfInts = {{1, 2,3,4}, {5,6,7,8},{9,10,11,12}}; 

    //create search variables 
    System.out.println("Enter the key number to search for in the array: "); 
    int key = input.nextInt(); 
    boolean foundIt; 

    //perform search using a for loop 
    for (int i = 0; i <arrayOfInts.length; i++){ 
     for (int j = 0; j <arrayOfInts[i].length; j++){ 
      if (arrayOfInts[i][j] == key) { 
       foundIt = true; 

       if (foundIt) { 
        System.out.println("found " + key + " at row " +i+ " column " +j); 

       } else { 
        System.out.println(key + "is not in the array"); 
       } 
      } 
     } 
    } 
} 
} 
+1

@ 부울 값은 'null'일 수 없습니다. 초기화되지 않았지만 'null'이 아닙니다. – khelwood

+0

또한 요소를 찾았 으면 루프에서 벗어날 수 있습니다. 반복 할 필요가 없습니다. –

+0

올바른 코드 스타일 (형식)을 사용하십시오. 나는 [Google Java Style] (https://google-styleguide.googlecode.com/svn/trunk/javaguide.html)을 좋아하지만 Google에서도 다른 스타일을 찾을 수 있습니다. 적절한 스타일을 사용하면 코드에서 많은 실수를 쉽게 감지 할 수 있습니다. 또한 일반적인 가독성을 높입니다. – brimborium

답변

2

당신은 거짓에 부울을 초기화한다 : 키가 발견되지 않은 경우 당신이 그것을 액세스 할 때

boolean foundIt = false; 

그렇지 않으면, foundIt가 초기화되지 않은 것 if 조건에서.

foundIt을 초기화하지 않아야 합병증 오류 (The local variable foundIt may not have been initialized)가 발생했지만이 오류를 숨기는 또 다른 오류가있었습니다. 출력을 인쇄하는 if 문은 for 루프 밖에 있어야합니다. 이제는 일치하는 것을 발견하는 조건 안에 있으므로 일치하는 것을 찾은 경우에만 평가됩니다.

+2

Java에서'boolean'의 기본값은'false'입니다. – brimborium

+0

@brimborium 아직 컴파일 할 코드를 초기화해야합니다. – khelwood

+0

@brimborium 그것은 반원들에게만 사실입니다. 지역 변수를 초기화해야합니다. – Eran

1

브라케팅이 잘못되었습니다. if-else 문

if (foundIt) { 
    System.out.println("found " + key + " at row " +i+ " column " +j); 

} else 
     {System.out.println(key + "is not in the array"); 
} 

for 루프를 검사합니다.

if (arrayOfInts[i][j] == key) { 

각 일치에 대한 메시지를 표시하려면 for 루프 내에 있어야합니다. 그러나 당신은 루프

if (arrayOfInts[i][j] == key) { 
    System.out.println("found " + key + " at row " +i+ " column " +j); 

의에서 if 문 내부에 println 메시지를 두어야 그리고 키가 발견되지 않을 때 다른 메시지를 인쇄 할 수 있지만, 이것은 마지막에 수행해야합니다. 부울을 처음부터 초기화해야합니다!

boolean foundIt = false; 
... 
//at the end 
if(!foundIt) { 
    System.out.println("found " + key + " at row " +i+ " column " +j); 
} 
+1

@Paul 아니요 for의 for 내부에만 인쇄됩니다. 따라서 if 문에서 일치 항목이 발견 된 경우에만 foundIt이 true로 설정됩니다. – Juru

+1

아 맞습니다. 코드 검토로 인해 드라이브가 잘못되었습니다. 죄송합니다 –

1

코드를 다음과 같이 변경할 수 있습니다. 코드에는 많은 문제가 있습니다. 당신은 당신이 경우에 그래서 당신은 끝에 다른 분기를 붙여 그냥 원하는 요소를 찾아 수익을 추가 foundIt

Scanner input = new Scanner(System.in); 
    //lets create the array 
    int[][] arrayOfInts = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; 
    //create search variables 
    System.out.println("Enter the key number to search for in the array: "); 
    int key = input.nextInt(); 
    boolean foundIt = false; 
    for (int i = 0; i < arrayOfInts.length; i++) { 
     for (int j = 0; j < arrayOfInts[i].length; j++) { 
      if (arrayOfInts[i][j] == key) { 
      System.out.println("found " + key + " at row " + i + " column " + j); 
      // if found it will change the foundIt to true 
      foundIt = true; 
      } 
     } 
    } 
    if (!foundIt) { 
     System.out.println(key + "is not in the array"); 
    } 
+0

요소가 배열에서 발견되면 왜 깨지지 않습니까? –

+1

@SaiAvinash 예, 우리는 헤어질 수 있습니다. 그러나 중복 요소가 있다면 어떻게 될까요? 그들도 찾아야합니까? –

+0

나는 부서지지 않을 것이다, 행과 열을 표시하고 모든 출력을 고유하게 만든다. 만약 당신이 그걸 발견했다는 것을 알고 싶다면 더 빠를 수 있습니다. 그러나이 구현은 모든 일치를 보여주기 때문에 더욱 완벽합니다. – Juru

0
// perform search using a for loop 
    for (int i = 0; i < arrayOfInts.length; i++) { 
     for (int j = 0; j < arrayOfInts[i].length; j++) { 
      if (arrayOfInts[i][j] == key) { 
        System.out.println("found " + key + " at row " + i + " column " 
          + j); 
        return;   
      } 
     } 
    } 
    System.out.println(key + "is not in the array"); 

초기화/잘라해야합니다, {}의 올바른 순서를 확인해야합니다 고리.

+0

foundIt을 true로 설정 했으므로 내부 if 절이 필요하지 않습니다. – Marco

0

귀하의 System.out에이 경우 블록

if (arrayOfInts[i][j] == key) 

당신이 뭔가를 찾을 수없는 경우이 그래서 더 출력이없는 경우에만 내부

나는이 방법으로 그것을 할 것

:

... 
for (int i = 0; i <arrayOfInts.length; i++){ 
    for (int j = 0; j <arrayOfInts[i].length; j++){ 
     if (arrayOfInts[i][j] == key) { 
      foundIt = true; 
      // Tell where you found it 
      System.out.println("found " + key + " at row " +i+ " column " +j); 
     } 
    } 
} 
// After all check whether you found something anytime 
if(!foundIt){ 
    System.out.println(key + "is not in the array"); 
} 
... 
0

인쇄 문 if (foundIt) ... else 블록이 if (arrayOfInts [i] [j] == 키) 블록 내에 있기 때문입니다. 즉, int가 발견되지 않으면 코드가 인쇄 된 위치를 확인하면 해당 내부로 들어 가지 않습니다. "찾을 수 없음"을 끝까지 이동할 수 있습니다. 예 :

boolean foundIt = false; 
    // perform search using a for loop 
    for (int i = 0; i < arrayOfInts.length; i++) 
    { 
     for (int j = 0; j < arrayOfInts[i].length; j++) 
     { 
      if (arrayOfInts[i][j] == key) 
      { 
       foundIt = true; 
       System.out.println("found " + key + " at row " + i + " column " + j); 
      } 

     } 
    } 
    if (!foundIt) 
    { 
     System.out.println(key + "is not in the array"); 
    } 

먼저 foundIt을 false로 초기화하는 것을 잊지 마십시오.

0

내 권장 해결책은 다음과 같습니다

bool foundit=false; 

for (int i = 0; i <arrayOfInts.length; i++){ 
     for (int j = 0; j <arrayOfInts[i].length; j++){ 
      if (arrayOfInts[i][j] == key) 
      { 
      foundIt = true; 
      break; 
      System.out.println("found " + key + " at row " +i+ " column " +j); 
      } 
     } 
} 

if(!foundit) 
{ 
system.out.println("Key not found in the array.") 
} 
0

이 작동 :

import java.util.Scanner; 
public class ArraySearch { 
public static void main (String[] args){ 
    Scanner input = new Scanner(System.in); 

    //lets create the array 
    int [] [] arrayOfInts = {{1, 2,3,4}, {5,6,7,8},{9,10,11,12}}; 

    //create search variables 
    System.out.println("Enter the key number to search for in the array: "); 
    int key = input.nextInt(); 

    //perform search using a for loop 
    for (int i = 0; i <arrayOfInts.length; i++){ 
     for (int j = 0; j <arrayOfInts[i].length; j++){ 
      if (arrayOfInts[i][j] == key) { 
       System.out.println("found " + key + " at row " +i+ " column " +j); 
       return; 
      } 
     } 
    } 
    System.out.println(key + " is not in the array"); 
} 
} 

이유 : 운영자 요소가 배열에있는 경우에만 실행 if (arrayOfInts[i][j] == key) {}의 명령, 그래서 필요 없다 boolean foundIt;을 사용하십시오. return을 사용하여 클래스 실행을 끝내십시오. 우리가 원하는 것을 발견했기 때문입니다. System.out.println(key + " is not in the array"); 라인은 2 사이클 후에 있어야하므로 이전에 2 차원 어레이의 각 요소를 검사 한 경우에만 작동합니다.