我有一個類和一個公共類,並且想要在該類中爲用戶輸入的數據分配一個變量。是否有可能以這種方式做到這一點,或者我必須移動變量。Java:調用一個類變量併爲其分配一個值
這是我的代碼
import java.util.Scanner;
class People {
String name;
int age;
String hair_colour;
String personality;
void confirm(){
System.out.println(name +" is " + age + " years old and has "
+ hair_colour + " hair and has a " + personality +" personality");
System.out.println("Is this correct? Y/N");
Scanner correct = new Scanner(System.in);
String reply = correct.nextLine();
if(reply=="Y" || reply=="y"){
System.out.println("Profile confirmed. Thank you.");
}
else {
System.out.println("Returning to profile creation");
}
}
}
public class PeopleProfile {
public static void main(String[]args){
Scanner input_details = new Scanner(System.in);
System.out.println("Please enter a name: ");
String given_name = input_details.nextLine();
System.out.println("Please enter a age: ");
int given_age = input_details.nextInt();
System.out.println("Please enter the persons hair colour: ");
String given_hair_colour = input_details.nextLine();
System.out.println("Please enter the persons personality: ");
String given_personality = input_details.nextLine();
}
}
你的代碼是顯著難度比閱讀如果你按照慣例格式化了它,那麼最好使用常規名稱。另外,請參閱http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java。但請注意,您目前甚至沒有創建「People」實例... –
爲了澄清我試圖將given_name分配給名稱(因爲在嘗試在其中調用名稱時出現錯誤)等等的輸入。 – Nathan
@Nathan沒有人的實例,沒有分配的名稱。您必須首先實例化People對象,然後才能爲該對象指定名稱。 –