嗨,我是编程和 Java 新手。 下面的代码将把用户输入添加到我尚未实现的文件中。然而,
我不知道为什么:
非常感谢任何帮助。
package so;
import java.util.Scanner;
public class programTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = "";
double time = -1.0;
char moreDataChoice = 'a';
boolean moreData = true;
do {
name = "";
time = -1.0;
System.out.println("Name:");
while (name.isEmpty() == true) {
name = sc.next();
if (name.isEmpty() == false) {
break;
} else {
System.out.println("Error. Please enter a name.");
}
}
System.out.println("Time:");
do {
time = sc.nextDouble();
sc.nextLine();
if (time > 0) {
break;
} else {
System.out.println("Error. Please enter a appropriate time");
}
} while (time < 0.0);
System.out.println("Enter more data? (y/n)");
do {
moreDataChoice = sc.next().charAt(0);
if (moreDataChoice == 'y') {
moreData = true;
} else if (moreDataChoice == 'n') {
moreData = false;
break;
} else {
System.out.println("Error. Please enter y or n.");
}
} while ((moreDataChoice != 'y') && (moreDataChoice != 'n'));
} while (moreData == true);
sc.close();
}
}
首先,我觉得你无缘无故地有太多的 do-while 循环。我修改了您的代码以使其更加简单,并且由于您每次都必须从用户那里获取输入,因此您不需要重置变量。你总是可以获取输入,然后检查它是否为空,然后提示他们再次输入。 还更改了一些使用
sc.next
代替 sc.nextLine
的地方的代码,如果您查看代码就可以理解。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = "";
double time = -1.0;
char moreDataChoice = 'y';
boolean moreData = true;
while(moreDataChoice == 'y') {
System.out.print("Name:");
name = sc.nextLine();
while (name.isEmpty()) {
System.out.println("Error. Please enter a name.");
name = sc.nextLine();
}
System.out.println("Time:");
time = sc.nextDouble();
sc.nextLine();
while(time < 0.0) {
System.out.println("Error. Please enter a appropriate time");
time = sc.nextDouble();
sc.nextLine();
}
System.out.println("Enter more data? (y/n)");
moreDataChoice = sc.nextLine().charAt(0);
while(!(moreDataChoice == 'y' || moreDataChoice == 'n')) {
System.out.println("Error. Please enter y or n.");
moreDataChoice = sc.nextLine().charAt(0);
}
}
System.out.println("Program ended");
sc.close();
}
}