Array program help needed
Java newbie here just trying to figure out the solution to this problem. The task is to create a program that asks a user the following:
Quote:
How many tests scores? 2 [enter]
Enter test score #1:70 [enter]
Enter test score #2:50 [enter]
Enter a score you wish to search: 50 [enter]
You scored 50 on test #2.
Or, display an error message if the score is not found. The program is to store the data in the array "exams". My code so far is below.
Exam class
Code :
public class Exam {
private int[] exams;
public Exam(int[] exams2)
{
this.exams = exams2;
}
public void sequentialSearch(int check)
{
for (int i = 0; i < exams.length; i++)
{
if (check == exams[i])
System.out.println("You got a " + check + " on exam "+ (i+1));
else
System.out.println("The test score was not found.");
}
}
}
ExamTester class
Code :
import java.util.Scanner;
public class ExamTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("How many exams?");
int numexams = keyboard.nextInt();
int[] exams = new int[numexams];
for (int a = 0; a < numexams; a++)
{
System.out.print("Enter a score on test # "+ (a+1) + ": " );
exams[a] = keyboard.nextInt();
}
System.out.println("Enter a score that you want to search: ");
int check = keyboard.nextInt();
Exam e = new Exam(exams);
e.sequentialSearch(check);
}
}
The program works, but it always outputs "The test score was not found" even after saying "You got x on exam y". I know it has something to do with that for loop, but I am stuck on how to fix it. Any help would be GREATLY appreciated!
Thanks!!
Re: Array program help needed
You should add a flag to the loop letting you know a score was found, rather than the if/else, at least I'm guessing this is the behavior you want
Code :
boolean found = false;
for (int i = 0; i < exams.length; i++)
{
if (check == exams[i]){
System.out.println("You got a " + check + " on exam "+ (i+1));
found = true;
}
}
if ( !found ){
System.out.println("The test score was not found.");
}
Re: Array program help needed
Oh man I can't believe I didn't think of a boolean. Thanks so much!