此问题在此处已有答案:
Type mismatch: cannot convert from String to int(3个答案)
20小时前关门了。
所以,我做了一个数字猜测器,我有这个:
// import required classes for the program
import java.util.Scanner;
import java.lang.Math;
public class GuessingGame {
public static void main(String[] args) {
// generate a random number between 1 and 100
int answer = (int) (Math.random() * 100) + 1;
// number of trials that the user has to guess the number
int k = 5;
// create a scanner object to read user input
Scanner input = new Scanner(System.in);
// TO check if the user has guessed the number
boolean correct = false;
System. out.println("I'm thinking of a number between 1 and 100.\nYou have 5 tries to guess the number.");
while (k > 0) {
System. out.println("Enter your guess: ");
int guess = input.next();
// if the user guesses correctly, print the congratulation message and exit the program
if (guess == answer) {
System. out.println("You guessed the number!\nYou win!");
break;
}
// if the user guesses greater than the number, print the message and reduce the number of
// trials
else if (guess > answer) {
System.out.println("Your guess is too high.\nYou have " + (k - 1) + " tries left.");
k--;
}
// if the user guesses less than the number, print the message and reduce the number of
// trials
else {
System.out.println("Your guess is too low.\nYou have " + (k - 1) + " tries left.");
}
// after each trial decrease the number of trials by 1
k--;
}
// if the user has run out of trials, print the message and exit the program
if (correct==false) {
System.out.println("You ran out of tries.\nYou lose!");
}
}
}
int guess = input.next();这一行在命令提示符中表示类型不匹配
我试着把int改成intreger,但是系统说这是类型不匹配。我看了看别人,也试了试他们的说法。
2条答案
按热度按时间ee7vknir1#
你的台词
next()方法传递了一个
String
,而您希望将其存储为int
或Integer
,因此您需要转换数据。以下是一些建议,但也可能存在一些警告:doinxwow2#
next()
方法返回一个String
。Java是强类型的,除非已知它是安全和明确的,否则不会静默地将内容从一种类型转换为另一种类型(例如:悄悄地将int
类型的值转换为long
--这总是合适的),或者在一个小的、枚举的环境集合中,如果这些特性是今天设计的,那么java可能不会是这样工作的。int x = next()
不起作用- java不会自动尝试将字符串值转换为int值。您必须指定[A]你想让java做这件事,以及它应该怎么做。或者,简单地使用scanner的API,它有
.nextInt()
方法可以为您完成此操作:int x = s.nextInt()
.