![](/img/trans.png)
[英]Java. User's input is working in main class through instance variable but not in other class
[英]Java. My one class's input from user is not return to main program
Java。 我的一堂課的用戶輸入不返回主程序
對於user1.guess1的值,此處其他類僅返回0,而不是用戶輸入的值。 在這里需要幫助,如何獲取用戶輸入的原始值。
class randtestdrive
{
public static void main(String[] args){
user user1 = new user();
user1.guess();
int a = user1.guess1 ;
int b = 5;
//for user1.guess1's value here other class is returing only 0 instead of value entered by the user.
// need help here how I can get the orignal value entered by the user.
System.out.println(user1.guess1+" test A's value");
if (a==b)
System.out.println("Hit");
else if(user1.guess1 != b)
System.out.println("Missed!");
}
}
class user
{
Scanner in = new Scanner(System.in);
int guess1;
void guess()
{
System.out.println("Guess the random number in 1-10");
int guess1 = in.nextInt();
}
}
這個:
int guess1 = in.nextInt();
是局部變量,而不是實例變量,請刪除int
,它將起作用。
這是您的user
類別:
class user {
Scanner in = new Scanner(System.in);
int guess1;
void guess() {
System.out.println("Guess the random number in 1-10");
int guess1 = in.nextInt();
}
}
創建新用戶時,實例變量默認情況下分配為0
。 然后,您讀入一個局部變量,該局部變量在guess()
方法的末尾被丟棄。 因此,您的主方法得到0
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.