java - How to stop on duplicate entry (Java)
问题描述
I have a simple code that asks a user to input items and stores them into an array. I would like to make it so the program stops running when the last entry is the same as the first.
so for example this would stop the program because Cookie it both the first item in the array and the last. But it's also ok to have duplicates with in the array like "Sugar" in this example:
Enter the item: Cookie
Enter the item: Sugar
Enter the item: Milk
Enter the item: Sugar
Enter the item: Salt
Enter the item: Cookie
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Decide the number of items
int numOfItems = 20;
//Create a string array to store the names of your items
String arrayOfNames[] = new String[numOfItems];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
}
//Now show your items's name one by one
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Item # " + (i+1) + " : ");
System.out.print(arrayOfNames[i] + "\n");
}
}
}
Thanks for your help
解决方案
You can do this by adding a simple if-condition
with equals()
method. you need do add following if-condition
.
if(Temp.equals(arrayOfNames[0])) // readed Temp equals to first element.
Try this code:-
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Decide the number of items
int numOfItems = 20,maxItems=0; // total items may vary
//Create a string array to store the names of your items
String arrayOfNames[] = new String[numOfItems];
String Temp=""; // for temporary storage
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
Temp= scan.nextLine();
if(Temp.equals(arrayOfNames[0])){
maxItems=i;
break;
}
else{
arrayOfNames[i]=Temp;
}
}
//Now show your items's name one by one
for (int i = 0; i < maxItems; i++) {
System.out.print("Item # " + (i+1) + " : ");
System.out.print(arrayOfNames[i] + "\n");
}
}
}
Output :-
Enter Item 1 : Cookie
Enter Item 2 : Sugar
Enter Item 3 : milk
Enter Item 4 : Sugar
Enter Item 5 : Salt
Enter Item 6 : Cookie
Item # 1 : Cookie
Item # 2 : Sugar
Item # 3 : milk
Item # 4 : Sugar
Item # 5 : Salt
推荐阅读
- flutter - Flutter 测试错误:NotInitializedError 涉及环境变量(.env)
- asp.net - 使用 ASP.net 在 Restful API 中显示多对多
- uwp - WinUI 3 - UWP - 如何以编程方式添加或删除资源字典
- llvm - RISC-V LLVM 13 链接器错误:`未定义的隐藏符号:__math_oflowf`
- cassandra - 如何查询列表中的元素
>> 在卡桑德拉? - haskell - 尽管设置了行级别策略,但未从 IHP DataSync 获得结果
- php - 如何在 woocommerce 属性之间放置自定义 div?
- mysql - MYSQL:如何计算每个数据的移动平均值?
- swift - Actor 'self' 只能从异步初始化器中传递 'inout'
- maven - 使用 maven 或 artifactory 查找依赖项的所有引用?