【发布时间】:2020-07-24 13:32:33
【问题描述】:
我正在尝试从函数“checkUser”返回一个布尔输出,然后为此打印一个输出。但是对于每次运行,即使条件正确,它也总是返回“false”。我使用了一个对象来保存布尔结果,因为 return 语句在“if”中不起作用。 另外,我在'getCheck()'函数中得到提示-'方法断点'。我做错了什么吗?
import java.util.Scanner;
class myclass {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Bank[] bk=new Bank[4];
System.out.println("Enter the Name, Age and the Acc No. of 3 users : ");
for(int i=0; i<3; i++) {
//System.out.print("Enter the Name : ");
String name=sc.next();
//System.out.print("Enter the age : ");
int age=sc.nextInt();
//System.out.print("Enter the Account Number : ");
int acc_no=sc.nextInt();
bk[i]=new Bank(name, age, acc_no);
}
System.out.println("Enter the Account no to validate a user : ");
int acc_chk=sc.nextInt();
// method calling
boolean c=checkUser(bk, acc_chk);
// Outputs
if(c)
System.out.println("The user account exits!");
else
System.out.println("The user account does not exit!");
}
// method to check the authenticity of the user
public static boolean checkUser(Bank[] obj, int ac_no) {
//boolean ch;
int j=0;
for(int i=0; i<3; i++) {
if(ac_no==obj[i].getAcc()) {
obj[i].setCheck(true);
j=i;
}
}
return obj[j].getCheck();
}
}
class Bank{
String name;
int age;
int acc;
String type;
boolean check;
public Bank(String s, int a, int b) {
}
public void setName(String s) {this.name=s;}
public void setAge(int a){this.age=a;}
public void setAcc(int b){this.acc=b;}
public void setType(String t) {this.type=t;}
public void setCheck(boolean ch){this.check=ch;}
public String getName() {return name;}
public int getAge() {return age;}
public int getAcc() {return acc;}
public String getType() {return type;}
public boolean getCheck() {return check;}
}
【问题讨论】:
-
你用过调试器吗?
-
首先你需要初始化 ch 变量,因为它是一个局部变量,你为什么使用 obj[0] ,它应该是 obj[i] 。
-
尝试使用有意义的变量名。
j=obj[i].getAcc()比acc = banks[i].getAcc()(甚至getAccountNumber())更难理解。长变量不会让你的程序变慢,但会让你的程序阅读速度更快 -
@HarmandeepSinghKalsi 在哪里?从我所看到的情况来看,他们正在使用它之前对其进行初始化。此外,
ch是一个bool,无论如何它都会在声明时初始化为false。 -
@HarmandeepSinghKalsi 不是真的,“你需要”与“它很好”不同。更好的做法是在使用前移动声明。