栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何用某个变量结束while循环

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何用某个变量结束while循环

您可以尝试的另一件事是,您可以继续要求用户输入正确的输入,而不是退出程序,只有在输入正确的输入后才继续操作。我不知道您的要求是什么,但是如果您想通过良好的代码习惯进行操作,则不应仅因为用户输入了错误的输入而终止程序。想象一下,如果您用错字搜索了一个单词,而Google刚刚关闭。

反正这就是我的做法

import java.util.Scanner;public class oddoreven {    public static void main(String[] args) {        int num;        int x = 1;        while (x == 1) { System.out.println("Enter a number to check whether or not it is odd or even"); Scanner s = new Scanner(System.in); boolean isInt = s.hasNextInt(); // Check if input is int while (isInt == false) { // If it is not int     s.nextLine(); // Discarding the line with wrong input     System.out.print("Please Enter correct input: "); // Asking user again     isInt = s.hasNextInt(); // If this is true it exits the loop otherwise it loops again } num = s.nextInt(); // If it is int. It reads the input if (num % 2 == 0)     System.out.println("The number is even"); else     System.out.println("The number is odd"); // trying to figure out how to get the pre to terminate if you put in a value // that isn't a number System.out.println("Type 1 to continue, 0 to terminate"); x = s.nextInt();        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/407174.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号