猿问

IF 语句在 for 循环中不能很好地工作

在下面的代码中,我想让用户在搜索框中输入可用的学生 ID 之一,然后如果学生 ID 有效,将出现一个简单的消息框,其中包含可用的学生 ID。


情况 1:当我在搜索框中输入 212 时,效果很好。


情况2:当我输入215或219或214(不是212)时,它会跳转到“未找到”消息框,再尝试两次后,我会收到一个包含已找到学生ID的消息框。


问题为什么我第一次输入215或219或214时没有找到消息框,但输入212时却可以正常工作?这个 for 循环或 IF 语句有什么问题?为什么当我输入215时,它会忽略第一次和第二次然后显示找到的消息框?


import javax.swing.*;

static int[] studentID = {212,214,215,219};


public static void main(String[] args) {

    search();


    System.exit(0);


}


public static void search(){

    for(int i = 0;i < studentID.length;i++){

        search = JOptionPane.showInputDialog(null,"Enter a student ID");

        if(studentID[i] == Integer.parseInt(search)){

            JOptionPane.showMessageDialog(null, studentID[i]);

            break;

        }else{

            JOptionPane.showMessageDialog(null,"NOT FOUND!!!");

        }

    }

}


桃花长相依
浏览 123回答 2
2回答

繁华开满天机

循环应该在读取输入之后,并且“NOT FOUND”消息应该在循环之后:public static void search(){&nbsp; &nbsp; search = JOptionPane.showInputDialog(null,"Enter a student ID");&nbsp; &nbsp; for(int i = 0;i < studentID.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; if(studentID[i] == Integer.parseInt(search)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JOptionPane.showMessageDialog(null, studentID[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; OptionPane.showMessageDialog(null,"NOT FOUND!!!");}如果要执行多次搜索,则应search()多次调用该方法。

偶然的你

import javax.swing.*;public class Stackoverflow1 {&nbsp; &nbsp; static int[] studentID = {212,214,215,219};&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; search();&nbsp; &nbsp; &nbsp; &nbsp; System.exit(0);&nbsp; &nbsp; }&nbsp; &nbsp; public static void search(){&nbsp; &nbsp; &nbsp; &nbsp; String enter_a_student_id = JOptionPane.showInputDialog(null, "Enter a student ID");&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0;i < studentID.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(studentID[i] == Integer.parseInt(enter_a_student_id)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JOptionPane.showMessageDialog(null, studentID[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.exit(0);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JOptionPane.showMessageDialog(null,"NOT FOUND!!!");&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答