我只是想创建一个简短的java程序来向用户请求一个int,然后将3添加到该int并显示它。出于某种原因,我的语法都错了。
import java.util.Scanner;
public class test {
public int attempt (int b) {
return 3+entry;
}
int r = attempt(entry);
public static void main (String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter single digit int ");
int entry = keyboard.nextInt();
System.out.println("Your number is " + entry);
System.out.println("Your number is " );
System.out.println("The final result is " + r);
}
}
答案 0 :(得分:6)
import java.util.Scanner;
public class test {
// this function should be static
public static int attempt (int b) {
//b for entry, since b is the name of the variable
return 3 + b;
}
public static void main (String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter single digit int ");
int entry = keyboard.nextInt();
//put this in your main function
int r = attempt(entry);
System.out.println("Your number is " + entry);
System.out.println("Your number is " );
System.out.println("The final result is " + r);
}
}
我认为你应该通过一些java教程......
答案 1 :(得分:1)
您无法调用非静态函数或从静态函数引用非静态变量。
所以基本上你必须写
public static int attempt ....
static int r = ...
问题是静态方法在类测试上运行,而非静态方法在类测试的实例上运行。