簡體   English   中英

我為 para 構造函數創建的 class 的 object 顯示錯誤。 我得到的錯誤是找不到符號

[英]The object that I created of the class for para constructer is showing a error. The error that I am getting is that that the symbol cant be found

import java.util.*;
public class StudentMain{
public static void main(String[] args){
    
    
Scanner scan = new Scanner(System.in);
System.out.println("Enter Student's Id:");
int Id=scan.nextInt();
scan.nextLine();
System.out.println("Enter Student's Name:");
String Name=scan.nextLine();

System.out.println("Enter the Student's address");
String Address=scan.nextLine();

System.out.println("Whether the student is from NIT(Yes/No):");
String option=scan.nextLine();

if(option.equals("YES")){
    
    Student stu = new Student(Id,Name,Address);
}
else if (option.equals("NO")){
    System.out.println("Enter the college name:");
    String collName=scan.nextLine();
    
    Student stu= new Student(Id,Name,Address,collName);
}

System.out.println("Student id:" + stu.getStudentId());

System.out.println("Student name:" + stu.getStudentName());
System.out.println("Address:"+ stu.getStudentAddress );
System.out.println("College Name:" +stu.collegeName);

這是執行 stu.getStudentName()、stu.getStudentAddress()、stu.getStudentId() 和 stu.CollegeName() 時出錯的地方

}
class Student {
private int studentId;
private String studentName;
private String studentAddress;
private String collegeName;

public Student(int Id,String Name,String Address)
{
    this.studentId=Id;
    this.studentName=Name;
    this.studentAddress=Address;
    collegeName="NIT";
}
public Student(int Id,String Name,String Address,String collName)
{
    this.studentId=Id;
    this.studentName=Name;
    this.studentAddress=Address;
    this.collegeName=collName;
}
public int getStudentId()
   {
       return studentId;
   }
public String getStudentName()
   {
       return studentName;
   }
public String getStudentAddress()
   {
       return studentAddress;
   }
public String getCollegeName()
   {
       return collegeName;
   }
   }}

我得到的錯誤是“Student stu=new Student(Id,Name,Address,collName);”非 static 變量,這不能從 static 上下文中引用,並且打印語句中的 stu.getStudentId() 是找不到符號我是無法理解為什么會發生此錯誤以及如何修復它。

如果您希望“stu”可用,則必須在使用它的同一塊或包含它的塊中聲明它。 基本上,您在這里(以及上面的位)創建並立即銷毀“stu”。

if(option.equals("YES")){
    ...{
        System.out.println("Enter the college name:");
        String collName=scan.nextLine();
        
        Student stu= new Student(Id,Name,Address,collName);
    }
    
    System.out.println("Student id:" + stu.getStudentId());

您在這兩行中缺少括號 ():

System.out.println("Address:"+ stu.getStudentAddress );
System.out.println("College Name:" +stu.collegeName);

它應該看起來像

System.out.println("Address:"+ stu.getStudentAddress());
System.out.println("College Name:" +stu.getCollegeName());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM