我正在尝试让用户为一本书的ISBN输入唯一的值。我能够接收用户输入,它可以很好地填充ArrayList,但是如果用户输入的值已经在ArrayList中,我希望他们收到一条错误消息,并被提示重试。
do{
System.out.print("\n ISBN must be 4 numbers only.\nEnter isbn: ");
isbn = sc.nextLine();
try{
isbnInt = Integer.valueOf(isbn);
}//end try
catch(NumberFormatException nfe){
System.out.println("\nPlease enter integer numbers only.");
}//end catch
}while(isbn.trim().length() <4 && (isbn.trim().length()>0) || (isbn.trim().length() >4));
sc = new Scanner(System.in);
System.out.println();
do{
System.out.print("Enter quantity: ");
quantity = sc.nextLine();
try{
quantityInt = Integer.valueOf(quantity);
}//end try
catch(NumberFormatException nfe){
System.out.println("\nPlease enter integer numbers from 1 through 1000 only.");
}//end catch
}while(quantity.trim().length() > 1000 ||(quantity.trim().length()<0) );
发布于 2019-05-06 02:14:56
创建验证ISBN的方法,如下所示
public boolean verifyISBN(int ISBN)
在这里,您将使用for循环检查数组中是否存在ISBN
收到返回值后,将其存储在一个变量中,并在第一个do-while循环的while条件中使用。
发布于 2019-05-06 02:24:55
我认为您需要一种不同的数据结构,比如HashSet,因为它不允许重复。
调用add方法时:
hashSet.add(quantityInt);
它验证HashSet是否已经包含该元素。
您可以检查该方法是否返回了false,如果是,则显示一条错误消息并再次启用输入。
...
final Set<Integer> set = new HashSet<>();
int quantityInt = scanner.nextInt();
while(!set.add(quantityInt)) {
System.out.println("You can't insert duplicate elements.");
quantityInt = scanner.nextInt();
}
...
发布于 2019-05-06 03:12:30
我觉得我就像在拨打电话。不幸的是,我需要使用ArrayList进行赋值。我有一个带有布尔运算符"contains“的while循环设置。
while(contains != books.contains(isbnInt)){
但它不起作用
https://stackoverflow.com/questions/55997961
复制相似问题