Basic Java program tune up assistance - java

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

Related

Given an array, find all combinations (2 integers) using addition and subtraction that equal a target value

I am trying to make a program that solves for all the 2 number combinations of addition and subtraction that equal a target value.
For example, given the array [12,1,9,11,32,19] and the target value twenty, the answers 1+19, 9+11, and 32-12 must be returned. If there are no possible combinations, the System should print that there are no possible combinations. Also, every combination must be two numbers ONLY. Is it possible to do this only in the main class?
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What length (in a whole number) would you like the array to be? ");
int arraySize = sc.nextInt();
int [] arr = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
int remainingNumbers = arraySize - i;
System.out.println("Please enter " + remainingNumbers + " more integers.");
arr[i] = sc.nextInt();
}
System.out.print("Please enter a target value: ");
int target = sc.nextInt();
System.out.println(Arrays.toString(arr));
// Algorithm here.
}
}
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
System.out.println(num1 + " + " + num2 + " = " +
(num1 + num2));
System.out.println(num1 + " - " + num2 + " = " +
(num1 - num2));
System.out.println(num1 + " x " + num2 + " = " +
(num1 * num2));
System.out.println(num1 + " / " + num2 + " = " +
(num1 / num2));
System.out.println(num1 + " mod " + num2 + " = " +
(num1 % num2));
}
}
enter code here
''' Input first number: 32 Input second number: 12 19 + 1 = 20 32 - 12 = 20 9+11= 20'
Yes, it is possible to do it only in the main class. It is even possible to do it only in the main method (despite doing it an own method is better, easier to understand). Just two nested for loops; one for the first value, one for the second value. Inside the inner loop just test if the sum of both values result in the expected result, same for subtraction. Set a boolean to indicate that at least one case was found. At the end print the negative message if the boolean is not set.
Sample:
private static boolean findCombinations(int target, int[] values) { // or ,int... values) {
boolean found = false;
for (int i = 0; i < values.length; i++) {
// second loop
// tests and print
}
return found;
}

Java do loop repeat until valid entry

I'm creating a Java project using a do-while loop to get a number from the user between 5 and 15. After this, I will create a square and triangle using the number the user entered.
I'm currently stuck on making my question repeat. After I run the program it runs fine until I input a number the second time the user is prompted to enter a number. It won't print if the number is invalid or not.
I tried moving the second "Enter a number..." inside of the do-loop but that just printed with the "Sorry, invalid" prompt. I did something similar with a case statement inside a while loop and it ran fine but I'm having difficulty with the do loop.
Can someone point me in the right direction?
import java.util.Scanner;
public class doLoop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
int minimum = 5;
int maximum = 15;
System.out.print("Enter a number between " + minimum + " and " + maximum + ":" );
do {
number = input.nextInt();
if (number >= minimum && number <= 15)
break;
else
System.out.print("Sorry, invalid");
break;
} while (false);
System.out.print("\nEnter a number between " + minimum + " and " + maximum + ":" );
number = input.nextInt();
}
}
In general, use break inside a while loop is considered a bad practice. You should have something like this
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int minimum = 5;
int maximum = 15;
do{
System.out.print("Enter a number between" + " " + minimum + " " + "and" + " " + maximum + ":" );
number = input.nextInt();
if (number < minimum || number > maximum)
System.out.print("Sorry, invalid");
} while (number < minimum || number > maximum);
}
There is a logical error in your code in the placement of your break and scanner input. If you really want to stay true to what you have, I find it much simpler to just add a boolean check instead of using a break. Below you can see I also put final so that way you know, and is a best practice that, that variable should not be altered or tampered with in code. I added a boolean since you wanted to check the do while for false, then we set it to true if it passes the if statement you made.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
boolean check = false;
// Final, because they are constant through-out the program
final int minimum = 5;
final int maximum = 15;
do {
System.out.print("Enter a number between " + minimum + " and " + maximum + ":" );
number = input.nextInt();
if (number >= minimum && number <= maximum)
check = true;
else
System.out.println("Sorry, invalid");
break;
} while (check);
}

ArrayList If Loop not working properly: JAVA

I have a program that asks the user their name etc. Then it asks how many times do you want the numbers to loop (so my program generates 3 random numbers between 7 and 13 and if it adds up to 31 they are the winner) and my issue is that I only want the last printed number to count towards if the player wins or looses, the other numbers are just for show or tease i guess. the problem is that regardless towards if the player wins or looses, the losing statement always prints out. Below is my entire 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: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
//enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
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 " + numShuffles + " hand(s) of 3 random numbers between 7-13" );
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("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
Arraylist numberStore = new Arraylist();
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));
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
}
}
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
}
}
}
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
you probably want something like
int lastNumber = numberStore.get(numberStore.size() - 1);
if (lastNumber == 31) {
to verify that is the error try to change that line to
int lastNumber = num1 + num2 + num3;
Edit based on further messages:
Looks like what you really want is this:
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 = num1 + num2 + num3;
boolean lastShuffle = (i == (numShuffles - 1));
if (lastShuffle) {
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
} else {
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;
}
Just a general suggestion: avoid to use break if possible, it makes control flow hard to follow and is not a good programming practice.
Several points to make here. One, your code is quite messy and hard to read. It's helpful when you're asking for help (and in general anyway) to properly indent your code. This is good practice and if you do other languages like Python can help you out a lot. Also, why do a check for !isWinner? Scrap the isWinner variable altogether and just check for the number equalling 31 and then have an else statement for the losing statement. Like this:
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
else {
System.out.println("Better Luck Next Time");
}
Also, take some steps to find the error. Print out each number as you get it, and use
int lastNumber = num1 + num2 + num3;
instead of
int lastNumber = (numberStore.size() - 1);
Also for anybody else compiling this, it's ArrayList and not Arraylist... just a little slip.
Sorry, I may have to say that your codes are a kind of mess up. a small factory with the solution you ask, hope it can be a little help to you
public static void main(String[] args) throws NumberFormatException,
IOException {
Scanner user_input = new Scanner(System.in);
String full_name = registeGamePlayer(user_input);
int numShuffles = initGame(user_input);
showTheGameInfo(full_name, numShuffles);
runningGame(user_input, numShuffles);
user_input.close();
}
/**
* #param user_input
* #param numShuffles
*/
private static void runningGame(Scanner user_input, int numShuffles) {
// 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);
int amount = num1 + num2 + num3;
System.out.printf("%d + %d + %d = %d \n", num1,num2,num3,amount);
if (amount == 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;
}
}
}
/**
* #param full_name
* #param numShuffles
*/
private static void showTheGameInfo(String full_name, int numShuffles) {
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
private static String registeGamePlayer(Scanner user_input){
String first_name;
System.out.print("Enter Your First Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
// enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
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");
return full_name;
}
private static int initGame(Scanner user_input){
// 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 " + numShuffles + " hand(s) of 3 random numbers between 7-13");
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);
return numShuffles;
}

How to randomly position a variable within X + Y = Z operation and loop

I basically want to be able to loop an X + Y = Z equation until the user inputs something other than an integer, like the letter "A" and also when having any number make the loop stop displaying a message.
Also, I am confused on how to randomly position the "?" which the user must input the correct answer.
For example
System.out.println("What is: " + num1 + " + ? = " + answer);
So far:
I am positioning the "?" manually through the IF statements. Can this be done in a more efficient way?
public static void main(String[] args) {
Random rand = new Random();
Scanner input = new Scanner(System.in);
int num1, num2, number3, answer;
do {
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println("What is: " + num1 + " + ? = " + answer);
number3= input.nextInt();
if (number3 == num2)
System.out.println("That is correct");
else
System.out.println("That is wrong");
num1= 1 + rand.nextInt(10);
num2= 1 + rand.nextInt(10);
answer= num1 + num2;
System.out.println(num1 + " + ? = " + answer);
number3= input.nextInt();
} while(number3 !=0);
}
Here is one way to do it:
public static void main(String[] args) {
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
int[] xyz = new int[3];
String[] display = new String[3];
int answer, position;
do {
xyz[0] = 1 + rand.nextInt(10);
xyz[1] = 1 + rand.nextInt(10);
xyz[2] = xyz[0] + xyz[1];
for (int i = 0; i < xyz.length; i++)
display[i] = String.valueOf(xyz[i]);
position = rand.nextInt(3);
display[position] = "?";
System.out.println("What is: " + display[0] + " + " + display[1] + " = " + display[2]);
do {
System.out.println("Please enter an integer or 'S' to stop");
String input = scanner.nextLine();
if (input.equals("S")) {
scanner.close();
System.out.println("Stopped");
return;
}
else if (input.matches("\\d+")) { // \\d+ means "a digit (0-9) once or more
answer = Integer.parseInt(input);
break;
}
} while (true);
if (answer == xyz[position])
System.out.println("That is correct");
else
System.out.println("That is wrong");
} while (true);
}
Notes:
I use an inner do-while loop to repeatedly check the input and ask the user for a valid input.
I use 2 arrays: one for storing the numbers and another for storing the display values.
I also added a stop condition since the outer loop is infinite. Always close the Scanner when you finish.
I randomly pick 1 of 3 positions for the "?".

Create a random within a range from an ArrayList within an Arraylist

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);

Categories