Reputation: 161
A loop in my class is not returning the expected value. It should return true when the value entered in the method is equal to one of the values in the area. When I compile and run my main method: "Please enter the id number to be checked" I enter 2 "you entered a number for the id" "565" "456" "342" "234" "237" "192" "237" "109" "278" "num u entered 2 true" "The value you entered is false" "Press any key to continue . . ."
The "num u entered 2 true" line is useless, and was just used for testing. Since 2 is not equal to any of the elements equal in the array, im not sure why it would remain false.
Here is my class.
public class Account
{
int[] aNum = {565, 456, 342, 234, 237, 192, 237, 109, 278};
boolean flag = false;
public boolean aChecker(int num)
{
for(int i = 0; i < aNum.length; i++)
{
if(num == aNum[i]);
{
System.out.println(aNum[i]);
flag = true;
}
}
System.out.println("num u entered " + num + " " + flag);
return flag;
}
}
Here is my main method.
import java.math.*;
import java.text.DecimalFormat;
import java.io.*;
import java.util.*;
public class labBookFiftyThree {
public static void main(String[] args) {
Scanner myInput = new Scanner(System.in);
Account myAccounts = new Account();
int id = -1;
while (id < 0) {
System.out.println("Please enter the id number to be checked");
if (myInput.hasNextInt()) {
System.out.println("you entered a number for the id");
id = myInput.nextInt();
} else if (myInput.hasNext()) {
System.out.println("Please enter a proper value");
myInput.next();
} else {
System.err.println("No more input");
System.exit(1);
}
}
System.out.println("The value you entered is " + myAccounts.aChecker(id));
}
}
Upvotes: 1
Views: 2214
Reputation: 31699
if(num == aNum[i]);
{
System.out.println(aNum[i]);
flag = true;
}
is equivalent to
if(num == aNum[i])
/* do nothing at all */;
{
System.out.println(aNum[i]);
flag = true;
}
Because of the extra semicolon after the if
, the System.out.println
and flag = true
are not part of the if
statement. Therefore they will be performed whether or not the if
condition is true
.
Delete the last semicolon from the if
line.
Upvotes: 1