剛剛瞭解到調用方法和想法我會嘗試一下,但我的代碼無法正常工作。它應該採取2個名字和打印。就這樣。我的變量是全局的,所以我所有的方法都應該能夠看到它們,但是當程序運行時它會打印出'null'。有人可以解釋爲什麼這不起作用嗎?這與傳遞變量有關嗎?我想如果這是全球性的,我不需要這樣做?調用方法/變量範圍
import java.util.Scanner;
public class UserID {
String firstName;
String secondName;
public void readNames(){
Scanner scan = new Scanner(System.in);
System.out.print("Enter first name: ");
firstName = scan.nextLine();
System.out.print("Enter second name: ");
secondName = scan.nextLine();
scan.close();
}
public void printID(){
System.out.println("Your user ID is: " + firstName);
}
public static void main(String[] args) {
UserID readNames = new UserID();
UserID printID = new UserID();
readNames.readNames();
printID.printID();
}
}
爲什麼要創建同一個類的兩個對象?一旦你找出這個問題,你應該能夠弄清楚它 – 3kings
Java中沒有這樣的全局變量。 – chrylis