gpt4 book ai didi

java - 如何在不必搜索数字(字符串格式)1-10 的情况下缩短我的 while 循环?

转载 作者:行者123 更新时间:2023-12-04 16:19:52 25 4
gpt4 key购买 nike

    //Input Number
System.out.print("Enter a number from 1-10: ");
words = input.next();

//Processing String
if(!words.equals(FLAG)){
while(!words.equals("1") && !words.equals("2") && !words.equals("3") &&
!words.equals("4") && !words.equals("5") && !words.equals("6") &&
!words.equals("7") && !words.equals("8") && !words.equals("9") &&
!words.equals("10")){
System.out.print("Please enter a number in integer form from 1-10: ");
words = input.next();
}
}
//Close Scanner
input.close();

//String to Integer
num = Integer.parseInt(words);

//Output Number
if(num >=1 || num <=10){
System.out.println("\nYour number is: " + num);
}

我怎样才能改变 while 循环?如果数字范围是 1-100 怎么办?有没有办法缩短处理字符串段?该程序需要能够处理字符串和整数。

最佳答案

将其解析为Integer

int number = Integer.parseInt(words);   

和循环:

while( !(number > 0 && number <= 10) ){ // loop the loop }    

注意:因为您将使用 parseInt(),所以您需要学习使用 try-catch block 。一定要查一下

关于java - 如何在不必搜索数字(字符串格式)1-10 的情况下缩短我的 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22852645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com