新手求教!Java中要求输入一个数字,该数字只能在另外两个数值之间,如果不满足要求重新输入。
做一个循环,条件是比较这个数。不满足就循环就可以了。
设定一个标记变量
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x,y= 10,z=20;
boolean flag = true;
while (flag){
x = scanner.nextInt();
if (x > y && x < z){
flag =false;
}else {
System.out.println("请重新输入");
}
}
}
}
好像是猜数字游戏功能
循环中嵌套判断,符合就跳出循环,不符合就继续循环
int a = 1;
int b = 10;
int n = 100;
for(int i = 0; i < n; i ++) {
if(i > a && i < b){
System.out.printf(i + "is OK!");
exist;
} else {
System.out.printf("Please input another data!"):
}
}
if(n = 100) {
System.out.printf("Exceed max number of input!");
}
直接用while(true)不行吗,满足条件则退出就是
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
Random rand=new Random();
int min=0,max=0;
while(min>=max){
if(min==0){
min=rand.nextInt(100);
}
else{
max=rand.nextInt(100);
}
}
System.out.println(min+" "+max);
System.out.println("请输入你要猜的数字:");
int res=scanner.nextInt();
while(true){
if(res>min&&res<max){
System.out.println("恭喜你!猜对了");
return;
}
System.out.println("猜的不对请重新输入:");
res=scanner.nextInt();
}
}
}
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
print();
}
public static void print(){
Scanner scaner = new Scanner(System.in);
int max = 10;
int min = 1;
int in = scaner.nextInt();
if(max < in || min > in){
System.out.println("重新输入");
print();
return;
}
System.out.println(in);
}
}
来晚了,楼上答案,都很正确。。。