在 Java 中使用 continue 选项连接 while 循环 [英] Wiring a while loop with a continue option in java

查看:51
本文介绍了在 Java 中使用 continue 选项连接 while 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究具有数据验证功能的贷款计算器.我已经写好了一切,一切顺利.我唯一无法弄清楚的是如何在询问用户继续是/否?:"的地方编写一个 while 循环,然后让程序仅在用户键入 y/Y 时继续,并且程序仅在用户键入时才结束类型 n/N,任何其他输入都应给出错误消息,如无效,您只能输入 Y 或 N".因此,如果用户输入x",它应该显示错误消息.

I am working on a loan calculator with data validation. I have written everything and good to go. The only thing I cannot figure out is how to write a while loop in where the user is asked "Continue y/n?: " and then have the program continue ONLY when the user types y/Y and the program ENDS ONLY when the user types n/N, any other input should give an error message like "Invalid, you can only enter Y or N". So if the user enters "x" it should display the error message.

我尝试过 else if 子句,我也尝试过使用我在程序的其余部分中使用的方法验证数据,但我根本不知道如何验证字符串.我只能用原始数据类型来做.

I have tried else if clauses, I have also tried to validate data with the methods I used in the rest of the program but I simply don't know how to validate strings. I can only do it with primitive data types.

这是我现在知道如何编写循环的唯一方法,问题是它只会以 Y 以外的任何内容结束程序.

This is the only way i know how to write the loop as of now, the problem is it will simply end the program with anything but a Y.

分配的一个选项是使用 JOptionPane 但我不知道如何将其合并到 while 循环中并让它显示是和否按钮.

an option for the assignment is to use JOptionPane but I do not know how to incorporate that into the while loop and have it display a yes and a no button.

    String choice = "y";

    while (choice.equalsIgnoreCase("y")) {

    // code here

    System.out.print("Continue? (y/n): ");
        choice = sc.next();
    }
   }

推荐答案

本质上,您需要两个循环:一个执行工作,另一个在内部提示用户验证.

Essentially, you want two loops: one doing the work and the other one inside prompting for user validation.

boolean isContinuing = true;

while (isContinuing) {
    // do work

    boolean inputIsInvalid = true;
    while (inputIsInvalid) {
      System.out.print("Continue? (y/n): ");

      String choice = sc.next();

      if ("y".equalsIgnoreCase(choice)) {
          inputIsInvalid = false;
      }
      else if ("n".equalsIgnoreCase(choice)) {
          inputIsInvalid = false;
          isContinuing = false;
      }
      else {
          System.err.print("Error: Only valid answers are Y/N.");
      }
    }
}

Node:我使用的是布尔变量而不是 break 语句,它使代码更加直接和可读.

Node: I am using boolean variables instead of break statements, it makes the code more straightfoward and readable.

这篇关于在 Java 中使用 continue 选项连接 while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆