对于一些项目,我一直在尝试用Java创建一个类似于:
的控制台菜单 (1) Do this
(2) Do that
(3) Blah blah
(4) etc
我正在使用do {...} while (...)
循环,但我无法获得控制变量的正确值。
我的代码是:
String status = "e";
do {
System.out.println("---------------------------------------");
System.out.println(b1.toString());
System.out.println(b2.toString());
System.out.println(b3.toString());
System.out.println("---------------------------------------");
System.out.println("Borrow(b), Return(r), Check(c), Exit(e)");
status = r.nextLine();
....
} while(!status.equals("e"));
此代码导致所有println
输出正确,但按Enter键后,同样的内容将再次输出,而我用....
替换的代码将不会执行。这段代码有其他控制台输出,从未出现过。
我认为这是因为r.nextLine()
返回的值会随着新数据的输出而不断变化。所以我做了一个单独的static
函数:
public static String getInfo(Scanner r, Book b1, Book b2, Book b3) {
System.out.println("---------------------------------------");
System.out.println(b1.toString());
System.out.println(b2.toString());
System.out.println(b3.toString());
System.out.println("---------------------------------------");
System.out.println("Borrow(b), Return(r), Check(c), Exit(e)");
String status = r.nextLine();
return status;
}
但是这个函数也返回相同的结果。我该怎么做才能解决这个问题?
编辑:
现在,这是我的菜单部分的完整代码,它在主要部分运行。
`String status =“e”;
do {
status = getInfo(reader,b1,b2,b3);
if (status == "b") {
System.out.println("Which patron ( (1)" + p.getName() + " or (2)" + p2.getName() + " is borrowing?");
int cur = reader.nextInt();
System.out.println("Which book is " + cur + " borrowing?");
String curbk = reader.nextLine();
if (p.hasBook(curbk)){
System.out.println(p.getName() + " has this book already.");
} else {
if (p2.hasBook(curbk)) {
System.out.println(p2.getName() + " has this book already.");
} else {
if (cur==1) {
System.out.println(p.borrowBook(curbk));
} else {
System.out.println(p2.borrowBook(curbk));
}
}
}
} else if (status == "r") {
System.out.println("Which patron ( (1)" + p.getName() + " or (2)" + p2.getName() + ") is returning?");
int cur = reader.nextInt();
System.out.println("Which book is " + cur + " returning?");
String curbk = reader.nextLine();
if (cur==1) {
if (p.hasBook(curbk)){
System.out.println(p.returnBook(curbk));
} else {
System.out.println(p.getName() + " does not have this book.");
}
} else {
if (p2.hasBook(curbk)){
System.out.println(p2.returnBook(curbk));
} else {
System.out.println(p2.getName() + " does not have this book.");
}
}
} else if (status == "c") {
System.out.println("Which book would you like to check for?");
String curbk = reader.nextLine();
if (p.hasBook(curbk)){
System.out.println(p.getName() + " has this book.");
} else {
if (p2.hasBook(curbk)) {
System.out.println(p2.getName() + " has this book.");
} else {
System.out.println("This book is ready to be checked out!");
}
}
}
} while(!status.equals("e"));`
getInfo()
来自上方。
答案 0 :(得分:0)
String status = r.nextLine();
删除关键字String,因为它创建了一个新的String而不是使用您已创建的变量。