我一直在开发一个程序,该程序将接受用户对元素周期表中元素的名称或符号的输入,然后输出有关该元素的一些事实。在这里问了几个问题之后,我已经到了程序正确存储所有数据的地步,以我想要的方式输出数据,并且可以接受名称或符号的输入。我现在遇到的问题是,我插入到循环中的中断实际上并没有从循环中中断,我真的不知道为什么。即使程序收到了正确的输入,它也会继续要求输入。此外,如果用户输入了一个符号而不是名称,程序将在最终正确输出之前反复告诉用户他们的输入无效(然后重新启动循环,而不是像应该的那样中断(。我是Java的新手,所以如果有人能帮我解决这两个问题,并简单地解释为什么会出现问题以及他们是如何解决的,我将不胜感激
import java.util.Scanner;
public class PeriodicTable {
public enum Element {
Hydrogen("H", "Nonmetal", "1.008"),
Helium("He", "Noble Gas", "4.003"),
Lithium("Li", "Alkali Metal", "6.941"),
Beryllium("Be", "Alkaline Earth", "9.012"),
Boron("B", "Semimetal", "10.811"),
Carbon("C", "Nonmetal", "12.011"),
//The rest of the periodic table is here, I just removed it for the sake of this post.
private String symbol;
private String group;
private String weight;
private Element(String symbol, String group, String weight) {
this.symbol = symbol;
this.group = group;
this.weight = weight;
}
}
static Element cName = null;
public static void main(String[] args) {
System.out.println("Enter the name or symbol of an element in the periodic table. ");
do {
Scanner reader = new Scanner(System.in);
String input = reader.nextLine().trim();
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input)) {
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "nGroup: " + sy.group + "nAtomic Mass: " + sy.weight);
reader.close();
break;
} else {
try {
cName = Element.valueOf(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "nGroup: " + cName.group + "nAtomic Mass: " + cName.weight);
reader.close();
break;
} catch(IllegalArgumentException e) {
System.out.println("That name or symbol is not valid. Please try again. ");
continue;
}
}
}
} while (true);
}
}
问题是break
在for
循环中,所以它只中断到for循环。如果你想打破do-while
循环,你可以使用一个标签:
outer:
do {
Scanner reader = new Scanner(System.in);
String input = reader.nextLine().trim();
for (Element sy : Element.values()) {
if (sy.symbol.equalsIgnoreCase(input)) {
System.out.println("Element: " + sy + " (" + sy.symbol + ")" + "nGroup: " + sy.group + "nAtomic Mass: " + sy.weight);
reader.close();
break outer;
} else {
try {
cName = Element.valueOf(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "nGroup: " + cName.group + "nAtomic Mass: " + cName.weight);
reader.close();
break outer;
} catch(IllegalArgumentException e) {
System.out.println("That name or symbol is not valid. Please try again. ");
continue;
}
}
}
} while (true);