2016-09-16 9 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

Elliott氏によると、メソッドを呼び出すことで実際にデータを処理しているわけではありません。あなたは何をしようとしているかに応じてそれを使用しなければなりません。

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

関連する問題