这是一个简单的程序,用于查找输入x值是否在数组中 用户在数组中键入数字,之后键入一个数字,以计算此数字在数组中重复多少次。 我有什么:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] mas = new int[5];
for (int i = 0; i < mas.length; i++) {
System.out.print("Input of mas["+i+"]: ");
int n = sc.nextInt();
}
valueX(mas);
for (int i = 0; i < 10000; i++) {
System.out.println("Would you like to continue (1=yes, 0=no)?");
int n = sc.nextInt();
if (n==1) {
valueX(mas);
}
if (n==0) {
System.out.println("Program terminated");
sc.close();
break;
}
}
}
public static void valueX(int mas1[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Input x: ");
int x =scanner.nextInt();
int count =0;
for (int i = 0; i < mas1.length; i++) {
if (x==mas1[i]) {
count++;
}
}
System.out.println("Value "+x+" appears "+count+" time(s) in the array.");
}
valueX metod应该做这项工作,但事实并非如此 我希望得到什么:
Input of mas[0]: 2
Input of mas[1]: 2
Input of mas[2]: 3
Input of mas[3]: 4
Input of mas[4]: 2
Input x: 2
Value 2 appears 3 time(s) in the array.
但是我的代码做了什么:
Input of mas[0]: 2
Input of mas[1]: 2
Input of mas[2]: 3
Input of mas[3]: 4
Input of mas[4]: 2
Input x: 2
Value 2 appears **0** time(s) in the array.
你能找到错误吗?
答案 0 :(得分:5)
您没有将输入值存储在数组中,因此您的数组具有所有0
(默认值int
)值,因此问题
int[] mas = new int[5];
for (int i = 0; i < mas.length; i++) {
System.out.print("Input of mas["+i+"]: ");
int n = sc.nextInt();
mas[i] = n;
//^^^^^^^^
}