今天我們有一個非常棘手的任務,並且在解決它時遇到了一些麻煩。我不斷收到錯誤信息:「非靜態變量名稱不能從靜態上下文中引用」。我的猜測是我在使用我的代碼時遇到了一個重大錯誤,我正在尋求一些幫助。任何幫助提前感謝!Java中的非靜態變量錯誤作業
import java.util.Scanner;
public class IfPractice
{
Scanner name = new Scanner(System.in);
String name = scan.nextLine();
int space = name.indexOf(" ");
String firstName = name.substring(0, space);
private String nickname;
private String ageResponse;
int age = scan.nextInt();
public static void main (String[] args)
{
System.out.print("Enter your full name: ");
System.out.print("Hello," + name +"!");
if (firstname.equals(("James") || ("james"))) {
this.nickname = "Jim";
}
else if(firstname.equals(("Robert") || ("robert"))) {
this.nickname = "Bobby";
}
else if(firstname.equals(("Ashwani") || ("ashwani"))) {
this.nickname = "Ash";
}
else {
this.nickname = "Buddy";
}
System.out.println("I think I will call you" + this.nickname);
System.out.println("How old are you? ");
if (age <= 18) {
this.age = "You are a child";
}
else if ((age >= 18) && (age <= 21)) {
this.age = "You are a child";
}
else if ((age >= 21) && (age <= 65)) {
this.age = "You can vote, but you can not drink";
}
else {
this.age = "You can get Social Security";
}
System.out.println(ageResponse);
}
}
您的錯誤消息說明了一切。 'firstname'是一個實例變量,你試圖從一個靜態函數main()中訪問它。 – dave