带有If语句的For循环后的语句不可达



我有一项非常基本的任务,但对我来说仍然是全新的领域。该程序应该要求用户输入他们的姓名、等级和科目。如果主题不是IT,他们的投入就会被搁置一边。但是,如果输入的主题是IT,则稍后将再次使用它们的名称、姓氏和等级来显示如下信息:

显示消息

根据用户输入的内容,信息可能有所不同。现在问题来了。我正确地键入了代码,但在使用JOptionPane显示消息的最后,它显示了一个错误:";无法访问的语句";。(为了澄清它发生在代码行旁边(这很奇怪,因为它几乎与作业备忘录完全相同,但却有错误。在某种程度上,这可能是Netbeans感到困惑,但我在家里重新安排了任务,它在这里发挥了应有的作用:

String name, surname, subject, message = "IT Learners:nn";
int grade, counter = 0;
for (int i = 0; i < 3; i++) {
name = JOptionPane.showInputDialog("Enter Your Name Here: ");
surname = JOptionPane.showInputDialog("Enter Your Surname Here: ");
subject = JOptionPane.showInputDialog("Enter Your Subject Here: ");
grade = Integer.parseInt(JOptionPane.showInputDialog("Enter Your "
+ "Grade Here: "));
if (subject.equalsIgnoreCase("IT")) {
message += name + " " + surname + " is in grade "
+ grade + ".n";
counter++;
}
}
JOptionPane.showMessageDialog(null, message + "There is a total of "
+ counter + " IT Learners.");

下一段代码是我在此期间在终端上写的代码的副本。我个人看不到这个错误,我来这里是想问它是否正确,还是有一个我似乎找不到的小错误。

我在学校做的代码:

String name, surname, subject, message = "IT Learners:nn";
int grade, counter = 0;
for (int i = 0; i < 3; i++) {
name = JOptionPane.showInputDialog("Enter Your Name Here: ");
surname = JOptionPane.showInputDialog("Enter Your Surname Here: ");
subject = JOptionPane.showInputDialog("Enter Your Subject Here: ");
grade = Integer.parseInt(JOptionPane.showInputDialog
("Enter Your Grade Here: "));
if (subject.equalsIgnoreCase("IT")) 
{
message += name + " " + surname + " is in grade "
+ grade + ".n";
counter++;
}
}
JOptionPane.showMessageDialog(null, message + "There is a total of "
+ counter + " IT Learners.");

它看起来真的很一样,是Netbeans混淆了,还是我缺少了一个细节?

完整代码:

import javax.swing.JOptionPane;
/**
*
* @author (My Name)
*/
public class ITLearners {
public static void main(String[] args) {
// TODO code application logic here
String name, surname, subject, message = "IT Learners:nn";
int grade, counter = 0;
for (int i = 0; i < 3; i++) {
name = JOptionPane.showInputDialog("Enter Your Name Here: ");
surname = JOptionPane.showInputDialog("Enter Your Surname Here: ");
subject = JOptionPane.showInputDialog("Enter Your Subject Here: ");
grade = Integer.parseInt(JOptionPane.showInputDialog("Enter Your "
+ "Grade Here: "));
if (subject.equalsIgnoreCase("IT")) {
message += name + " " + surname + " " + " is in grade "
+ grade + ".n";
counter++;
}
}
JOptionPane.showMessageDialog(null, message + "There is a total of "
+ counter + " IT Learners.");
}
}

我现在觉得很傻。学校编写的代码中的问题是for循环条件中的i是1。像这样:

for ( int i = 0; 1 < 3; i++; )

从中吸取的教训是:确保正确键入所有内容。有了1,我无意中在没有意识到的情况下创建了一个无限循环。非常感谢你的帮助,尤其是@AcidReisin!

相关内容

  • 没有找到相关文章

最新更新