java在终止时做

时间:2016-03-14 16:06:31

标签: java validation do-while

此程序要求用户输入一个数字,然后从列表中返回详细信息。我该怎么做?

         do {
          Scanner in = new Scanner(System.in);             
            System.out.println("Enter Number <terminated by 1>");

             }  while (!input.equals("-1"));
                System.out.println("Session Over");

        } catch (Exception e) {   
            System.out.println(e);
        }
    }
}

输出:

Enter Number <terminated by 1>
123456
Person Number: 12

4 个答案:

答案 0 :(得分:1)

with open(myfilename, 'w') as csvfile: writer = csv.DictWriter(csvfile) for a,b,c in zip(zmin_limits,zmax_limits,mlim_limits): info = id_match(data_zcosmo_lastz,data_zphot_lastz,a,b,c) writer.writerow(info) 是比较两个整数值的正确方法。

答案 1 :(得分:0)

在java中,当变量在循环内部时,你无法在do-while循环中测试变量:

part1 &
part2 &
part3 &
part4 &
wait

不会编译。

此外,do { int i = 10; } while (i > 5); 没有int input;方法,因为equals类型是原始的。

答案 2 :(得分:0)

首先从循环中删除扫描仪初始化并将其放入try块中,如Pshemo指出的那样。

try {
    Scanner in = new Scanner(System.in);
do {
    yada yada yada
}

然后尝试在你的while循环中包含你的否定,如下所示:

while (!(input.equals("-1")));

答案 3 :(得分:0)

专业提示:使用IDE。

您的代码错误至少有两个原因:

  1. 您的int input已在do块中定义,因此在关闭后无法显示
  2. 您在基本类型
  3. 上使用.equals

    按如下方式更正您的代码:

    public class Client {
    
        public static void main(String[] arg) {
            Client c = new Client();
            c.run();
        }
    
        private void run() {
            StudentData p = new StudentData();
            List<StudentDetailsType> personDetailsList = (List<StudentDetailsType>) p.getList();
    
    
            // input defined outside the do block so it is visible in while clause
            int input;
            // declare the scanner just one time here, so it will be closed automatically as the try/catch block ends
            try(Scanner in = new Scanner(System.in)) {
                do {
                    System.out.println("Enter 6 digit Student Number <terminated by -1>");
                    input = in.nextInt();
                    for (StudentDetailsType q : personDetailsList) {
    
                        if (q.getStudentNumber() == input) {
                            System.out.println("Student Number: " + q.getStudentNumber() + "\n" + "Student Name: "
                                    + q.getStudentName() + "\n" + "Result 1: " + q.getResult1() + "\n" + "Result 2: "
                                    + q.getResult2() + "\n" + "Result 3: " + q.getResult3());
                            break;
                        }
                    }
                } while (input != -1); // use an int comparison (!= that means not equals)
    
                System.out.println("Session Over");
    
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }