2017-10-09 57 views
-2

今天我們有一個非常棘手的任務,並且在解決它時遇到了一些麻煩。我不斷收到錯誤信息:「非靜態變量名稱不能從靜態上下文中引用」。我的猜測是我在使用我的代碼時遇到了一個重大錯誤,我正在尋求一些幫助。任何幫助提前感謝!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); 
} 
} 
+1

您的錯誤消息說明了一切。 'firstname'是一個實例變量,你試圖從一個靜態函數main()中訪問它。 – dave

回答

0

您不能從靜態方法引用this實例。您可以在main方法開始創建IfPractice實例,然後是指這種情況下是這樣的:

IfPractice ip = new IfPractice(); 
ip.nickname = 「Jim」; 
0

非常基本的Java概念。並且錯誤消息顯示全部: firstname是一個實例變量,您不能從靜態函數main()訪問它。

您可以將屬性更改爲靜態 - 將行移動到main()函數中,並從main()函數中刪除所有this.部分。

import java.util.Scanner; 
public class IfPractice 
{ 
    public static void main (String[] args) 
    { 
    System.out.print("Enter your full name: "); 
    System.out.print("Hello," + name +"!"); 
    Scanner name = new Scanner(System.in); 
    String name = scan.nextLine(); 
    int space = name.indexOf(" "); 
    String firstName = name.substring(0, space); 
    private String nickname; 
    ...... 
} 
相關問題