I'm making a slot machine for a college project. There are loads and loads of similar projects talked about online however the requirements for my project are slightly different. Here is my task:
The player starts with £1 credit, with each go costing 20 p.
If the Fruit Machine “rolls” two of the same symbol, the user wins 50 p.
The player wins £1 for three of the same and £5 for 3 Bells.
The player loses £1 if two skulls are rolled and all of his/her money if three skulls are rolled.
The player can choose to quit with the winnings after each roll or keep playing until there is no money left.
What I've come up with so far is this:
for ( int runCount = 1; runCount <= 3; runCount ++ ) {
int symIndex = r.nextInt(6);
if (symIndex == 0) {
symbol = "cherry";
} else if (symIndex == 1){
symbol = "orange";
} else if (symIndex == 2){
symbol = "lemon";
} else if (symIndex == 3){
symbol = "bell";
} else if (symIndex == 4){
symbol = "star";
} else if (symIndex == 5){
symbol = "skull";
}
if (runCount == 1){
reel1 = symbol;
} else if ( runCount == 2 ){
reel2 = symbol;
} else if ( runCount == 3 ){
reel3 = symbol;
}
}
System.out.println(reel1 + " " + reel2 + " " + reel3);
Which is great and spits out 3 random symbols but what is I need is a way is for it to somehow treat the bell and skull symbols differently. There must be an easier way than write out every possible combination in an if statement. In all the other projects I've seen the prize if statements have looked something like this
if (reel1 == reel2 && reel1 == reel3 && reel2 == reel3)
System.out.println("You have won!");
Or something about that etc etc. But if I do it this way it's not defining the actual symbol but just storing it in one of the reel variables so I can't make if statements for those specific outcomes.
Any help would be greatly, greatly appreciated. Even if you could just tell me how to phrase my question properly so I could search it would be helpful
I've changed things a little. Rather than storing 3 unique fields reel1, reel2 and reel3 you can re-use the counter variable you're using to control the for-loop to place the chosen symbols into an array. Note: you need to start the counter at 0, but this makes little/no difference.
private static final String CHERRY = "cherry";
private static final String ORANGE = "orange";
private static final String LEMON = "lemon";
private static final String BELL = "bell";
private static final String STAR = "star";
private static final String SKULL = "skull";
private static final Random random = new Random();
public static void main(String[] args) {
String[] symbols = new String[3];
pickRandomSymbolsForReels(symbols);
displayReels(symbols);
Map<String, Integer> symbolCounts = new HashMap<>();
checkResults(symbols, symbolCounts);
displayResults(symbolCounts);
}
private static void checkResults(String[] symbols, Map<String, Integer> symbolCounts) {
// for each symbol
// if (symbolCounts.get(symbol) != null) {
// symbolCounts.put(symbol, 1);
// } else {
// int incrementedValue = symbolCounts.get(symbol) + 1;
// symbolCounts.put(symbol, incrementedValue);
// }
}
private static String[] pickRandomSymbolsForReels(String[] symbols) {
for (int reelIndex = 0; reelIndex < symbols.length; reelIndex++) {
int choice = random.nextInt(6);
switch (choice) {
case 0:
symbols[reelIndex] = CHERRY;
break;
case 1:
symbols[reelIndex] = ORANGE;
break;
case 2:
symbols[reelIndex] = LEMON;
break;
case 3:
symbols[reelIndex] = BELL;
break;
case 4:
symbols[reelIndex] = STAR;
break;
case 5:
symbols[reelIndex] = SKULL;
break;
}
}
return symbols;
}
private static void displayReels(String[] symbols) {
for (String symbol : symbols) {
System.out.print(symbol + " ");
}
System.out.println();
}
private static void displayResults(Map<String, Integer> symbolCounts) {
/**
* Here you'll need to understand the logic of various events.
* e.g
* 3 skulls - instantly lose all credit - game over
* 2 skulls - decreaseBalance(1.00)
* 3 Bells - increaseBalance(amount)
* 3 of any other symbol - increaseBalance(amount)
* 2 of any thing else - increaseBalance(amount)
* .. etc
*/
// if (hasThreeSkulls(symbolCounts.get(SKULL)) {
// gameOver();
// } else if (hasTwoSkulls(symbolCounts.get(SKULL)) {
// decreaseBalance(100) // note when working with money, store pence amount only and display the value as pounds and pence.. otherwise you'll have issues
// } etc ..
}
Next gather the stats from the reels (counts of the symbols of interest). Finally check the stats for winning/losing results. This will be a bunch of if, else-if statements.
Related
The directions for the assignment are: Program a game of War. In War, if the value of your card is greater than your opponent's card, you earn one point. If your opponent's card is greater than your card, your opponent gets a point. If you tie it is a war! That means the next hand is worth 2 points. If it is another tie, then the next hand is worth 4 points, and you keep adding 2 until the tie is broken. Then the scoring goes back to normal.
1) You should use your Cards class to get 2 playing cards.
2) Ask the user how many rounds they would like to play.
3) Have a loop to catch if they enter a negative number of rounds.
4) End the program if they want to play 0 rounds.
5) Print the user's car and the computer's card for each round.
6) Print out the correct score after each round.
7) Aces are LOW (Worth 1 point).
8) After all the rounds are complete, print a message that tells the user if they won, lost, or tied.
I have the driver class ready (see below). I need help creating a class that will do the stuff stated above. After each round it should ask the user to press enter to go on to the next round.
Here is my driver class code, it provides a card number and suit.
public class Cards
{
private int A;
private int B;
private String c;
private String b;
public Cards()
{
getSuit();
getCardName();
suit();
name();
}
public int getSuit()
{
A = (int) (Math.random()*4+1); //rolls a number between 1 and 4
return A;
}
public int getCardName()
{
B = (int) (Math.random()*13+1); //rolls a number between 1 and 13
return B;
}
public String suit()
{
if (A == 1) b = "Hearts";
else if (A == 2) b = "Diamonds";
else if (A == 3) b = "Clubs";
else b = "Spades";
return b;
}
public String name()
{
if (B == 1) c = "Ace";
else if (B == 2) c = "2";
else if (B == 3) c = "3";
else if (B == 4) c = "4";
else if (B == 5) c = "5";
else if (B == 6) c = "6";
else if (B == 7) c = "7";
else if (B == 8) c = "8";
else if (B == 9) c = "9";
else if (B == 10) c = "10";
else if (B == 11) c = "Jack";
else if (B == 12) c = "Queen";
else c = "King";
return c;
}
public String toString()
{
return c + " of " + b;
}
}
I would like to offer a review of your code, to hopefully help you improve it.
The variable names A/B/c/b do not offer any insight into what they represent. I am left guess what they are, as there are no comments either.
The getSuit() and getCardName() cause side effects. Calling getCardName() causes the card's number to change. This is not great in that most developers expect a getter method to not alter the object. For example, the following code would be rather confusing:
card.name(); // "Ace"
card.name(); // "Ace"
card.getCardName(); // 10. Should be 1???
card.name(); // "10". Huh?
It would probably be better to just set the card's suit and number in the constructor. At the very least, set the methods to private.
The suit() and name() methods return a string. There is no need to save the value into class fields b and c, except where you are using them in the toString() method, which can just be rewritten as:
return name() + " of " + suit();
This will reduce your duplication of data.
You might consider generating (and storing!) your cards in a loop, rather than randomly generated, as currently both players might be able to draw the exact same card. While this might not be against the requirements, I would not expect both players to draw the same card in a game of war.
getCardName() is poorly named. getCardValue() might be better, but as above, it should not alter the current value.
I have the class written, it should look something like this:
import java.util.Scanner;
public class WarGame extends Cards {
public static void main(String args[]) {
boolean playing = true;
int myScore = 0;
int oppsScore = 0;
int round = 0;
int increment = 1;
while (playing) {
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
if (input == 0 || input < 0)
{
System.out.println("INVALID ROUND NUMBER ENTERED!");
playing = false;
}
while (round <= input)
{
Cards myCard = new Cards();
Cards oppsCard = new Cards();
System.out.println("You have the " + myCard.toString());
System.out.println("The computer has the " + oppsCard.toString());
if (myCard.getSuit() > oppsCard.getSuit())
{
myScore += 1;
}
else if (oppsCard.getSuit() > myCard.getSuit())
{
oppsScore += 1;
}
else
{
increment *= 2;
System.out.println("WAR!!!!");
}
System.out.println("Your score: " + myScore);
System.out.println("Computer's score: " + oppsScore);
}
}
if (myScore > oppsScore) {
System.out.println("You win!");
} else if (myScore < oppsScore) {
System.out.println("You lose!");
} else {
System.out.println("It's a tie!");
}
}
}
I have a main menu class which gets a choice from the user and then uses that choice to select other classes from a switch statement pertaining to the menu options. My code is:
public static void main(String[] args) {
int dieOne = 0;
int dieTwo = 0;
int choice = 0;
DiceMaker dice = new DiceMaker(); // class that creates the dice
RollDice roll = new RollDice(); // class that imitates roll
DiceMenu menu = new DiceMenu();
DiceRoller series = new DiceRoller();
System.out.println("Welcome to the Dice Roll Stats Calculator!\n");
while (choice != 4) {
menu.DiceMenu();
choice = menu.getUserChoice();
switch (choice) {
case 1:
dice.diceMaker();
dieOne = dice.DieOne();
dieTwo = dice.DieTwo();
System.out.println(dice.DieOne() + dice.DieTwo());
return;
case 2:
roll.rollDice(dieOne, dieTwo);
roll.displayRoll();
return;
case 3:
series.diceRoller();
series.displayResults();
return;
case 4:
break;
}// switch (choice)
} // while (choice != 4)
}
Case for is the 'Exit' option, so I put the switch statement in a while loop with the boolean condition being not equal to 4 so that when the choice was set to 4 the loop would stop. The proper case executes but the problem I'm having is that the loop, and consequently the program stop after each case that I try, even if the choice was not 4. I tried using break statements after case 1, 2 and 3 as well, and when I did that, it would just repeat the case in an infinite loop. I tried to figure this out on my own cut could never find anything that resembled what I was seeing enough for me to figure out what the problem was. I'm guessing this probably isn't the best way to make a menu in the future. Thank in advance.
The rest of my code is as follows. Please note, DiceRoller class is still under construction, but DiceMaker and RollDice classes seem to be working.
DiceMenu class:
public class DiceMenu
{
public static final int CHOICE_UNKNOWN = 0;
public static final int CHOICE_MAKE_DICE = 1;
public static final int CHOICE_ROLL_ONCE = 2;
public static final int CHOICE_SERIES_ROLL = 3;
public static final int CHOICE_QUIT = 4;
private int choice = 0;
Scanner scan = new Scanner(System.in);
public int DiceMenu()
{
while ( this.choice < 1 || this.choice > 4 ) // while loop keeps choices in range
{
System.out.println(" MAIN MENU\n");
System.out.println("1. Create Your Dice");
System.out.println("2. Roll Your Dice");
System.out.println("3. Perform A Series Of Rolls And Show Stats");
System.out.println("4. Exit\n");
try // avoid invalid input
{
System.out.print("Please choose an option: ");
this.choice = scan.nextInt(); // get number of sides from user
}
catch (InputMismatchException e)
{
//if input is invalid, returns to beginning of loop
System.out.println("Invalid Input. Please try again.\n");
scan.next();
continue;
}
if ( this.choice < 1 || this.choice > 4 ) // if input is out of range
// notify user before continuing
{
System.out.println("Choice must reflect menu options. (1-4)"
+ " Please try again.\n");
this.choice = 0;
}
}//while ( this.choice < 1 || this.choice > 4 )
return 0;
}
public int getUserChoice()
{
return this.choice;
}
}
RollDice class:
public class RollDice
{
private int roll;
private int rollOne;
private int rollTwo;
private int rollTotal;
public int rollDice (int dieOne, int dieTwo)
{
this.rollOne = 1 + (int)(Math.random() * dieOne);
this.rollTwo = 1 + (int)(Math.random() * dieTwo);
this.rollTotal = this.rollOne + this.rollTwo;
return 0;
}
public void displayRoll()
{
System.out.println("You roll a " + rollOne + " and a "
+ rollTwo + " for a total of " +
rollTotal + "!"); //display separate and total
//roll amounts
if ( rollTotal == 2 ) // if/else tests for special rolls
{
System.out.println("Snake Eyes!");
}
else if ( rollTotal == 7 )
{
System.out.println("Craps!");
}
else if ( rollOne == 6 && rollTwo == 6 )
{
System.out.println("Boxcars!");
}
}
}// public class DiceRoller
DiceMaker class:
public class DiceMaker
{
private int sides = 0;
private int dieOne;
private int dieTwo;
public int diceMaker()
{
while ( sides < 4 || sides > 20 ) // while loop keeps sides within range
{
Scanner scan = new Scanner(System.in);
try // avoid invalid input
{
System.out.print("Please enter the number of sides each die "
+ "should have (must be between 4 and 20): ");
this.sides = scan.nextInt(); // get number of sides from user
}
catch (InputMismatchException e)
{
//if input is invalid, returns to beginning of loop
System.out.println("Invalid Input. Please try again.\n");
scan.next();
continue;
}
if (sides < 4 || sides > 20) // if input is out of range
// notify user before continuing
{
System.out.println("Die must have between 4 and 20 sides."
+ " Please try again.\n");
}
}//while ( sides < 4 || sides > 20 )
this.dieOne = sides;
this.dieTwo = sides;
return 0;
}
public int DieOne()
{
return this.dieOne;
}
public int DieTwo()
{
return this.dieTwo;
}
}// public class DiceMaker
Remove the return(s) from cases 1,2 and 3. If you return from main the program terminates. You want to loop so don't do that. However, as pointed out by #ajb in the comments below, you don't want the case(s) to fall through. So you need break(s).
case 1: dice.diceMaker();
dieOne = dice.DieOne();
dieTwo = dice.DieTwo();
System.out.println(dieOne + dieTwo);
// return;
break; // <-- applies to innermost block (switch).
case 2: roll.rollDice(dieOne, dieTwo);
roll.displayRoll();
// return;
break; // <-- applies to innermost block (switch).
case 3: series.diceRoller();
series.displayResults();
// return;
break; // <-- applies to innermost block (switch).
Also, you could use continue (here, which would apply to the innermost loop). Finally, remember that case 4 terminates the loop (because choice is 4) and you don't need case 4 for that reason.
I am attempting to write a program that helps a user make the correct EV play for each hand. However at the minute I am using card value (i.e. total of two cards) to base my decisions. For example 9=9, 10=10, j=11, q=12.... I would like the use to be able to enter in their actualy hands e.g. Adks (ace of diamonds, king of spades). This would be more accurate as it would take into account the suited value of the hand etc. Can anyone give me advice on the best way to incorporate this? Many thanks in advance! My cuurent code is below!
package uk.ac.qub.lectures;
//importing resources (scanner)
import java.util.Scanner;
public class PokeGame {
public static final int MIN_POSITION = 1;
public static final int MAX_POSITION = 8;
public static void main(String[] args) {
// declaring user position
int userPosition = 0;
// setting up scanner
Scanner scanner = new Scanner(System.in);
// integer referring to use again or not
int useAgain = 0;
// boolean getting valid input for repeat
boolean repeat = false;
// declaring number value of each card
int cards;
do {
// getting user position
do {
System.out.printf("Please enter position between %d and %d\n",MIN_POSITION, MAX_POSITION);
userPosition = scanner.nextInt();
} while ((userPosition < MIN_POSITION) || (userPosition > MAX_POSITION));
// getting hand hand strength
System.out.println("Enter card value");
cards = scanner.nextInt();
switch (userPosition) {
case 1:
case 2:
if (cards > 10) {
System.out.println("SHOVE");
} else
System.out.println("FOLD");
break;
case 3:
case 4:
case 5:
if (cards > 13) {
System.out.println("SHOVE");
} else
System.out.println("FOLD");
break;
case 6:
case 7:
case 8:
if (cards > 17) {
System.out.println("SHOVE");
} else
System.out.println("FOLD");
break;
default:
System.out.println("ENTER VALID POSITION");
}
do {
System.out.println("Do you advice on another Hand?");
System.out.println("Enter 1 for Yes, Enter 0 for No");
useAgain = scanner.nextInt();
if ((useAgain == 1) || (useAgain == 0)) {
repeat = false;
} else {
System.out.println("Invalid Input, please enter 1 or 0");
repeat = true;
}
} while (repeat);
} while (useAgain != 0);
// clean up resources
scanner.close();
}// method end
}// class end
If you take the card input like this; "AA", "9T" or "9Ts", you can then compute a hand value based on suitedness and gaps like such using you input cards:
import java.util.Arrays;
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
String[] hand = (scanner.nextLine() + 'u').toUpperCase().split("");
String values = " 23456789TJQKA";
int[] cards = new int[] {values.indexOf(hand[1]), values.indexOf(hand[2])};
Arrays.sort(cards);
int gap = cards[1] - cards[0] - 1;
boolean pair = gap == -1;
boolean suited = hand[3].equals("S");
char[] cards = new char[] {(char)values.charAt(cards[0]), (char)values.charAt(cards[1])};
int handValue = 0;
// adjust value based on pairs, suitedness or connectedness
if (pair) // hand is a pair
handValue += 10; //or whatever you want
else if (suited) // hand is suited
handValue += 3; //or whatever you want
if (gap == 0) // hand is no gap
handValue += 5; //or whatever you want.
if (gap == 1) // hand is one gap
handValue += 3; //or whatever you want.
if (cards[1] == 'A' && cards[0] == 'K' && suited) // AK suited
System.out.println("AK Suited!");
else if (cards[1] == 'A' && suited) // Ax suited
System.out.println("Ax Suited!");
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This is a tid bit of my total program, consisting of 4 classes. The classes goal is to print out a card with a numerical value and suit, the user than proceeds to guess wether the next card has a higher numerical value. If the cards are the same, the suit method determis the greatest suit in the order // SPADES >>>> HEARTS >>>> CLUBS >>>> DIAMONDS (As seen in the card method). The problem however, occurs in my HighLowrev class, in the do while loop as the user is asked to play again, if the user responds with 'y', the program continues and even if the user responds with 'n' the program continues. I have tried Looking up further usage of Boolean but have realized that I'm quite sure they work this way. Any help would be much appreciated.
CARD CLASS
public class Card {
// card class initalize varibles (NOtice the FINAL (THEY NEVER CHANGE VALUE!!!))
public final static int SPADES = 3; // Codes for the 4 suits, plus Joker.
public final static int HEARTS = 2;
public final static int DIAMONDS = 0;
public final static int CLUBS = 1;
public final static int JOKER = 4;
// SPADES >>>> HEARTS >>>> CLUBS >>>> DIAMONDS
public final static int ACE = 1; // Codes for the non-numeric cards.
public final static int JACK = 11; // Cards 2 through 10 have their
public final static int QUEEN = 12; // numerical values for their codes.
public final static int KING = 13;
private final int suit;
private final int value;
public static void main (String [] args){
} // joker constructor
public Card() {
suit = JOKER;
value = 1;
}
// incase an illegal field occurs
public Card(int theValue, int theSuit) {
if (theSuit != SPADES && theSuit != HEARTS && theSuit != DIAMONDS &&
theSuit != CLUBS && theSuit != JOKER)
throw new IllegalArgumentException("Illegal playing card suit");
if (theSuit != JOKER && (theValue < 1 || theValue > 13))
throw new IllegalArgumentException("Illegal playing card value");
value = theValue;
suit = theSuit;
}
public int getSuit() {
return suit;
}
// getter methods
public int getValue() {
return value;
}
// cases for suits...
public String getSuitAsString() {
switch ( suit ) {
case SPADES: return "Spades";
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case CLUBS: return "Clubs";
default: return "Joker";
}
}
// cases for numerical values...
public String getValueAsString() {
if (suit == JOKER)
return "" + value;
else {
switch ( value ) {
case 1: return "Ace";
case 2: return "2";
case 3: return "3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "10";
case 11: return "Jack";
case 12: return "Queen";
default: return "King";
}
}
}
public String toString() {
if (suit == JOKER) {
if (value == 1)
return "Joker"; // if the suit is the joker ....
else
return "Joker #" + value;
}
else { // return suit and number
return getValueAsString() + " of " + getSuitAsString() ;
}
}
}
MAIN PROGRAM CLASS
import java.io.*;
public class HighLowrev {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // allow input
System.out.println("This program lets you play the simple card game,");
System.out.println("HighLow. A card is dealt from a deck of cards.");
System.out.println("You have to predict whether the next card will be");
System.out.println("higher or lower. Your score in the game is the");
System.out.println("number of correct predictions you make before");
System.out.println("you guess wrong.");
System.out.println();
int gamesPlayed = 0; // Number of games user has played.
int sumOfScores = 0; // The sum of all the scores from
// all the games played.
double averageScore; // Average score, computed by dividing
// sumOfScores by gamesPlayed.
boolean playAgain = true;; // Record user's response when user is
// asked whether he wants to play
// another game.
do {
int scoreThisGame; // Score for one game.
scoreThisGame = play(); // Play the game and get the score.
sumOfScores += scoreThisGame;
gamesPlayed++;
System.out.print("Play again? ");
String input = br.readLine();
if(input== "Y" || input =="y") {
playAgain = true;
}
else {
playAgain =false;
}
} while (playAgain=true);
averageScore = ((double)sumOfScores) / gamesPlayed;
System.out.println();
System.out.println("You played " + gamesPlayed + " games.");
System.out.printf("Your average score was %1.3f.\n", averageScore);
} // end main()
private static int play() throws IOException {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // allow input
Deck deck = new Deck(); // Get a new deck of cards, and
Card currentCard; // The current card, which the user sees.
Card nextCard; // The next card in the deck. The user tries
int correctGuesses ; // The number of correct predictions the
char guess; // The user's guess. 'H' if the user predicts that
deck.shuffle(); // Shuffle the deck into a random order before
correctGuesses = 0;
currentCard = deck.dealCard();
System.out.println("The first card is the " + currentCard);
while (true) { // Loop ends when user's prediction is wrong.
/* Get the user's prediction, 'H' or 'L' (or 'h' or 'l'). */
System.out.println("Will the next card be higher (H) or lower (L)? ");
do { /// THE SECTION HERE IS THE SPECIFIED PROBLEM, THE IF AND ELSE STATEMENTS DONT DO ANYTHING!
guess = (char)br.read();
guess = Character.toUpperCase(guess);
if (guess != 'H' && guess != 'L')
System.out.println("Please respond with H or L: ");
} while (guess != 'H' && guess != 'L');
nextCard = deck.dealCard();
System.out.println("The next card is " + nextCard);
if(nextCard.getValue() == currentCard.getValue()) {
if(guess == 'H') {
if(nextCard.getSuit() > currentCard.getSuit()) {
System.out.println("Your prediction was correct.");
correctGuesses++;
}
}
else {
System.out.println("Your prediction was incorrect.");
break; // End the game.
}
if(guess == 'L') {
if(nextCard.getSuit() < currentCard.getSuit()) {
System.out.println("Your prediction was correct.");
correctGuesses++;
}
}
else {
System.out.println("Your prediction was incorrect.");
break;
}
}
else if (nextCard.getValue() > currentCard.getValue()) {
if (guess == 'H') {
System.out.println("Your prediction was correct.");
correctGuesses++;
}
else {
System.out.println("Your prediction was incorrect.");
break; // End the game.
}
}
else { // nextCard is lower
if (guess == 'L') {
System.out.println("Your prediction was correct.");
correctGuesses++;
}
else {
System.out.println("Your prediction was incorrect.");
break; // End the game.
}
}
currentCard = nextCard;
System.out.println();
System.out.println("The card is " + currentCard);
} // end of while loop
System.out.println();
System.out.println("The game is over.");
System.out.println("You made " + correctGuesses
+ " correct predictions.");
System.out.println();
return correctGuesses;
}
}
String comparison in Java is not done with == but with String#equals
That is, instead of
if(input== "Y" || input =="y") {
You should be using something more like...
if("Y".equalsIgnoreCase(input)) {
Updated...
There is also a never ending assignment of true to playAgain
} while (playAgain=true);
This will assign true back to playAgain, which means the loop can never be exited. Try using something like...
} while (playAgain);
...instead
The variable you are comparing input is a String.
Strings cannot be equated using == you must use String#equals()
The == operator checks whether the references to the objects are equal. See this post
In this case you may want to use String#equalsIgnoreCase()
Also as mentioned you need to fix while (playAgain=true); This is assigning true the variable playAgain and will always be true, Here you want to use == or just the varaible itself (no need to compare booleans)
while (playAgain=true);
should it be while (playAgain == true); ?
The comparison operator is not correct.
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;