gpt4 book ai didi

java - 数组包含该值多少次?

转载 作者:行者123 更新时间:2023-12-01 16:46:18 25 4
gpt4 key购买 nike

这是一个简单的程序,用于查找输入 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 方法应该可以完成这项工作,但它没有。
我期望得到什么:

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(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;
//^^^^^^^^

}

关于java - 数组包含该值多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49958163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com