如何确保这些字段在用户填写时不会留空?这是一个类文件,填写的信息将由另一个主文件调用。我想确保填写信息,但直到最后一切都被编译(其他类文件正在处理)。如果名称留空,那么我希望程序声明名称字段留空并需要填写才能点击完成按钮。任何和所有的帮助表示赞赏。
import java.util.Scanner;
public class fillInfo
{
public String name;
public String address;
public String telephone;
public void readInput()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the customers name?");
name = keyboard.nextLine();
System.out.println("What is the customers telephone number?");
telephone = keyboard.nextLine();
System.out.println("What is the customers address?");
address = keyboard.nextLine();
}
public void writeOutput()
{
System.out.println("Sold to: "+ name);
System.out.println("Telephone: "+ telephone);
System.out.println("Address: "+ address);
}
}
答案 0 :(得分:0)
也许你做了类似的事情:
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the customers name?");
name = keyboard.nextLine();
while(name="")//empty string (nothing) entered
{
System.out.println("Please enter a valid name");
name = keyboard.nextLine();
}
。 。
答案 1 :(得分:0)
对于每个字段变量,您可以执行以下操作:
while (name == null || name.trim().isEmpty()) {
System.out.println("What is the customers name?");
name = keyboard.nextLine();
}
更新:可以在程序结束前检查值并调用这样的辅助方法:
if (name == null || name.trim().isEmpty()) {
name = getInputValue("What is the customers name?");
}
使用相应的辅助方法:
private String getInputValue(String prompt) {
System.out.println(prompt);
Scanner keyboard = new Scanner(System.in);
return keyboard.nextLine();
}
注意:这对资源的效率低于第一种方法,因为每个缺少的字段变量都会创建一个新的Scanner
实例。