java - Java:显示用户输入每个新值后输入的完整唯一值集
问题描述
我需要编写一个“在用户输入每个新值后显示完整的唯一值输入集”的代码。如:
·完整·集合·的·唯一·值·输入·是:↵</p>
唯一·价值·1:·是·100↵</p>
唯一·价值·2:·是·10↵</p>
唯一·价值·3:·是·20↵</p>
我在下面附上了我的代码,并完成了代码,但是,我的最后一行似乎遇到了错误,以产生最后一个“这是第一次输入(用户输入)”和唯一值部分结果唯一值 # 是(用户输入是唯一的并存储在数组中)。最后一行 System.out.println("Unique...) 似乎有错误。任何帮助将不胜感激。
import java.util.Scanner;
import java.util.ArrayList;
public class DisplayUniqueValueInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// creating an ArrayList from user input
ArrayList<Integer> userInputs = new ArrayList<Integer>(5);
// prompt user and store input
int count = 0;
while (true) {
int a = 0;
while(true) {
System.out.print("Enter an integer between 10 and 100:");
a = Integer.parseInt(sc.nextLine());
if (a < 10 || a > 100)
System.out.println("Invalid input\n");
else
break;
}
count++;
if (count == 5)
break;
boolean ifExists = false;
for(int i = 0; i<userInputs.size(); i++) {
if (userInputs.get(i) == a) {
ifExists = true;
break;
}
}
if (!ifExists){
System.out.printf("This is the first time %d has been entered\n", a);
userInputs.add(a);
}
} // end while statement
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < 5; i++) {
System.out.println("Unique Value" + userInputs[i] + "is:" + " ");
}
} // end main method
} // end of class
解决方案
对于最后一个循环,您应该这样做,因为您的数组用于存储唯一数字,对吗?因此,如果唯一编号少于 5 个,您的程序就会中断,为什么不使用 Set 代替呢?
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < userInputs.size(); i++) {
System.out.println("Unique Value" + userInputs.get(i) + "is:" + " ");
}