为什么我的程序不使用我写的方法?
问题描述:
给定的程序编译,但不以我想要的方式运行。我认为这不是应用我写的方法。有任何想法吗?为什么我的程序不使用我写的方法?
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;
}
}
答
就像Elliott说的那样,你实际上并没有对调用方法的数据做任何事情。你必须根据你想要做的事情来使用它。
答
你需要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
您没有储存(或使用)调用你的方法的结果。 –