大家好抱歉我是Java的新手,这是我班上的练习之一。 我应该询问用户输入5个数字,然后比较它们是否与之前输入的数字相同。 到目前为止,这些是我的代码,但我无法使其工作。 感谢。
import java.util.Scanner;
public class Source {
private static int num = 0;
private static int[] enterednum = new int[5];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(int count = 0; count < enterednum.length; count++) {
System.out.println("Enter a number.");
num = input.nextInt();
compare(enterednum);
}
System.out.println("These are the number you have entered: ");
System.out.println(enterednum);
}
public static void compare(int[] enterednum) {
for(int count = 0; count < 6; count++)
if(num == enterednum[count])
System.out.println("The number has been entered before.");
}
}
答案 0 :(得分:1)
你可能想要这样的东西:
import java.util.Scanner;
public class Source
{
private static int enterednum[]=new int[5];
public static void main(String args[])
{
int num=0; // make this local variable since this need not be class property
Scanner input = new Scanner(System.in);
for(int count=0;count<enterednum.length;count++)
{
System.out.println("Enter a number.");
num = input.nextInt();
compare(num, count);
enterednum[count] = num; // store the input
}
System.out.println("These are the number you have entered: ");
// print numbers in array instead the array
for(int count=0;count<enterednum.length;count++)
{
System.out.println(enterednum[count]);
}
}
// change the method signature to let it get the number of input
public static void compare(int num, int inputcount)
{
for(int count=0;count<inputcount;count++)
{
if(num==enterednum[count])
System.out.println("The number has been entered before.");
}
}
}
答案 1 :(得分:0)
You can do this way if you need.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Source {
public static void main(String[] args) throws IOException {
// I used buffered reader because I am familiar with it :)
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create a Set to store numbers
Set<Integer> numbers = new HashSet<>();
for (int i = 0; i < 5; i++) {
System.out.print("Enter a number: ");
String line = in.readLine();
int intValue = Integer.parseInt(line);
// You can check you number is in the set or not
if (numbers.contains(intValue)) {
System.out.println("You have entered " + intValue + " before");
} else {
numbers.add(intValue);
}
}
}
}