Java. making a question re-ask if you get it wrong - java

I am new to java so I'm terrible at it. Basically I am making a multi choice quiz thing.
But my problem is that even if you get the question wrong it goes to the next question
and I want it to ask the same question again, like a loop. I have tried to make it work but I can't, it's probably very simple and easy.
If anyone can help that would be cool !
it says
whats 9+10?
1. 19
2. 21
3. 18
current code:
iAnswer = Integer.parseInt(System.console().readLine());
if (iAnswer == 1) {
System.out.println(" ");
System.out.println("Correct");
}
else {
iLives -= 1;
System.out.println(" ");
System.out.println("Incorrect");
}
(when you get a question wrong you lose a life, but i don't think that matters)

I'm not sure if this is what you asked for but I came up with this !
//get input from console
Scanner scanner = new Scanner(System.in);
//create a loop to keep
while (true) {
//get 2 random number on value(0 - 20)
int n1 = (int) (Math.random() * 20 + 1);
int n2 = (int) (Math.random() * 20 + 1);
//correct Answer is saved in correctAns value
int correctAns = n1 + n2;
System.out.println("What is the anwser of : ");
System.out.print(n1 + " + " + n2 + " = ");
//get the answer from user input
int ans = scanner.nextInt();
//if user input is equal to current Answer
if (ans == correctAns) {
System.out.println("Congrats next question !");
} else {
//if user input is not equal to currentAns
boolean condition = true;
//create another loop where user has to answer right to get to
//the next question
while (condition) {
System.out.println("What is the anwser of : ");
System.out.print(n1 + " + " + n2 + " = ");
ans = scanner.nextInt();
//if user input is equal to currentAns
if (ans == correctAns) {
//stop the loop and continue to the other question
condition = false;
} else {
// if user input is not equal to currentAns keep asking
// the same question
condition = true;
}
}
}
}

Related

how to extract answers from for loop

I can't figure out how to correctly write my for loop statement that will give me the correct score. I bolded the code that is what I can't figure out how to write correctly. Anytime I run my program I end up with the first result of (rslt < 3) no matter what numbers I enter.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String options[] = {
"mild or spicy",
"tea or coffee",
"breakfast or " +
"brunch",
"summer or winter",
"paper or plastic"
};
int answers[] = new int[options.length];
String result[] = new String[answers.length];
boolean bool = true;
while (true) {
for (int i = 0; i < options.length; i++) {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 1] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 2] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 3] + "?");
answers[i] = scanner.nextInt();
System.out.println("Do you prefer " + options[i + 4] + "?");
answers[i] = scanner.nextInt();
break;
}
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
int rslt = getScore(result);
if (rslt < 3)
System.out.println("You prefer life to be calm and organized");
else if (rslt > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
int out = scanner.nextInt();
if (out == 0)
bool = false;
if (!bool)
System.exit(0);
}
}
static int getScore(String[] result) {
int score = 0;
for (int i = 0; i < result.length; i++) {
switch (result[i]) {
case "spicy":
score++;
break;
case "coffee":
score++;
break;
case "breakfast":
score++;
break;
case "winter":
score++;
break;
case "paper":
score++;
break;
}
}
return score;
}
}
I have modified your code according to my understanding of the code.
It works just exactly like you may have wanted.
package module1.assignment;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[][] options = {
{"mild", "spicy"},
{"tea", "coffee"},
{"brunch", "breakfast"},
{"summer", "winter"},
{"plastic", "paper"}
};
int[] answers = new int[options.length];
do {
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i][0] +
" or " + options[i][1] + "?");
answers[i] = scanner.nextInt();
}
int result = getScore(answers);
if (result < 3)
System.out.println("You prefer life to be calm and organized");
else if (result > 3)
System.out.println("You prefer life to be spontaneous and active.");
else
System.out.println("You prefer a good balance in life");
System.out.println("Enter 0 to exit program or 1 to run again");
} while (scanner.nextInt() != 0);
}
static int getScore(int[] answers) {
int score = 0;
for (int answer : answers) if (answer == 1) score++;
return score;
}
}
To Fix Your Code
In the first for-loop, you are supposed to loop through the options array. But somehow you unfold the loop within the loop body. To prevent the whole thing loop again, you break the loop immediately. To fix the first loop, write it like this instead. Properly loop through each element, no need to unfold it, no need to break it.
System.out.println("Enter 0 for the preference on the left\n" + "Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
answers[i] = scanner.nextInt();
}
In the second loop, you are supposed to retrieve the selected string from answers and write the string to results. Without modifying your data structure, this can be achieved by using split(" or ") on the option, which gives you an array of string which you can use the answer as index to access. Note that this does not prevent array index out of bound exception if user enter anything other than 0 or 1, which you should totally do, but is out of scope of this question.
for (int i = 0; i < answers.length; i++) {
result[i] = options[i].split(" or ")[answers[i]] ;
}
And there you go.
To Solve Your Task
Alternatively, redesigning the data structure and logic to get rid of the unnecessary string manipulation and comparison is more ideal. You don't even need the result and answers array, simply add up the user input will do (if the user follows your instruction)
int rslt = 0;
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
for (int i = 0; i < options.length; i++) {
System.out.println("Do you prefer " + options[i] + "?");
rslt += scanner.nextInt();
}
Inside the loop, you continue assigning the result to the same index in the answers list, rather than assigning the result to another index for each input. Because you are not iterating anything, you don't even need the loop. Replace the entire while loop with the code below. Please upvote and accept answer if it solves/helps you with your problem.
System.out.println("Enter 0 for the preference on the left\n" +
"Enter 1 for the preference on the right");
System.out.println("Do you prefer " + options[0] + "?");
answers[0] = scanner.nextInt();
System.out.println("Do you prefer " + options[1] + "?");
answers[1] = scanner.nextInt();
System.out.println("Do you prefer " + options[2] + "?");
answers[2] = scanner.nextInt();
System.out.println("Do you prefer " + options[3] + "?");
answers[3] = scanner.nextInt();
System.out.println("Do you prefer " + options[4] + "?");
answers[4] = scanner.nextInt();
Also, please note this:
for (int i = 0; i < answers.length; i++) {
result[i] = [answers[i]];
}
won't work. Instead of result[i] = [answers[i]];, do result[i] = Integer.parseInt(answers.get(i)).
This is part causing the unexpected behaviour: result[i] = [answers[i]];
From what I understood, you want to implement this:
For each option, store the user choice like 0 or 1, 0 for left, 1 for right
For each user choice, store the string value of the choice, i.e., for the 1st question if the user inputs 0, mild should be captured
Calculate scores by comparing string value of user input against a branching construct, switch case here
The problem is in step 2, the current code result[i] = [answers[i]]; does not express this operation properly.
answers[i] stores the user choice 0 or 1, step 1 operation. So to convert it to the corresponding choice in string step 2 operation, something like this should be done
(options[i].split(" or "))[answers[i]]
Explanation:
Pick up the complete string for each answer
Divide the string into two parts(array with 2 indexes 0 and 1), left and right, using a delimiter, " or " in this case
pick up the left or right based on the value stored in answers[i](the user input)
This should let the code behave as expected :)
There are other aspects that can be improved in the code though, as others have already suggested.

Trying to put an if-statement in a for loop

I am trying to input an if-statement inside of this for-loop so that whenever the user still has to eat the loop can be redone without having to lose the data already provided.
boolean yes = true;
boolean no = false;
double calorieCount = DCN;
int snackCalories = 300;
int mealCalories = 1100;
double meal = mealCalories;
double snack = snackCalories;
for (int i = 1; calorieCount <= calorieCount; calorieCount--) {
System.out.println("Did you eat? yes or no");
String answer = sc.next();
if(yes == true) { //You did eat
System.out.println("Did you eat a meal(1) or a snack(2)?");
int foodChoice = sc.nextInt();
if(foodChoice == 1) //Meal
System.out.println("Your calories left for the day : " + (calorieCount - meal));
}
int foodChoice = sc.nextInt();
if(foodChoice == 2) {//Snack
calorieCount = calorieCount - snack;
System.out.println("Your calories left for the day : " + (calorieCount - snack));
}
else {
System.out.println("Your calories left for the day : " + calorieCount);
};
else(no == false){
System.out.println(calorieCount);
}
it seems like you have some real syntax & semantic problems. For example your for-loop condition is calorieCount <= calorieCount. Both sides are equal. Overall its hard to read your Code because its not formatted correctly. Its hard to help right now - use a formatting Tool - Check Syntax and use a Debugger. Then clarify your question. Naming of your variables could also be improved.

How to repeat if statements in while loops [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to have a user guess a number picked by a random number generator, but my code decides to, if it doesn't equal, stick within one if statement.
System.out.println("Enter a guess between 1 and 200: ");
String guess = input.nextLine();
int userInput = Integer.parseInt(guess);
Random rnd = new Random(seed);
int x = rnd.nextInt(200) + 1;
int currentInt = 1;
String msg = "That was impossible!";
and my while loop contains many if statements:
boolean boo = false;
while (!boo) {
if (userInput == x) {
System.out.println("Congratulations! Your guess was correct!");
System.out.println("");
System.out.println("I had chosen " + x + " as the target number.");
System.out.println("You guessed it in " + currentInt + " tries.");
if (currentInt == 1) {
//do something
} else if (currentInt >= 2) {
//do something
} else if (currentInt >= 4) {
...
} else if (currentInt >= 11) {
msg = "Maybe you should play something else";
System.out.println(msg);
}
break;
} else if (userInput > x) {
System.out.println("Your guess was too high - try again.");
System.out.println("");
System.out.println("Enter a guess between 1 and 200: ");
String highGuess = input.nextLine();
int tooHigh = Integer.parseInt(highGuess);
continue;
} else if (userInput < x) {
System.out.println("Your guess was too low - try again.");
System.out.println("");
System.out.println("Enter a guess between 1 and 200: ");
String lowGuess = input.nextLine();
int tooLow = Integer.parseInt(lowGuess);
continue;
}
currentInt = currentInt + 1;
}
My code works decently, if the answer is correct in the first try then the first if statement works, but if it's greater or less than x, then the same block runs (if greater, keeps putting greater even if next input is less than)
Update userInput with tooHigh and tooLow .

A "Stick Game" program in Java not working correctly?

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

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