[英]Unable to scan all the elements of the string array using scanner in java
[英]How to get the Scanner to scan all the elements in an array, in java
這是問題:創建一個字符串數組並為其分配 5 個名稱。 詢問用戶他們的名字是什么,如果他們的名字與已經在列表中的名字相同,則做一些事情。 發揮創意,。 使用 for-each 循環打印數組中的每個名稱,每個索引之間有一個空格。
這是我到目前為止所擁有的。 我遇到的問題之一是掃描儀只將輸入與陣列上的名字進行比較,而不是 rest。
public static void main(String[] args) {
String[] names = {"Jose", "Alex", "Steven", "Sky", "Ana"};
Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String input = scan.next();
for (String n:names) {
if (n.equalsIgnoreCase(input)) {
System.out.print("Hooray! Your odds of finding a keychain with your name on it are high! =) ");
}
else {
System.out.print("Welcome to the rare names club!!! =D " );
System.out.print(names + " ");
}
break;
}
}
}
隨時對您看到的任何其他問題發表評論。 我是新手,希望得到反饋。 謝謝
也許這會有所幫助。 我認為“休息”被過早地稱為。 有很多方法可以解決這個問題,但我使用 boolean 來確定是否找到了名稱。 然后我在循環之后使用 boolean 來確定要打印的內容。
public static void main(String[] args) {
String[] names = {"Jose", "Alex", "Steven", "Sky", "Ana"};
Scanner scan = new Scanner(System.in);
System.out.println("What is your name? ");
String input = scan.next();
boolean isFound = false;
for (String n:names) {
if (n.equalsIgnoreCase(input)) {
isFound = true;
break;
}
}
if (isFound) {
System.out.print("Hooray! Your odds of finding a keychain with your name on it are high! =) ");
} else {
System.out.print("Welcome to the rare names club!!! =D " );
System.out.print(names + " ");
}
}
相同的方法但略有不同:)
`導入 java.util.Scanner; 導入 java.util.ArrayList;
公共 class 新 { 公共 static void main (String[]args) {
String [] cities = {"Poznan", "Warsaw", "Gdansk", "Wroclaw", "Krakow", "Lodz", "Katowice"};
Scanner scan = new Scanner(System.in);
System.out.println("What is the name of your city in Poland? ");
String name = scan.nextLine();
for (String n:cities) {
if (n.equalsIgnoreCase(name)) {
System.out.println("You are citizen of Poland from " +name);
System.out.println("Thank your for visiting " +name);
}
else {
System.out.println("You are not from Poland!!!" );
System.out.println("There is not city in Poland called" +name);
}
break;
}
}
}`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.