[英]How many times a number occurs
I need to write a program that reads an array of ints and an integer number n .我需要编写一个程序来读取一个整数数组和一个 integer 数字n 。 The program must check how many times n occurs in the array.
程序必须检查n在数组中出现了多少次。
Input:输入:
The first line contains the size of the input array.第一行包含输入数组的大小。
The second line contains elements of the array separated by spaces.第二行包含由空格分隔的数组元素。
The third line contains n.第三行包含 n。
Output: Output:
The result is only a single non-negative integer number.结果只有一个非负 integer 数字。
My code:我的代码:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
int n = scanner.nextInt();
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int counter = 0;
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);
}
}
Test input:测试输入:
6
1 2 3 4 2 1
2
My result: 1我的结果: 1
My question is why int n = scanner.nextInt();
我的问题是为什么
int n = scanner.nextInt();
read "1".读“1”。 It should "2".
它应该是“2”。
Reading the n variable was in the wrong place.读取n变量是在错误的地方。 The solution:
解决方案:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int counter = 0;
int n = scanner.nextInt();
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);
}
}
You should read n after you read the array like so:您应该在读取数组后读取 n ,如下所示:
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int n = scanner.nextInt();
int counter = 0;
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.