Can anyone please help. I am comparing 2 sets of lottery numbers the userNumbers being the numbers from your ticket and the numbers array representing numbers from the lottery draw on the website. When I run the program and type in the 6 correct numbers the program informs me I have won the jackpot. However if I have any less than 6 numbers matching I am stuck in a while loop. can anyone help me to get out of this so that if I match 2 numbers the program will inform me ive matched 2 nos, if I match 3 it will inform me of this and so on! and if I match the bonus the program will inform me I have matched the bonus and (n) amount of numbers.
I am quite new to Java and have been mulling over this for some time! Thanks in advance!
final int SIZE = 6;
//array to store user numbers
int [] userNumbers = new int[SIZE];
boolean found = false;
int pos = 0;
boolean bonus = false;
int lottCount = 0;
boolean jackpot;
while (pos<SIZE)
{
System.out.println("enter your numbers");
userNumbers[pos]=keyboard.nextInt();
pos++;
}
for (int count: userNumbers)
{
System.out.println(count);
}
for (int loop = 0; loop <SIZE; loop++ )
{
for (int loopOther = 0; loopOther < numbers.length; loopOther++)
{
if (userNumbers[loop] == numbers[loopOther])
{
lottCount++;
} else if (userNumbers[loop] == bonusBall)
{
bonus = true;
}
}//for
}//forMain
if (lottCount == 6)
{
jackpot = true;
System.out.println("You have matched all numbers!! Congratulations you are a jackpot winner");
}else System.out.println(" You have matched " + lottCount + " numbers. Please visit the webpage did you see what you have won");
while (lottCount < 6)
if (bonus)
{
System.out.println("You have matched " + lottCount + " numbers " + "and" + " the bonus ball"
+ bonusBall + " Please see the website to check your prize.");
} else
System.out.println("You have not won at this time. ");
looks like "while (lottCount < 6)" is unnecessary, take that out and it should work, looks like you want something along the lines of:
if (lottCount == 6) {
System.out.println("You have matched all numbers!! Congratulations you are a jackpot winner");
}
else if (!bonus) {
System.out.println(" You have matched " + lottCount + " numbers. Please visit the webpage did you see what you have won");
}
if (bonus) {
System.out.println("You have matched " + lottCount + " numbers " + "and" + " the bonus ball"
+ bonusBall + " Please see the website to check your prize.");
}
Related
My program asks the user for their name, then asks for a number of shuffles of 3 random numbers.
When one of the shuffles adds to the desired number (which is 31) the shuffle stops. I need to happen that the program only reads the LAST SHUFFLE. E.g.
how many shuffles do you want: 3
10 + 11 + 10 = 31 congrats you are the winner!!
The current output is:
9 + 6 + 8
8 + 10 + 12
7 + 9 + 11
I need assistance in making sure the user cannot put non alphabetical characters in their name. I also need the ability to be able to print out how many shuffles the user had before the numbers were printed out.
Here is my code,
`import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.IOException;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
//enter their first name
String first_name;
System.out.print("Enter Your First Name: ");
first_name = user_input.next();
//enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = user_input.next();
//full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
//this is the buffer that resets if the user types a letter instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out
.println(" You will be given a hand of 3 random numbers between 7-13"
+ "\n you will be drawn a the number of shuffles as you entered above ");
delay(2000);
System.out
.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = "
+ (num1 + num2 + num3));
// adding the numbers together
if (num1 + num2 + num3 == 31) {
isWinner = true;
System.out
.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
}
if (!isWinner)
System.out.println("Better Luck Next Time");
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// if pressed y or yes the program will run again with the same number of shuffles entered from before
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}`
Arraylist numberStore = new Arraylist();
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
}
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
isWinner = true;
System.out
.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
to make sure that only the last shuffle can get read as a winner or loser.
Because you are initializing your num1, num 2... variables inside of your for loop then those variables are scoped to that for loop. I would suggest that if you want to make sure that only one set of numbers can be judged then you move the scope out of the loop. Adding the totals to an array would then allow you to choose as many as you want to judge.
When it comes to sterilizing your inputs you can use util.Scanner to do most of it for you with a little knowledge of regex:
while (!scan.hasNext("[A-Za-z]+")) {
System.out.println("Nope, that's not it!");
sc.next();
}
This will stop your scanner allowing any none alphabetical char's being entered, you can read more about Regex with this tool
I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();
I am at a loss of how I would only allow a user to enter three unique numbers. I have tried to create another array that adds the input and checks with the damage array to make sure all numbers are unique, but it does not seem to work. Thank you for any help!!
ArrayList<Integer> damage = new ArrayList<Integer>();
ArrayList<Integer> unique = new ArrayList<Integer>();
for (int k = 0; k<=10; k++)
{
unique.add(k);
}
do
{
System.out.print("Attack or Defend? (A or D) ");
option = keyboard.nextLine().toUpperCase();
System.out.println();
switch (option)
{
case "A":
System.out.println("Enter three unique random numbers (1-10)");
for(int i = 0; i<3; i++)
{
System.out.print("number " + (i+1) + ": ");
input = keyboard.nextInt();
if (input < 1 || input > 10)
{
System.out.println("Error! Enter a valid number (1-10)");
}
else
{
if (unique.contains(input))
{
unique.remove(input);
System.out.println(unique);
damage.add(input);
System.out.println(damage);
i--;
}
else
{
unique.add(0, input);
System.out.println("Number is not unique!");
}
}
}
System.out.println(damage);
System.out.println();
UserDamage ahit = new UserDamage(damage, option);
name.getName();
ahit.setUserDamage(damage, option);
System.out.println("\n");
cpuHealth-=ahit.getUserDamage();
cpu.setCpuDamage();
userHealth-=cpu.getCpuDamage();
System.out.println("\n\nHealth left: " + userHealth);
System.out.println("Computer health left: " + cpuHealth + "\n");
damage.clear();
option = null;
break;
default:
System.out.println("Invalid selection.");
break;
}
}
while(userHealth>0 || cpuHealth >0);
Use the contains method from java.util.List to determine if the item is already present. From the Javadoc:
boolean contains(Object o)
Returns true if this list contains the
specified element. More formally, returns true if and only if this
list contains at least one element e such that (o==null ? e==null :
o.equals(e)).
You are close. Just need some more logic work in here and using what Mike Kobit suggested.
ArrayList<Integer> damage = new ArrayList<Integer>();
System.out.println("Enter three unique random numbers (1-10)");
for(int i = 0; i<3; i++)
{
System.out.print("number " + (i+1) + ": ");
input = keyboard.nextInt();
if(damage.contains(input) == false && input > 0 && input <= 10)
damage.add(input);
else{
System.out.println("Error! Enter an unique valid number (1-10)");
i--;
}
}
The i-- is for the loop so if you entered in bad value 3 times, no values would go into the array.
The contains() method should be useful for you. So entering one number can look like this:
while(input > 10 || input < 0 || damage.contains(input)) {
System.out.print("number " + (i+1) + ": ");
input = keyboard.nextInt();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I made a little program in Java where the user is being asked to pick three cards, ranging from 4 to 6. It's a bit of a sloppy code, but it works. Three random numbers (4 to 6) are generated. If the user guesses these numbers in the right order, he wins. Now, there should be an option for the user to change one of his guesses if he did not get all cards right the first time. This should be done by the user by inserting 1, 2 or 3 to retry. There should be no new random number generated. I did not learn this yet at school and did try some searching on the internet. Anyone who can give me some insight in doing this?
package cardgame;
import java.util.Scanner;
public class CardGame {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[] guess = new int[3];
int[] card = new int[3];
System.out.println("Pick three cards with numbers ranging from 4 to 6!\n");
for (int i=0; i<3; i++){
System.out.print("Card number " + (i+1) + " (4, 5 or 6): ");
guess[i] = scan.nextInt();
}
System.out.println(" ");
System.out.println("Your hand of cards: " + "[" + guess[0] + "]" + "[" + guess[1] + "]" + "[" + guess[2] + "]");
for (int i=0; i<3; i++){
card[i] = (int) (Math.random() * 3 + 2 +2);
}
System.out.println("My hand of cards: " + "[" + card[0] + "]" + "[" + card[1] + "]" + "[" + card[2] + "]\n");
int count = 0;
for (int i=0; i<3; i++){
if (card[i] == guess[i])
count++;
}
if (count == 3){
System.out.println("Congratulations, you have won!");
} else{
System.out.println("I'm sorry, you lost!");
}
}
}
How about something like this:
System.out.println("Would you like to change one of your guesses? yes/no");
if(scan.next() == "yes")
{
System.out.println("What guess would you like to change? 1/2/3");
if(scan.nextInt() == 1 || scan.nextInt() == 2 || scan.nextInt() == 3)
{
int temp = scan.nextInt();
System.out.println("What is your new guess?");
guess[temp-1] == scan.nextInt(); // -1 because array index starts at 0
}
else
System.out.println("That's not a valid guess number");
}
This is a very basic example. You could make it as complex as you want. For example, by adding a loop prompting the user to ask again if their guess was invalid.
I am at the end of my program here and Im trying to create a random number thats in an arraylist. I have the syntax below that Im using. I don't know how to write this, but I hope the code shows what I'm trying to accomplish.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class TriviaQuestionTester {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File gameFile = new File("trivia.txt");
String nextLine, category;
int cat1 = 0;
int cat2 = 0;
int cat3 = 0;
int cat4 = 0;
int cat5 = 0;
int cat6 = 0;
int random1, random2, random3, random4, random5, random6;
int totalScore = 0;
int awardedPoints = 200;
String answer;
Random random = new Random();
Scanner inFile = new Scanner(gameFile);
Scanner scanner = new Scanner(System.in);
ArrayList <String> myList = new ArrayList<String>();
//append # sign to first index of arraylist when we copy the text file into it. first line will
//be the first category.
category = "#"+ inFile.nextLine();
//add category to arraylist
myList.add(category);
//while textfile has another line of input, write that line into the arraylist.
while (inFile.hasNextLine()){
nextLine = inFile.nextLine();
//check if the next line is blank. if it is, advance to the next line (as it must be a category) and append # sign
//before copying it into the arraylist. if it is not, write the line into the arraylist.
if(nextLine.equals("")){
category = "#"+ inFile.nextLine();
myList.add(category);
} else {
myList.add(nextLine);
}
}
//close the text file from reading
inFile.close();
System.out.println("Steve's Crazy Trivia Game!!!!" );
System.out.println("");
//find categories by searching the contents of every arraylist index and looking for the # sign.
//when you find that, assign that into the respective variable.
int q = 1;
for(int j = 0; j < myList.size(); j++){
if(myList.get(j).contains("#")){
//System.out.println("Category found at " + j);
if(q == 1){
cat1 = j;
}
if(q == 2){
cat2 = j;
}
if(q == 3){
cat3 = j;
}
if(q == 4){
cat4 = j;
}
if(q == 5){
cat5 = j;
}
if(q == 6){
cat6 = j;
}
q++;
}
}
//first question
//get category from variable, print it to user without the # sign
System.out.println("Category: " + myList.get(cat1).substring(1));
//generate a random number in a range 1 more than the index where the category is and 2 less than
//where the next category is to get a question (always will be odd numbers)
//Credit: Derek Teay
random1 = random.nextInt(((cat2 - 2) - (cat1 + 1))) + (cat1 + 1);
//debug code - shows the number generated
//System.out.println("Random number: " + random1);
//take the modulus of the random number. if there is a remainder, the number is odd, continue.
//if there is not a remainder, number is even, generate a new number until the randomly generated
//number is odd.
while (random1 % 2 == 0){
random1 = random.nextInt(((cat2 - 2) - (cat1 + 1))) + (cat1 + 1);
//debug code - shows the new random number if the first number isn't odd
//System.out.println("New random number: " + random1);
}
//display the question to the user
System.out.println("Question: " + myList.get(random1));
//accept user input
System.out.print("Please type your answer: ");
//store the user answer in a variable but lowercase
answer = scanner.nextLine().toLowerCase();
System.out.println();
//display the officially correct answer from the arraylist
//System.out.println("Answer: " + myList.get(random1 +1));
//if the user answer matches the official answer, tell them they're correct and award points - else
//tell them they are incorrect
// Display the officially correct answer from the arraylist
String correctAnswer = myList.get(random1 +1);
System.out.println("Answer: " + correctAnswer); // Instead use a variable
// if the user answer matches the official answer, tell them they're
// correct and award points
// else tell them they suck LOL
if(correctAnswer.equalsIgnoreCase(answer.trim())) {
System.out.println("Correct!");
totalScore = totalScore + awardedPoints;
System.out.println("You won " + awardedPoints);
}
else {
System.out.println("You are incorrect");
}
//display total accumulated points
System.out.println("Your total points are: " + totalScore);
//wait for user to hit any key before displaying the next question
System.out.print("Hit Enter");
System.out.println("");
scanner.nextLine();
//second question
//get category from variable, print it to user without the # sign
System.out.println("Category: " + myList.get(cat2).substring(1));
//generate a random number in a range 1 more than the index where the category is and 2 less than
//where the next category is to get a question (always will be odd numbers)
//Credit: Derek Teay
random2 = random.nextInt(((cat3 - 2) - (cat2 + 1))) + (cat2 + 1);
//take the modulus of the random number. if there is a remainder, the number is odd, continue.
//if there is not a remainder, number is even, generate a new number until the randomly generated
//number is odd.
while (random2 % 2 == 0){
random2 = random.nextInt(((cat3 - 2) - (cat2 + 1))) + (cat2 + 1);
}
//display the question to the user
System.out.println("Question: " + myList.get(random2 + 1));
//accept user input
System.out.print("Please type your answer: ");
//store the user answer in a variable but lowercase
answer = scanner.nextLine().toLowerCase();
System.out.println();
//if the user answer matches the official answer, tell them they're correct and award points - else
//tell them they are incorrect
// Display the officially correct answer from the arraylist
String correctAnswer1 = myList.get(random2 +1);
System.out.println("Answer: " + correctAnswer1); // Instead use a variable
// if the user answer matches the official answer, tell them they're
// correct and award points
// else tell them they suck LOL
if(correctAnswer1.equalsIgnoreCase(answer.trim())) {
System.out.println("Correct!");
totalScore = totalScore + awardedPoints;
System.out.println("You won " + awardedPoints);
}
else {
System.out.println("You are wrong again");
}
//display total accumulated points
System.out.println("Your total points are: " + totalScore);
//wait for user to hit any key before displaying the next question
System.out.print("Hit Enter");
System.out.println("");
scanner.nextLine();
//third question
//get category from variable, print it to user without the # sign
System.out.println("Category: " + myList.get(cat3).substring(1));
//generate a random number in a range 1 more than the index where the category is and 2 less than
//where the next category is to get a question (always will be odd numbers)
//Credit: Derek Teay
random3 = random.nextInt(((cat4 - 2) - (cat3 + 1))) + (cat3 + 1);
//take the modulus of the random number. if there is a remainder, the number is odd, continue.
//if there is not a remainder, number is even, generate a new number until the randomly generated
//number is odd.
while (random3 % 2 == 0){
random3 = random.nextInt(((cat4 - 2) - (cat3 + 1))) + (cat3 + 1);
}
//display the question to the user
System.out.println("Question: " + myList.get(random3 + 1));
//accept user input
System.out.print("Please type your answer: ");
//store the user answer in a variable but lowercase
answer = scanner.nextLine().toLowerCase();
System.out.println();
//if the user answer matches the official answer, tell them they're correct and award points - else
//tell them they are incorrect
// Display the officially correct answer from the arraylist
String correctAnswer2 = myList.get(random3 +1);
System.out.println("Answer: " + correctAnswer1); // Instead use a variable
// if the user answer matches the official answer, tell them they're
// correct and award points
// else tell them they suck LOL
if(correctAnswer2.equalsIgnoreCase(answer.trim())) {
System.out.println("Correct!");
totalScore = totalScore + awardedPoints;
System.out.println("You won " + awardedPoints);
}
else {
System.out.println("Wow, you really stink");
}
//display total accumulated points
System.out.println("Your total points are: " + totalScore);
//wait for user to hit any key before displaying the next question
System.out.print("Hit Enter");
System.out.println("");
scanner.nextLine();
//fourth question
//get category from variable, print it to user without the # sign
System.out.println("Category: " + myList.get(cat4).substring(1));
//generate a random number in a range 1 more than the index where the category is and 2 less than
//where the next category is to get a question (always will be odd numbers)
//Credit: Derek Teay
random4 = random.nextInt(((cat5 - 2) - (cat4 + 1))) + (cat4 + 1);
//take the modulus of the random number. if there is a remainder, the number is odd, continue.
//if there is not a remainder, number is even, generate a new number until the randomly generated
//number is odd.
while (random4 % 2 == 0){
random4 = random.nextInt(((cat5 - 2) - (cat4 + 1))) + (cat4 + 1);
}
//display the question to the user
System.out.println("Question: " + myList.get(random4 + 1));
//accept user input
System.out.print("Please type your answer: ");
//store the user answer in a variable but lowercase
answer = scanner.nextLine().toLowerCase();
System.out.println();
//if the user answer matches the official answer, tell them they're correct and award points - else
//tell them they are incorrect
// Display the officially correct answer from the arraylist
String correctAnswer3 = myList.get(random4 +1);
System.out.println("Answer: " + correctAnswer3); // Instead use a variable
// if the user answer matches the official answer, tell them they're
// correct and award points
// else tell them they suck LOL
if(correctAnswer3.equalsIgnoreCase(answer.trim())) {
System.out.println("Correct!");
totalScore = totalScore + awardedPoints;
System.out.println("You won " + awardedPoints);
}
else {
System.out.println("You are incorrect");
}
//display total accumulated points
System.out.println("Your total points are: " + totalScore);
//wait for user to hit any key before displaying the next question
System.out.print("Hit Enter");
System.out.println("");
scanner.nextLine();
//fifth question
//get category from variable, print it to user without the # sign
//generate a random number in a range 1 more than the index where the category is and 2 less than
//where the next category is to get a question (always will be odd numbers)
//Credit: Derek Teay
random5 = random.nextInt(((cat6 - 2) - ( cat5 + 1))) + (cat5 + 1);
//take the modulus of the random number. if there is a remainder, the number is odd, continue.
//if there is not a remainder, number is even, generate a new number until the randomly generated
//number is odd.
while (random5 % 2 == 0){
random5 = random.nextInt(((cat6 - 2) - (cat5 + 1))) + (cat5 + 1);
}
//display the question to the user
System.out.println("Question: " + myList.get(random5 + 1));
//accept user input
System.out.print("Please type your answer: ");
//store the user answer in a variable but lowercase
answer = scanner.nextLine().toLowerCase();
System.out.println();
//if the user answer matches the official answer, tell them they're correct and award points - else
//tell them they are incorrect
// Display the officially correct answer from the arraylist
String correctAnswer4 = myList.get(random5 +1);
System.out.println("Answer: " + correctAnswer4); // Instead use a variable
// if the user answer matches the official answer, tell them they're
// correct and award points
// else tell them they suck LOL
if(correctAnswer4.equalsIgnoreCase(answer.trim())) {
System.out.println("Correct!");
totalScore = totalScore + awardedPoints;
System.out.println("You won " + awardedPoints);
}
else {
System.out.println("You are incorrect");
}
//display total accumulated points
System.out.println("Your total points are: " + totalScore);
//wait for user to hit any key before displaying the next question
System.out.print("Hit Enter");
System.out.println("");
scanner.nextLine();
//sixth question
//get category from variable, print it to user without the # sign
System.out.println("Category: " + myList.get(cat6).substring(1));
//generate a random number in a range 1 more than the index where the category is and 2 less than
//where the next category is to get a question (always will be odd numbers)
//Credit: Derek Teay
random6 = random.nextInt((cat6.maximum - cat6.minimum) + (cat6.minimum));
//take the modulus of the random number. if there is a remainder, the number is odd, continue.
//if there is not a remainder, number is even, generate a new number until the randomly generated
//number is odd.
while (random6 % 2 == 0){
random6 = random.nextInt(((cat3 - 2) - (cat2 + 1))) + (cat2 + 1);
}
//display the question to the user
System.out.println("Question: " + myList.get(random6 + 1));
//accept user input
System.out.print("Please type your answer: ");
//store the user answer in a variable but lowercase
answer = scanner.nextLine().toLowerCase();
System.out.println();
//if the user answer matches the official answer, tell them they're correct and award points - else
//tell them they are incorrect
// Display the officially correct answer from the arraylist
String correctAnswer5 = myList.get(random6 +1);
System.out.println("Answer: " + correctAnswer5); // Instead use a variable
// if the user answer matches the official answer, tell them they're
// correct and award points
// else tell them they suck LOL
if(correctAnswer1.equalsIgnoreCase(answer.trim())) {
System.out.println("Correct!");
totalScore = totalScore + awardedPoints;
System.out.println("You won " + awardedPoints);
}
else {
System.out.println("Did you even go to school?");
}
//display total accumulated points
System.out.println("Your total points are: " + totalScore);
//wait for user to hit any key before displaying the next question
System.out.print("Hit Enter");
System.out.println("");
scanner.nextLine();
}
// TODO Auto-generated method stub
}
Well first off your line:
random6 = random.nextInt((cat6.maximum - cat6.minimum) + (cat6.minimum));
should be:
random6 = random.nextInt(cat6.maximum - cat6.minimum) + cat6.minimum;
You're using an awful lot of parentheses so it gets hard to see, but the minimum value should go outside the call to nextInt() because nextInt() returns a value of the range [0, max - min) but you want one in the range [min, max).
Next, you can do this:
while ((random6 = random.nextInt(cat6.maximum - cat6.minimum) + cat6.minimum) % 2 == 0) {
continue;
}
EDIT: Well, after looking at your full code a bit more...
Learn to use and love functions. Here, what you're doing (getting an index of a random question based on a category index) is complex and discrete enough to be its own function:
//generate a random number in a range 1 more than the index where the category is and 2 less than
//where the next category is to get a question (always will be odd numbers)
public static int getRandomQuestionIndex(int category) {
int min = category - 2;
int max = category + 2; // Because nextInt() is exclusive on upper bound
int random6;
while ((random6 = random.nextInt(max - min) + min) % 2 == 0) {
continue;
}
return random6;
}
I don't really understand what your goal is, but I think there's a bug on this line:
random6 = random.nextInt((cat6.maximum - cat6.minimum) + (cat6.minimum));
Your parentheses aren't quite right. It should be:
random6 = random.nextInt((cat6.maximum - cat6.minimum)) + (cat6.minimum);