英文:
Cannot find symbol when I've defined it already
问题
The issue with the code is that it's trying to use the printf
method without specifying the object to call it on. In Java, you should use System.out.printf
to print formatted output. Here's the corrected code:
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
int guess, diff;
Random random = new Random();
Scanner in = new Scanner(System.in);
int number = random.nextInt(100) + 1;
System.out.println("I'm thinking of a number between 1 and 100");
System.out.println("(including both). Can you guess what it is?");
System.out.print("Type a number: ");
guess = in.nextInt();
System.out.printf("Your guess is: %s", guess);
diff = number - guess;
System.out.printf("The number I was thinking of is: %d", number);
System.out.printf("You were off by: %d", diff);
}
}
The code now correctly uses System.out.printf
to print formatted output.
英文:
I'm making a Guess the Number game, and this is my code for the game.
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
int guess, diff;
Random random = new Random();
Scanner in = new Scanner(System.in);
int number = random.nextInt(100) + 1;
System.out.println("I'm thinking of a number between 1 and 100");
System.out.println("(including both). Can you guess what it is?");
System.out.print("Type a number: ");
guess = in.nextInt();
System.out.printf("Your guess is: %s", guess);
diff = number - guess;
printf("The number I was thinking of is: %d", guess);
printf("You were off by: %d", diff);
}
}
However, when I try to compile it, it comes up with the following error:
Guess.java:20: error: cannot find symbol
printf("The number I was thinking of is: %d", guess);
^
symbol: method printf(String,int)
location: class Guess
Guess.java:21: error: cannot find symbol
printf("You were off by: %d", diff);
^
symbol: method printf(String,int)
location: class Guess
2 errors
What is wrong with the code?
答案1
得分: 1
我假设您正在尝试调用System.out
对象的printf
方法。这将如下所示:
System.out.printf("您的差距是:%d", diff);
您需要使用正确的对象目标进行方法调用:通常,方法调用的语法是“接收者 . 方法名称(参数)”。如果接收者是当前对象,则可以省略它。
英文:
I assume you are trying to call the printf
method of the System.out
object. That would look like:
System.out.printf("You were off by: %d", diff);
You need to make the method call using the right object target: in general the method call syntax is "receiver . method name ( parameters )". If the receiver is the current object, it can be omitted.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论