我通过创建while循环创建了以下代码。我不知道为什么循环被设置为看17行而不是15行。
while (scan.hasNext())
{
selectedUserName.setText(scan.next());
if(scan.nextLine().toString() == "Male")
{
male = new JRadioButton("Male", true);
}
else if(scan.nextLine().toString() == "Female")
{
female = new JRadioButton("Female", true);
}
selectedGenderText.setText(scan.nextLine());
if(scan.next().toString() == "Warrior")
{
userClassBox.setSelectedItem(classes[0]);
}
else if(scan.next().toString() == "Barbarian")
{
userClassBox.setSelectedItem(classes[1]);
}
else if(scan.next().toString() == "Mage")
{
userClassBox.setSelectedItem(classes[2]);
}
else if(scan.next().toString() == "Thief")
{
userClassBox.setSelectedItem(classes[3]);
}
selectedClassText.setText(scan.nextLine());
pointsText.setText(scan.nextLine());
pointsSlider.setValue(Integer.parseInt(scan.nextLine()));
intelligenceText.setText(scan.nextLine());
intelligenceSlider.setValue(Integer.parseInt(scan.nextLine()));
dexterityText.setText(scan.nextLine());
dexteritySlider.setValue(Integer.parseInt(scan.nextLine()));
strengthText.setText(scan.nextLine());
strengthSlider.setValue(Integer.parseInt(scan.nextLine()));
wisdomText.setText(scan.nextLine());
wisdomSlider.setValue(Integer.parseInt(scan.nextLine()));
}
我的输入文件有15行与上面的代码匹配,
Warrior
Male
Male
Warrior
Warrior
0
0
10
10
30
30
60
60
0
0
if / else语句是否引用了两个新行?当我运行该程序时,它会卡在以下行 -
Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at CharacterCreation$OpenCharListener.actionPerformed(CharacterCreation.java:450)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
这引用从 -
开始的最后两行 wisdomText.setText(scan.nextLine());
wisdomSlider.setValue(Integer.parseInt(scan.nextLine()));
为什么.nextLine()功能看17行而不是15?
答案 0 :(得分:3)
请注意,Scanner.nextLine()
会占用扫描仪的数据。所以在这个例子中:
if(scan.nextLine().toString() == "Male")
{
male = new JRadioButton("Male", true);
}
else if(scan.nextLine().toString() == "Female")
{
female = new JRadioButton("Female", true);
}
在第一个if语句中,您将使用扫描程序中的数据,如果条件为false,则您将在else-if语句中使用它后面的任何内容。
您可能只想做String input = scan.nextLine();
然后与存储的字符串进行比较。