1

我如何确保这些字段在用户填写时不会留空?这是一个类文件,填写的信息会被另一个主文件调用。我想确保信息已填写,但要等到最后所有其他内容都已完成(我正在处理其他类文件)。如果名称留空,那么我希望程序说明名称字段留空并且需要填写,然后我才能单击完成按钮。任何和所有的帮助表示赞赏。

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);
}
}
4

2 回答 2

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();
}

. . .

于 2012-10-18T23:08:14.227 回答
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每个缺失的字段变量都会创建一个新实例。

于 2012-10-18T23:11:56.930 回答