我知道這是非常簡單的事情,但是,我只編程了幾個月,所以我的大腦有時會霧化出來,我需要一個帶有嵌套else if語句的while循環的幫助。問題我的循環是連續的,因爲用戶從來沒有機會進入他們的選擇(-1停止循環)。我怎樣才能改變循環,讓它通過要求用戶輸入一個選項(1-4或-1退出)來操作java loop,if else
請任何幫助表示讚賞。我知道這很簡單,我已經通過以前的論壇討論進行過搜索,但我似乎無法使其工作。
//create new scanner object
Scanner userInput = new Scanner (System.in);
int end = 0;
//find out what user wants to do with address book
while (end != -1)
{
System.out.println(" ");
System.out.println(" ");
System.out.println("----------------------------");
System.out.println("What would you like to do with your address book? ...");
System.out.println("----------------------------");
System.out.println("Add new [Enter 1]");
System.out.println("Delete existing [Enter 2]");
System.out.println("Edit existing [Enter 3]");
System.out.println("Search for [Enter 4]");
System.out.println("EXIT [Enter -1]");
}
if (userInput.hasNext() && (userInput.nextInt() == 1))
{
AddressBookProcessor.addContact();
}
else if (userInput.hasNext() && userInput.nextInt() == 2)
{
AddressBookProcessor.deleteContact();
}
else if (userInput.hasNext() && userInput.nextInt() == 3)
{
AddressBookProcessor.editContact();
}
else if (userInput.hasNext() && userInput.nextInt() == 4)
{
AddressBookProcessor.findContact();
}
else if (userInput.nextInt() != 1 || userInput.nextInt() != 2
|| userInput.nextInt() != 3 || userInput.nextInt() != -1)
{
System.out.println("Please enter a valid input");
end = -1;
}
}
感謝,我的大腦累了,一切都在今晚,剛剛看到代碼連續4天不間斷! – user2044988 2013-03-19 00:43:59