Ask user to retry only one of his three answers? (java) [closed] - java

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.

Related

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

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

Figuring out odd even and zeros [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 7 years ago.
Improve this question
I am having problems with my java program. I have to input a value then print out the number of odds, evens, and zeroes. The odds and zeroes display fine but the evens display total digits.
import java.util.Scanner;
public class OddEvenZero
{
public static void main(String[] args)
{
int even = 0;
int odd = 0;
int zero = 0;
int placeInValue;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a Value: ");
String valueEntered = scan.nextLine();
for(placeInValue = 0; placeInValue < valueEntered.length(); placeInValue ++)
{
char value = valueEntered.charAt(placeInValue);
int numberUsedInLoop = Integer.parseInt(Character.toString(value));
if(numberUsedInLoop == 0)
{
zero ++;
}
else if(numberUsedInLoop%2 == 0);
{
even ++;
}
if(numberUsedInLoop%2 != 0 && numberUsedInLoop != 0)
{
odd ++;
}
}
System.out.println("Number of Zeroes in Number: " + zero);
System.out.println("Number of Evens in Number: " + even);
System.out.println("Number of Odds in Number: " + odd);
}
}
Output:
Enter a Value:
225500
Number of Zeroes in Number: 2
Number of Evens in Number: 6
Number of Odds in Number: 2
Any help is appreciated.
The semicolon terminates the else if immediately here
else if(numberUsedInLoop%2 == 0); // <-- terminates the else if
{ // <-- raw block
even ++;
}
change it to something like
else if(numberUsedInLoop%2 == 0)
{
even ++;
}
else // <-- just an else should satisfy your conditions
{
odd ++;
}

Why isn't my code randomly generating more than once?

Sorry for probably a noobish question but I can't figure out what's wrong with this code. I've looked everywhere but I couldn't find any answer.
The problem is that it will only randomly generate num and num2 once when I need it randomly genereated 5 times. Any help is greatly appreciated.
import java.util.Scanner;
import java.util.Random;
public class Choice5
{
public static void main(String [] args)
{
Random r = new Random();
Scanner k = new Scanner(System.in);
String name;
int num= 1 + r.nextInt(10);
int num2=1 + r.nextInt(10);
int answer = num*num2;
int attempt;
int countcorrect = 0;
int countincorrect =0;
System.out.println("Hi, what's your name?");
name =k.next();
for(int x=1; x<=5; x++)
{
System.out.println("Test " +x+ " of 5");
System.out.println("Ok " +name+ " What is " +num+ " x " +num2+ " ?");
attempt = k.nextInt();
if(attempt == answer)
{
System.out.println("Good Job " +name+ " the answer was indeed " +answer);
countcorrect++;
}
if(attempt != answer)
{
System.out.println("Incorrect " +name+ " the answer was actually " +answer);
countincorrect++;
}
}
System.out.println("You got " +countcorrect+ " right");
System.out.println("You got " +countincorrect+ " wrong");
if (countcorrect < 3)
{
System.out.println("You should try the test again");
}
else
{
System.out.println("Good job " +name+ " ,you passed the test!");
}
}
}
You are choosing random numbers for num and num2 exactly once, toward the top of main, and more importantly, before the for loop. These numbers aren't assigned again, so they remain the same during all loop iterations.
To have them change for each loop iteration, declare the variables for the numbers and the answer, and assign new values inside the for loop, instead of before it.
for(int x=1; x<=5; x++)
{
int num= 1 + r.nextInt(10);
int num2=1 + r.nextInt(10);
int answer = num*num2;
// rest of code is the same
You generate a random number when, in this case, you call nextNum() As you can see you only call this once for num and num2 since it is out of the loop.
Simple answer, put those calls within your loop to create more than one random number.

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

I am comparing 2 sets of integer values from 2 saparate arrays

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.");
}

Categories