Validating against duplicate user entries when using sets - java

I am currently studying Java and have being using normal arrays so far. Next semester we will be using data structures like ArrayList etc, but i decided to read ahead. I have read that for storing data that can not be a duplicate, Sets were the data structure of choice, but in the code below the user can still enter a duplicate entry? Can any body explain the process to me and perhaps a solution to my problem?
public class Lotto {
private static final int INPUT_SIZE = 6;
private static final int MIN_NUMBER_POSSIBLE = 0;
private static final int MAX_NUMBER_POSSIBLE = 25;
private Set<Integer> userNumbers = new HashSet<Integer>();
private Set<Integer> randomNumbers = new HashSet<Integer>();
public static void main(String[] args) {
Lotto c = new Lotto();
c.generateRandomNumbers();
System.out.println("Pick " + INPUT_SIZE + " numbers from "
+ MIN_NUMBER_POSSIBLE + " to " + MAX_NUMBER_POSSIBLE + ".");
c.readUserNumbers();
if (c.doUserNumbersMatchRandomNumbers()) {
System.out.println("You win :) !");
} else {
System.out.println("Sorry you failed :( !");
c.showRandomNumbersToUser();
}
}
private void generateRandomNumbers() {
Random random = new Random();
for (int i = 0; i < INPUT_SIZE; i++) {
randomNumbers.add(random.nextInt(MAX_NUMBER_POSSIBLE));
}
}
private void showRandomNumbersToUser() {
System.out.println("\nRandom numbers where : ");
for (Integer randomNumber : randomNumbers) {
System.out.println(randomNumber + "\t");
}
}
private void readUserNumbers() {
Scanner input = new Scanner(System.in);
int inputSize = 1;
while (input.hasNextInt() && inputSize < INPUT_SIZE) {
int numberChoosen = input.nextInt();
if (numberChoosen < MIN_NUMBER_POSSIBLE
|| numberChoosen > MAX_NUMBER_POSSIBLE) {
System.out.println("Your number must be in "
+ MIN_NUMBER_POSSIBLE + " - " + MAX_NUMBER_POSSIBLE
+ " range.");
} else {
userNumbers.add(numberChoosen);
inputSize++;
}
}
}
private boolean doUserNumbersMatchRandomNumbers() {
for (Integer userNumber : userNumbers) {
if (!randomNumbers.contains(userNumber)) {
return false;
}
printMatchingNumber(userNumber);
}
return true;
}
private void printMatchingNumber(int num) {
System.out.println("Your number, " + num + ", has been called.");
}
}

Set#add(Object) returns true when the object was added successfully and false otherwise. It will not throw an exception, so you need to add a conditional to check whether the operation was successful:
if (userNumbers.add(numberChoosen)) {
System.out.println("Number added successfully");
} else {
System.out.println("Duplicate number detected");
}

Sets do not prohibit entering a unique value more than once. It is on you to check preconditions, see e.g Set.add.
So instead of just calling:
userNumbers.add(numberChoosen);
try
if (!userNumbers.contains(numberChoosen)) {
userNumbers.add(numberChoosen);
} else {
// do stuff...
}

Related

Squaring application in java

New to programming here. I need to write application that does the following...
Squaring application instructions
The code I have so far follows. I am running into a problem where my code will not read from negative integers to strings and properly prompt the user to enter valid data. I believe I need to nest my loops but am having trouble doing so. Any help would be greatly appreciated. Thanks.
import java.util.Scanner;
public class Squaring {
public static int getValidInt(int greaterThan, Scanner scan) {
System.out.println("Enter an integer greater than " + greaterThan + ":" );
int input;
while ( !scan.hasNextInt() ) {
String garbage = scan.next();
scan.nextLine();
System.out.println(garbage + " is not valid input.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
while ( !((input = scan.nextInt()) > greaterThan )) {
int garbage = input;
System.out.println(garbage + " is not greater than 1.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 1 ;
int total = 0;
a = getValidInt(a,scan);
int b = a;
System.out.println(a);
long n = a;
while ( n < 1000000 ) {
System.out.println(n*n);
n = n * n;
total = total + 1;
}
System.out.println(b + " exceeded 1,000,000 after " + total + " squarings.") ;
}
}
Without any try-catch:
public static int getValidInt(int greaterThan, Scanner scan) {
int input = 0;
boolean valid = false;
while (!valid) {
System.out.println("Enter an integer greater than " + greaterThan + ":");
if (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
} else {
input = scan.nextInt();
if (input <= greaterThan) {
System.out.println(input + " is not greater than " + greaterThan);
} else {
valid = true;
}
}
}
return input;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = getValidInt(1, scan);
System.out.println(a);
int total = 0;
long n = a;
while ( n < 1000000 ) {
n = n * n;
System.out.println(n);
total++;
}
System.out.println(a + " exceeded 1,000,000 after " + total + " squarings.") ;
}
I've come up with the following:
public static int getValidInt(int greaterThan, Scanner scan) {
int number = greaterThan;
do {
while (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
}
number = scan.nextInt();
if (number < greaterThan) {
System.out.println("input is: " + number + " minimum is: " + greaterThan);
}
} while (number < greaterThan);
return number;
}
It has a do while loop which makes sure number cannot be smaller than greaterThan, if it is it will do the while loop again.
Inside the do while loop is another loop which tells the user that their input is garbage, and will continue doing so until a number is inserted.

How can I get my program back on track when printing out all student records?

import java.util.Scanner;
public class MainBinaryTreeArray
{
public static void main(String[] args)
{
int choice;
Scanner scan= new Scanner(System.in);
BinaryTreeArray data = new BinaryTreeArray();
Listing l1 = new Listing("Carol", 4354, 3.2);
Listing l2 = new Listing("Timothy", 2353, 4.0);
Listing l3 = new Listing("Dean", 4544, 2.4);
Listing l4 = new Listing("Sue", 3445, 3.0);
data.insert(l1);
data.insert(l2);
data.insert(l3);
data.insert(l4);
do
{
// Choose which operation by entering a number
System.out.println("*****************(Menu Operations:)******************");
System.out.println(" (Press 1). Insert.");
System.out.println(" (Press 2). Fetch.");
System.out.println(" (Press 5). Output all student records.");
System.out.println(" (Press 6). Exit the program.");
System.out.println("Enter your choice: ");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("Are students inserted: " + data.insert(l1));
break;
case 2:
System.out.println("The student's info that's fetched: ");
System.out.print(data.fetch("Timothy"));
break;
case 5:
System.out.print("Output all the student's records: ");
data.showAll();
}
}while(choice!=6);
}
}
public class BinaryTreeArray
{
private Listing[] data;
private int size;
public BinaryTreeArray()
{
size = 100;
data = new Listing[size];
}
public void showAll()
{
for(int i=0; i<size; i++)
System.out.print(data[i] + " ");
}
public boolean insert(Listing newListing)
{
int i = 0;
while(i < size && data[i]!= null)
{
if(data[i].getKey().compareTo(newListing.getKey()) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size)
return false;
else
{
data[i] = newListing.deepCopy();
return true;
}
}
public Listing fetch(String targetKey)
{
int i= 0;
while(i< size && data[i]!= null && data[i].getKey()!=targetKey)
{
if(data[i].getKey().compareTo(targetKey) > 0)
i = 2 * i + 1;
else
i = 2 * i + 2;
}
if(i >= size || data[i] == null)
return null;
else
return data[i].deepCopy();
}
}
public class Listing implements Comparable<Listing>
{ private String name; // key field
private int ID;
private double GPA;
public Listing(String n, int id, double gpa)
{ name = n;
ID = id;
GPA = gpa;
}
public String toString()
{ return("Name is " + " " + name +
"\nID is" + " " + ID +
"\nGPA is" + " " + GPA + "\n");
}
public Listing deepCopy()
{ Listing clone = new Listing(name, ID, GPA);
return clone;
}
public int compareTo(Listing other)
{
return this.name.compareTo(other.getKey());
}
public String getKey()
{
return name;
}
}// end of class Listing
Hello All,
My java program compiles fine, but I am having a terrible and miserable time with getting my program to stop printing all those nulls when I output all student records in my BinaryTreeArray. Here is complete program. Any suggestions? Please do give any advice. So to make what I am saying clear, I need help with understanding why when I print out student records it includes a whole bunch of extra nulls that really have no purpose and just make my program look crazy. Any solutions to this problem?
When you initialize the BinaryTreeArray(), you set the field variable "size" to 100 and use this to initialize the data Listing[] array. When you print out the data, the loop uses the same "size" variable so you get all 100 entries, including the null entries. A simple solution would be to filter the data for null when you show all.
public class BinaryTreeArray
{
...
public void showAll()
{
for(int i=0; i<size; i++)
{
if (data[i] != null)
System.out.print(data[i] + " ");
}
}
...
}
An alternate solution would be to change your use of size to maxSize and then create a variable size that is incremented as you insert listings.

How to save user input in an array an check later if its already in the array in java?

I have to make a random number guessing game, where each round I have have a limit of 10 guesses. The part that I am confused about is where I need to check if any of the guesses are repeated in that round. I know I have to make an array and store the numbers in there but I am not sure how to do that.
Here is my entire code, everything else works as intended:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
private static final int MIN_NUMBER = 1;
private static final int MAX_NUMBER = 205;
private static final int QUIT_VALUE = -1;
private static final int LOSE_VALUE = -2;
private static final int MAX_GAMES = 2;
private static final int MAX_GUESSES = 10;
private static final int HINT_THRESHOLD = 5;
private static final int BACKDOOR_VALUE = -314;
private static final String NOPE_MSG = "nope...";
private static final String NOPE_NOPE_MSG =
"you've already guessed that wrong guess...";
private static final String INVALID_INPUT_BEGIN =
"*** invalid input -- ";
private static final String INVALID_INPUT_LESS_MIN_MSG =
INVALID_INPUT_BEGIN + "must be greater than " + (MIN_NUMBER - 1);
private static final String INVALID_INPUT_GREATER_MAX_MSG =
INVALID_INPUT_BEGIN + "must be less than " + (MAX_NUMBER + 1);
private static final String INVALID_INPUT_YN_MSG =
INVALID_INPUT_BEGIN + "must be n or y";
private static final String WINNER_MSG =
"you're a winner... # of guesses: ";
private static final String LOSER_MSG =
"too many guesses entered... the number was ";
private static final String QUITTER_MSG =
"you're a quitter... the number was ";
private static final String MAX_GAMES_PLAYED_MSG =
"you've played the maximum number (" + MAX_GAMES + ") of games";
private static final String ENTER_GUESS_PROMPT =
"enter a guess between " + MIN_NUMBER + " and " + MAX_NUMBER +
" (" + QUIT_VALUE + " to quit): ";
private static final String PLAY_AGAIN_PROMPT =
"Do you want to play again (n or y)? ";
private static final String BOLD_BEGIN = "*** ";
private static final String BOLD_END = " ***";
private static final String PLAY_MSG = " playing the CSC" + MAX_NUMBER +
" guessing game." + BOLD_END;
private static final String WELCOME_MSG =
BOLD_BEGIN + "Hello! Have fun" + PLAY_MSG;
private static final String THANKS_MSG =
BOLD_BEGIN + "Thanks for" + PLAY_MSG;
static Random rng = new Random(System.currentTimeMillis());
static Scanner stdin = new Scanner(System.in);
static Scanner scan = new Scanner(System.in);
static int guess;
static int numberOfGames = 0;
static int numberOfWins = 0;
static int numberOfLoses = 0;
static boolean endStart = true; // Check if this boolean is used
public static void main(String[] args) {
PlayGame();
PostGame();
EndGame();
}
public static void PlayGame() {
int guessCounter = 0;
int n = MIN_NUMBER + rng.nextInt(MAX_NUMBER);
System.out.println(WELCOME_MSG);
boolean test = true;
do {
System.out.println();
System.out.print(ENTER_GUESS_PROMPT);
guess = stdin.nextInt();
guessCounter = guessCounter + 1;
if (guess < MIN_NUMBER && guess != BACKDOOR_VALUE &&
guess != QUIT_VALUE) {
System.out.println(INVALID_INPUT_LESS_MIN_MSG + "\n");
}
if (guess > MAX_NUMBER) {
System.out.println(INVALID_INPUT_GREATER_MAX_MSG + "\n");
}
// Giving the user the answer
if (guess == BACKDOOR_VALUE) {
System.out.println(n);
}
// Quiting the round and giving the chance to end the game
if (guess == QUIT_VALUE) {
System.out.println((QUITTER_MSG + n) + "\n" +
PLAY_AGAIN_PROMPT);
numberOfLoses++;
String val = scan.next();
if (val.equalsIgnoreCase("y")) {
numberOfGames++;
PlayGame();
}
if (val.equalsIgnoreCase("n")) {
System.out.println(THANKS_MSG);
test = false;
PostGame();
break;
}
}
// Correct guess on the last try
if (guessCounter == MAX_GUESSES || guess == n) {
numberOfGames++;
System.out.println(WINNER_MSG + guessCounter);
numberOfWins++;
System.out.println(PLAY_AGAIN_PROMPT);
String val = scan.next();
if (val.equalsIgnoreCase("y"))
PlayGame();
if (val.equalsIgnoreCase("n")) {
System.out.println(THANKS_MSG);
test = false;
PostGame();
break;
}
}
// Max games
if (numberOfGames == MAX_GAMES) {
System.out.println(MAX_GAMES_PLAYED_MSG);
test = false;
PostGame();
break;
}
// Max guesses
if (guessCounter == MAX_GUESSES) {
numberOfGames++;
System.out.println(LOSER_MSG + n + "\n" + PLAY_AGAIN_PROMPT);
numberOfLoses++;
String val = scan.next();
if (val.equalsIgnoreCase("y"))
PlayGame();
if (val.equalsIgnoreCase("n")) {
System.out.println(THANKS_MSG);
test = false;
PostGame();
break;
}
}
// Guessing in the range of the bonds
if (guess > MIN_NUMBER || guess < MAX_NUMBER) {
if (guess != n) {
System.out.print(NOPE_MSG);
}
if (guess == n) {
numberOfGames++;
System.out.println(WINNER_MSG + guessCounter);
numberOfWins++;
System.out.println(PLAY_AGAIN_PROMPT);
String val = scan.next();
if (val.equalsIgnoreCase("y"))
PlayGame();
if (val.equalsIgnoreCase("n")) {
System.out.println(THANKS_MSG);
test = false;
PostGame();
break;
}
}
}
// Giving hints after 5 tries until the max # of guesses
if (guessCounter == HINT_THRESHOLD ||
guessCounter == (HINT_THRESHOLD + 1) ||
guessCounter == (HINT_THRESHOLD + 2) ||
guessCounter == (HINT_THRESHOLD + 3) ||
guessCounter == (HINT_THRESHOLD + 4) ||
guessCounter == (HINT_THRESHOLD + 5)) {
if (guess != n && guess > n) {
System.out.println(" lower");
}
if (guess != n && guess < n) {
System.out.println(" higher");
}
}
}
while (guess > MIN_NUMBER || guess < MAX_NUMBER);
}
// Post game information
public static void PostGame() {
int winningPct = 0;
System.out.print("Played: " + numberOfGames + ";" +
" Won: " + numberOfWins + ";" +
" Lost: " + numberOfLoses + ";");
if (numberOfGames != 0) {
System.out.println(" winningPct: " +
(winningPct = numberOfWins / numberOfGames));
} else {
winningPct = 0;
}
EndGame();
}
// Ending the game
public static void EndGame() {
}
}
Using array to check if a number is guessed earlier is not optimal way. It limits the range of numbers you can guess even if the number of tries is not very high. Also most of the indexes of the array will remain empty in general.
So, better you can use Set<Integer> (or Set<Long> depending on allowed range of number that is guessed). Here is an example code:
Set<Integer> guessedNumbers = new HashSet<Integer>();
if(guessedNumbers.contains(guess)){
System.out.println("You already guessed this earlier");
}
else{
guessedNumbers.add(guess);
}
The part that I am confused about is where I need to check
Huh, i was confused too when i read this code...
So, let's start!
Do you really need all these string constants? They are not reused often so why don't just print messages?
static Random rng = new Random(System.currentTimeMillis()); - it's unmeaningful name. Rename to random, randomGenerator or something else.
static int guess; why don't initialize to 0 or remove other initializations. Looks inconsistent.
static boolean endStart = true; endStart? Really?! That variable name contrary to yourself. // Check if this boolean is used - i checked with Ctrl+f in browser -> 0 usages.
boolean test = true; test of what? For what? numberGuessed, isGuessed would be better.
guessCounter = guessCounter + 1; change to guessCounter++; just for simplicity.
Is PlayGame(); recursive? Looks odd.
These are just some stranges in code for me, but overall design is overcomplicated too:
Try to concentrate on "main loop" that presents in many games and hide all cluttering service actions in separate functions.
I'm not sure but you can use objects to make interaction with game more "natural". Something like:
Game game = new Game();
Player player = new Player();
boolean numberGuessed = false;
while (!numberGuessed) {
int guess = player.makeGuess();
if (game.checkGuess(guess)) {
System.out.println("You win!");
} else {
System.out.println("Please, try again");
}
class Player {
private int guessCount;
public String grabInput() {
System.out.println("Make a guess");
System.out.print("> ");
// take Scanner input, parse number or exit message
}
public int makeGuess() {
//present your guess
guessCount++;
}
}
That is very very rough outline but i think it helps you rethink application design.
Ah, your original question... almost forget about it.
Write the function (actually method) that iterates over array and checks given number for existence. In my example you can incapsulate such function in player.makeGuess() function

Multi-threading same code at the same time

I want my program to test two BigIntegers at the same time. As of now my code is testing one at a time. Since I want the code to be the same for both runs, is there a simple synchronized statement that I would be able to use to implement this?
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Enter number ");
int number = Integer.parseInt(input);
BigInteger num = new BigInteger(input);
String output = num + " is" + (IsPrime(num) ? " " : " not ")
+ "a prime number.";
JOptionPane.showMessageDialog(null, output);
}
public static boolean IsPrime(BigInteger num) {
if (num.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
return false;
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(num) <= 0; i =
i.add(new BigInteger("2"))) {
if (num.mod(i).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
return true;
}
}
I have reached a solution to my question.
Because two integers were being tested I needed to create a textOne and a textTwo to test each individually for primeness.
public static boolean IsPrime(BigInteger textOne) {
// check if number is a multiple of 2
if (textOne.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
return false;
}// if not, then just check the odds
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(textOne) <= 0; i =
i.add(new BigInteger("2"))) {
if (textOne.mod(i).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
return true;
}
public static boolean IsPrime2(BigInteger textTwo) {
// check if number is a multiple of 2
if (textTwo.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
return false;
}// if not, then just check the odds
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(textTwo) <= 0; i =
i.add(new BigInteger("2"))) {
if (textTwo.mod(i).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
return true;
}
I designated that num and num2 be designated for the BigIntegers so that output would reflect the following..
public void run() {
String output = num + " is" + (IsPrime(num) ? " " : " not ")
+ "a prime number.";
lblResults.setText(output);
String output2 = num2 + " is" + (IsPrime(num2) ? " " : " not ")
+ "a prime number.";
lblResults2.setText(output2);
}}

Create a loop to generate a new "user" with own variable names if user makes number of users = 2, or 3, etc

You don't have to read all my code, don't worry. My main problem is highlighted in the body of this message.
I am very new to programming. I'm supposed to create a Java program that reads a string input, separates that string into chars mapped to an array (that array is a Memo for answers to multiple choice Questions). Then read another string input from user, separate that input into chars in an array as well, and then compare the two array indices. basically, it's supposed to see how many array indices are the same, and then generate a score of correct answers (it's a multiple choice answer program, so the chars in the strings will be A B or C).
I have to store the student's (user's) name and keep his score. But the program will ask you for how many students there are and then run a loop asking of name, and answer (as many times as the amount of students you typed in. Max is 10), then compare the answer to the memo, generate a score, and use all the students answers to calculator an average score. So far I have managed to create a program that will do this for one user. The problem I have is looping it to store multiple user names, and scores, to calculate an average score.
Here is my code. if you copy and paste this into your IDE, you'll see that it runs perfectly (apart from some error handling and JOptionPane dialog button stuff left out). But it will only work IF you enter the number of users as 1. Anything else, and it won't run properly. So how do I get it to loop for several users?
package multiquestions;
import javax.swing.JOptionPane;
public class MultiQuestions {
public static void main(String[] args) {
String aMemo = getInput0();
int aStudentNumber = getInput1();
String aStudentName = getInput2();
String aStudentAnswer = getInput3();
int aScore = CalcScore(aStudentAnswer, aMemo);
if (aStudentNumber == 1) {
StudentInfo(aStudentName, aScore);
}
System.exit(0);
}
public static String getInput0() {
String Memo = JOptionPane
.showInputDialog("Please enter the memo answers to the 10 multiple choice questions\nno spaces and all in Capital letters e.g.ABCDEABCDE");
return Memo;
}
public static int getInput1() {
int StudentNumber = Integer.parseInt(JOptionPane
.showInputDialog("Please enter the number of students in the class"));
return StudentNumber;
}
public static String getInput2() {
String StudentName = JOptionPane.showInputDialog("Please enter the student's name");
return StudentName;
}
public static String getInput3() {
String StudentAnswer = JOptionPane
.showInputDialog("Please enter the student's answers to the 10 multiple choice questions\nno spaces and all in Capital letters e.g.ABCDEABCDE");
return StudentAnswer;
}
public static int CalcScore(String bStudentAnswer, String bMemo) {
int One;
int Two;
int Three;
int Four;
int Five;
int Six;
int Seven;
int Eight;
int Nine;
int Ten;
char Reference[] = new char[10];
for (char Ref : Reference) {
Reference[0] = bMemo.charAt(0);
Reference[1] = bMemo.charAt(1);
Reference[2] = bMemo.charAt(2);
Reference[3] = bMemo.charAt(3);
Reference[4] = bMemo.charAt(4);
Reference[5] = bMemo.charAt(5);
Reference[6] = bMemo.charAt(6);
Reference[7] = bMemo.charAt(7);
Reference[8] = bMemo.charAt(8);
Reference[9] = bMemo.charAt(9);
}
char Answer[] = new char[10];
for (char Ans : Answer) {
Answer[0] = bStudentAnswer.charAt(0);
Answer[1] = bStudentAnswer.charAt(1);
Answer[2] = bStudentAnswer.charAt(2);
Answer[3] = bStudentAnswer.charAt(3);
Answer[4] = bStudentAnswer.charAt(4);
Answer[5] = bStudentAnswer.charAt(5);
Answer[6] = bStudentAnswer.charAt(6);
Answer[7] = bStudentAnswer.charAt(7);
Answer[8] = bStudentAnswer.charAt(8);
Answer[9] = bStudentAnswer.charAt(9);
}
/*
* Below is the list of if statements which add one to each variable (Variables One to Ten
* declared at top of this method) if the array characters match each other at their indeces
*/
if (Reference[0] == Answer[0]) {
One = 1;
} else {
One = 0;
}
if (Reference[1] == Answer[1]) {
Two = 1;
} else {
Two = 0;
}
if (Reference[2] == Answer[2]) {
Three = 1;
} else {
Three = 0;
}
if (Reference[3] == Answer[3]) {
Four = 1;
} else {
Four = 0;
}
if (Reference[4] == Answer[4]) {
Five = 1;
} else {
Five = 0;
}
if (Reference[5] == Answer[5]) {
Six = 1;
} else {
Six = 0;
}
if (Reference[6] == Answer[6]) {
Seven = 1;
} else {
Seven = 0;
}
if (Reference[7] == Answer[7]) {
Eight = 1;
} else {
Eight = 0;
}
if (Reference[8] == Answer[8]) {
Nine = 1;
} else {
Nine = 0;
}
if (Reference[9] == Answer[9]) {
Ten = 1;
} else {
Ten = 0;
}
int Score = One + Two + Three + Four + Five + Six + Seven + Eight + Nine + Ten;
return Score;
}
public static void StudentInfo(String bStudentName, int bScore) {
switch (bScore) {
/*
* Below is case stament for values of bScore(score returned from CalcScore() For each value of
* bScore it must do something specific
*/
case 10:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 A Marvelous");
break;
case 9:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 A Marvelous");
break;
case 8:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 B Outstanding");
break;
case 7:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 C Significant");
break;
case 6:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore
+ "/10 D Above Average");
break;
case 5:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore
+ "/10 E Barely Adequate");
break;
case 4:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 F Fail");
break;
case 3:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 F Fail");
break;
case 2:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 F Fail");
break;
case 1:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 F Fail");
break;
case 0:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 F Fail");
}
}
public static void Exit() {
int exit = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?");
if (exit == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
public static void CalcAverage() {}
}
Might be helpful for learning purpose (assuming strings are not null and lengths of strings are equal):
public static int CalcScore(String bStudentAnswer, String bMemo) {
char[] answer = bStudentAnswer.toCharArray();
char[] memo = bMemo.toCharArray();
int score = 0;
for (int i = 0; i < answer.length; i++) {
if (answer[i] == memo[i]) score++;
}
return score;
}
instead of saying if == 1, do
for (int i = 0; i < aStudentNumber; i++) {
String aStudentName = getInput2();
String aStudentAnswer = getInput3();
int aScore = CalcScore(aStudentAnswer, aMemo);
StudentInfo(aStudentName, aScore);
}
Now, if you want to store that data programmatically so you can access it later on, change your StudentInfo method to something like
public static StudentInfo createStudentInfo(String bStudentName, int bScore){
...
return someObj;
}
where someObj is a an instance of a StudentInfo class (that you have to create) that actually holds all of the data you want to keep track of. Then, simply add that class to a list (inside your loop):
ArrayList<StudentInfo> siList = new ArrayList<StudentInfo>();
for (int i = 0; i < aStudentNumber; i++) {
String aStudentName = getInput2();
String aStudentAnswer = getInput3();
int aScore = CalcScore(aStudentAnswer, aMemo);
//StudentInfo(aStudentName, aScore); // get rid of this line since we are adding it to a list now
siList.add(createStudentInfo(aStudentName, aScore));
}
Now you can recall all of that data if need be.
The biggest thing is that you need a loop. Loop until the index is at your count, and perform the same actions for each answer set.
Edit: The following is to address the question posted in the comments.
I think you're better off with a constructor. Use a class something like this:
public class StudentInfo {
private String bStudentName;
private int bScore;
public StudentInfo (String bStudentName, int bScore) {
this.bStudentName = bStudentName;
this.bScore = bScore;
}
public String getStudentName() {
return this.bStudentName; //'this' keyword not really necessary, but helpful
}
public int getScore() {
return this.bScore;// again, 'this' not necessary
}
public void doStuff() { // optional method to do stuff with the data if need be
...
}
}
Then, in your loop, do
ArrayList<StudentInfo> siList = new ArrayList<StudentInfo>();
for (int i = 0; i < aStudentNumber; i++) {
String aStudentName = getInput2();
String aStudentAnswer = getInput3();
int aScore = CalcScore(aStudentAnswer, aMemo);
//StudentInfo(aStudentName, aScore); // get rid of this line since we are adding it to a list now
//siList.add(createStudentInfo(aStudentName, aScore));
StudentInfo si = new StudentInfo(aStudentName, aScore);
si.doStuff(); // optional method call in case you want to do something with the data other than store it.
siList.add(si);
}
your StudentInfo class should be in the same package as your main class. If, for some reason, it is not, at the top of your main class add include theotherpackage.StudentInfo;

Categories

Resources