gpt4 book ai didi

java - 从用户输入java覆盖变量

转载 作者:行者123 更新时间:2023-12-01 18:35:00 24 4
gpt4 key购买 nike

我是Java的新手,为了建立一些技能,我想写一个简单的猜数字游戏。不幸的是,我无法弄清楚如何更新存储用户输入的整数。知道我如何“覆盖”我的int b吗?

import java.util.Scanner;

public class ratespiel {
public static void main(String[] args) {

int a = 30;
Scanner scan = new Scanner(System.in);

System.out.println("The number you're looking for is between 0-100. Take a guess!");
int b = scan.nextInt();

while (a != b) {
if (a < b) {
System.out.println("too high!");
int b = scan.nextInt();
} else if (a > b) {
System.out.println("too low!");
int b = scan.nextInt();
}
}
if (a == b){
System.out.print("Congratulations, you guessed the right number!");
}

}
}

最佳答案

b在循环中不会被覆盖,因为您要重新声明它。

使用int b = ...将创建一个名为b的全新变量。

您需要删除int才能使其正常工作。

import java.util.Scanner;

public class ratespiel {
public static void main(String[] args) {

int a = 30;
Scanner scan = new Scanner(System.in);

System.out.println("The number you're looking for is between 0-100. Take a guess!");
int b = scan.nextInt();

while (a != b) {
if (a < b) {
System.out.println("too high!");
b = scan.nextInt();
} else if (a > b) {
System.out.println("too low!");
b = scan.nextInt();
}
}
if (a == b){
System.out.print("Congratulations, you guessed the right number!");
}

}
}

关于java - 从用户输入java覆盖变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60077876/

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