问题
How do I exit this loop when user presses ENTER. This is part of the codes I have done. I am having problems in how to code when user presses ENTER.
static String[] itemList = new String[10];
do {
System.out.print("Enter item (press ENTER to exit) " + (count + 1) + ": ");
String item = input.next();
itemList[count] = item;
if (item == "")
count = itemList.length;
回答1:
You are comparing String
s using ==
not .equals()
.
This compares the pointer to the String
, not the contents of the String
.
回答2:
Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
while(readString!=null)
{
System.out.println(readString);
if(readString.equals(""))
System.out.println("Read Enter Key.");
if(scanner.hasNextLine())
readString = scanner.nextLine();
else
readString = null;
}
回答3:
Check the condition before entering into loop. For example:
boolean statusIsNotReady = true;
while(statusIsNotReady) {
// do your fty;
if(someCondition) {
statusIsNotReady = false; // If the status changed
}
}
回答4:
public class SampleInputReader{
public static void main(String args[]){
String[] itemList = new String[10];
int count = 0;
Scanner keyboard = new Scanner(System.in);
String data = "";
do{
System.out.print("Enter item (press ENTER to exit) " + (count + 1)+ ": ");
data = keyboard.nextLine();
if(data.isEmpty())
break;
itemList[count] = data;
count++;
}while(true);
for(int i = 0; i< itemList.length; i++)
System.out.println(itemList[i]);
}
}
But instead of Array i suggest you to use Arraylist.
来源:https://stackoverflow.com/questions/21698038/how-to-exit-loop-with-enter