Java练习:5.分支与循环1.2——猜数字
本帖最后由 划句顾 于 2023-3-5 22:54 编辑题目:输入一个数字,猜是不是正确的数字
运行结果如下:
package case_and_for;
import java.util.Random;
import java.util.Scanner;
import java.util.random.*;
public class GuessNumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random random = new Random();
System.out.println("给你一个1至100之间的整数,请猜测这个数");
int realNumber =random.nextInt(100)+1;
int yourGuess = 0;
System.out.println("请输入您的猜测:");
yourGuess = in.nextInt();
while(yourGuess != realNumber)
{
if(yourGuess>realNumber)
{
System.out.println("猜大了,再输入你的猜测:");
yourGuess = in.nextInt();
}
else if(yourGuess<realNumber)
{
System.out.println("猜小了,再输入你的猜测:");
yourGuess = in.nextInt();
}
}
System.out.println("猜对了!!!");
}
}
static/image/hrline/5.gif
另外一种方法,然后顺便计算一下猜了几次
运行结果如下:
package hello;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
// 初始化
Scanner in = new Scanner(System.in);
intguess ;
int count = 0;
int number;
number = (int)(Math.random()*101); //
do {
System.out.print("请输入:");
guess = in.nextInt();
count = count + 1;
if(guess>number)
{
System.out.println("输入的数字大了"+"count:"+count);
}
else if(guess<number)
{
System.out.println("输入的数字小了"+"count:"+count);
}
}while(guess != number);
System.out.println("一共猜了"+count+"次"+","+"猜中的数字为"+number);
}
}
{:7_141:}
页:
[1]