Java 检查扫描仪的错误?
所以我决定制作一个程序,制作每个都有名字的Orc对象Java 检查扫描仪的错误?,java,validation,java.util.scanner,Java,Validation,Java.util.scanner,所以我决定制作一个程序,制作每个都有名字的Orc对象 import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); for (int x = 0; x < 10; x++){ System.out.println("Input the nam
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for (int x = 0; x < 10; x++){
System.out.println("Input the name of your Orc here:");
String name = input.nextLine(); //THIS is where the inputed name is registerd.
Orcmaker Orc = new Orcmaker(name);
System.out.println(Orc);
input.close();
}
System.out.println("Fire");
//Find a way to run validation code while not obstructing the for loop to make multiple orc objects.
}
}
String.valueOf
在这里是完全冗余的;只需执行返回名称
。此外,您不应将普通变量名大写,而应仅将类名(和其他类型名)大写。此外,您正在循环中调用input.close()
。你应该在循环之外调用它。我真的不知道你说的“使某些代码行变为空白”是什么意思。但是for
循环中的代码应该缩进;否则,很难理解。我不知道你所说的“循环吞噬重要代码”是什么意思。我认为您可能需要添加一个内部while
循环,该循环具有输入.nextLine()
,如果输入有效,则中断该循环,如果输入无效,则显示错误消息并返回。要验证是否没有数字或特殊字符,请使用正则表达式(也称为regex)。您可以通过谷歌搜索“Java教程正则表达式”了解更多信息。您可以使用正则表达式进行名称验证,并与您的输入匹配,如果不匹配,则在控制台上显示错误消息。
public class Orcmaker {
private String name;
private int age;
private String weapon;
public Orcmaker(String OrcName){
this.name = OrcName;
}
@Override
public String toString() {
return String.valueOf(name);
}
}