2016-09-16 2 views
-1

주어진 프로그램이 컴파일되지만 원하는 방식으로 실행되지 않습니다. 나는 내가 작성한 방법을 적용하지 않는다고 생각한다. 어떤 아이디어? 엘리엇처럼내 프로그램이 내가 작성한 방법을 사용하지 않는 이유는 무엇입니까?

import java.util.Scanner; 
public class Assignment_1_q1 { 

    static Scanner input = new Scanner(System.in); 
    public static int i; 
    public static int counter; 
    public static int n; 

    //main method 
    public static void main(String[] args) { 

     System.out.println("Enter n's value: "); 
     n = input.nextInt(); //Prompts the user to input the integer number n. 
     int[] table = new int[10]; //Create an array of size 10. 
     getArrayValues(table); //Calls the first method 
     matchCriteria(table, counter, n); //Calls the second methods 
     System.out.println("There is "+ n +"numbers greater than n!"); //display the result. 

    } 
    //the first method to input array values from the user, 
    //allows nonnegative numbers only to be stored into the array. 
    public static int[] getArrayValues(int table[]){ 

     while (table[i] < 0) 
     System.out.println("Pleas try a nonnegative number!"); 

     for (int i = 0; table[i] < table.length; i++){   
      System.out.println("Enter an array value: "); 
      table[i] = input.nextInt();   
     } 
     return table; 
    } 
    // the second method determines how many of array values are greater than the value of n. 
    public static int matchCriteria(int array[], int counter, int n){ 

     counter = 0; 

     for(int i = 0; i < array.length && i > n;) { 
      if (i > n) counter++; 
     } 
     return counter; 
    } 

} 
+0

당신은 저장 (또는 사용)하여 메소드를 호출의 결과가되지 않습니다. –

답변

-1

은 당신이 정말로 메소드를 호출의 데이터로 작업을 수행하지 않는 말했다. 당신은 당신이하려는 일에 따라 그것을 사용해야합니다.

0

당신은 같은 테이블에 getArrayValues ​​()의 결과를 저장해야합니다

table = getArrayValues(table); 

int newcounter = matchCriteria(table, counter, n); 

그 위에, 당신은 루프 테이블 [I]를 사용하는 대신 내가의 선택 기준에 깨닫는다. while 루프에서 그것을 할 더 나은 것 :

같은 리팩토링 고려 :

for (int i = 0; i < table.length; i++){   
     System.out.println("Enter an array value: "); 
     table[i] = input.nextInt(); 
     while(table[i] < 0) { 
      System.out.println("Pleas try a nonnegative number!"); 
      table[i] = input.nextInt(); 
     } 
    } 
+0

위대한, 출력에 도움이되었지만 여전히 사용자가 음수를 입력하도록 허용합니다. –

+0

괜찮은 @KhaledBoustati는 사용자가 음수를 입력 할 수 있어야하지만 양수를 입력 할 때까지 테이블에 저장하지 않습니다. . 음수 입력에서 프로그램을 중단하려면 예외 발생을 고려하십시오. – jmc

관련 문제