java未定义名称“Y”,以及奇怪的输出问题
我的代码可以编译,但当我尝试运行它时,当我运行Y/N循环控制变量时,它会给我一个“未定义名称”的错误。我在下面输入了整个程序的编码
此外,它在询问循环问题时显示关闭对话框。。我做错了什么
//declarations
String itemName; //name of item
String itemPriceInput; //user input of price
double itemPrice; //parsed name of price
String itemQuantityInput; //user input of quantity
double itemQuantity; //parsed input of quantity
String inputMore; //loop control
//Create file instance
java.io.File itemAttributes = new java.io.File("Items_In_Stock.txt");
//Create a scanner for the file
Scanner input = new Scanner(itemAttributes);
System.out.println("Welcome to the inventory list program"); //welcome dialog for user
System.out.println("This program will show items on hand, as well as their info"); //more dialog
System.out.println("Enter 'Y' to proceed, or 'Q' to quit"); //asking to start program
inputMore=input.next(); //taking input for loop control
while (inputMore.equalsIgnoreCase("y")) //beginning outer loop
{
while (input.hasNext()) //beginning inner loop
{
itemName=input.next(); // input item name
System.out.print (" ");
itemPriceInput=input.next(); //input item price
itemPrice=Double.parseDouble(itemPriceInput); //parse to double
System.out.print (" ");
itemQuantityInput=input.next(); //input quantity
itemQuantity=Double.parseDouble(itemQuantityInput); //parse to double
System.out.println("Name: " + itemName + " " + "Price: " + itemPrice + " " + "Quantity: " + itemQuantity); //display input items
} //close inner loop
System.out.print("Enter 'Y' to input more, or 'Q' to quit"); //asking user to input more, or quit
} //close outer loop
input.close(); //close program
System.out.println("Thank you for using the program. Goodbye");//goodbye statement
# 1 楼答案
我看到的唯一错误是
您忘记在循环结束时更新inputMore,换句话说
inputMoreinputMore.equalsIgnoreCase("y")
将始终返回true,因为您从未更改它的值你可以换成
或者在循环的末尾添加另一个
# 2 楼答案
我假设您的
txt
文件包含如下数据到目前为止,我可以看到两个缺陷: 当您询问用户
"Enter 'Y' to proceed, or 'Q' to quit"
时,您应该使用System.in
使用不同的扫描仪还有,为什么要在内部使用while循环??您应该在那里使用
if
条件来请求用户选择这是更新后的代码。它将解决您的问题: