Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Lost Newbie!
please improve the code it never shows the conditions. As well as i need to put four wins in a row for the user to win. please help!!
import java.util.Scanner;
import java.util.Random;
public class HiLoGame {
public static void main (String[] args) {
String guess=null;
String high= "high";
String low="low";
String equal = "equal";
int nextCard;
int card=3;
System.out.println("Current card is: "+ card);
if(card==11){
System.out.println ("Which means it is card jack!");
}else if(card==12){
System.out.print("which means it is card queen!");
}else if(card==13){
System.out.println("Which means it is card king!");
}else if (card==14){
System.out.println("Which means it is card Ace!");
}
System.out.println("WELCOME! to High-Low game.");
System.out.println("Guess four times in a row to win.");
while(true){
Random generator = new Random();
nextCard = generator.nextInt(14)+1;
System.out.println("Next card will be high, low or equal?");
Scanner input = new Scanner(System.in);
guess = input.next();
System.out.println("It is --> "+ nextCard);
card = generator.nextInt(14)+2;
nextCard = generator.nextInt(14)+2;
System.out.println("Next card will be high, low or equal?");
Scanner input1 = new Scanner(System.in);
guess = input1.next();
System.out.println("It is --> "+ nextCard);
while(true){
if (guess.equals(high))
{
if (card < nextCard)
{
System.out.println("NICE GUESS ");
System.out.println("KEEP PLAYING");
break;
}
else
{
System.out.println("Sorry WRONG GUESS!");
System.out.println("Better luck next time");
System.exit(0);
}
}
else if (guess.equals(low))
{
if (card > nextCard)
{
System.out.println("NICE GUESS");
System.out.println("KEEP PLAYING");
break;
}
else
{
System.out.println("Sorry WRONG GUESS!");
System.out.println("Better luck next time");
}
}
else if(guess.equals(equal))
{
if (card==nextCard)
{
System.out.println("NICE GUESS");
System.out.println("KEEP PLAYING");
break;
}
else
{
System.out.println("Sorry WRONG GUESS");
System.out.println("Better luck next time!");
System.exit(0);
}
}
}}}}
your code is a bit strange and confusing but I have taken the time to go through it, any questions feel free to ask:
import java.util.Scanner;
import java.util.Random;
public class HiLoGame {
public static void main(String[] args) {
Random generator = new Random();
Scanner input = new Scanner(System.in);
String guess = null, result = null;
Boolean won = false;
int nextCard, card = 3, count = 0;
System.out.println("Current card is: " + card);
switch (card) {
case 11:
System.out.println("Which means it is card jack!");
break;
case 12:
System.out.print("which means it is card queen!");
break;
case 13:
System.out.print("which means it is card king!");
break:
case 14:
System.out.println("Which means it is card Ace!");
break;
}
System.out.println("WELCOME! to High-Low game.\nGuess four times in a row to win.");
while (!won) {
nextCard = generator.nextInt(14) + 1;
System.out.println("You current card is: " + card + "\nWill the next card be high, low or equal?");
guess = input.next().toLowerCase();
System.out.println("The next card is:" + nextCard);
if(card<nextCard){
result = "high";
}
else if(card>nextCard){
result = "low";
}
else if(card==nextCard){
result = "equal";
}
if(guess.equals(result)){
System.out.println("NICE GUESS\nKEEP PLAYING");
card = nextCard;
count++;
}
else {
System.out.println("Sorry WRONG GUESS!\nBetter luck next time");
count=0;
}
if(count==4){
System.out.println("Congratulations, you have beaten the game!!!\nWould you like to play again? Yes/No");
guess = input.next().toLowerCase();
if(guess.equals("yes"))
{
count = 0;
card = generator.nextInt(14) + 1;
}
else{
System.out.println("Thank you for playing, goodbye");
System.exit(0);
}
}
}
}
}
Good luck with your learning!
A few of the things used in this code compared to the code in question are:
I have used a switch block, this is used instead of multiple if statements, you can pass in the variable and then in the line: case you put in what you want to match it against, this looks a lot nicer and is much more efficient than using multiple if statements.
I have also used a \n in the printline this is the escape xhar for a newline. You can use this instead of multiple print line statements.
You should try in your code to minimise the amount of repeated text, my code is far from perfect but if it was then you wouldn't have anything to look into.
Instead of calling multiple if statements also try doing one set of if statements to check a condition and then save the result in advance, this changes the amount of comparisons...
Hopefully that makes sense to you.
Related
in this code is playing Rock Paper Scissors, between the computer and the user. My code is all working great, however, I'm trying to think of a better way to make it ask the user if they would want to play again. If yes, then it would start the program again, if no, then it would stop. My "yes" seems to work but the no will stop and not go through all the way. Any suggestions or tips on how to do this? I will trying to incorporate a different while loop, but wasn't working. Would a do loop be good for this scenario? Thanks!
//import scanner
import java.util.Scanner;
import java.util.*;
//declare variables and main methods
class Rock {
Scanner scan = new Scanner(System.in);
Random generator = new Random();
String response, name;
char choice;
int rounds, computerChoice, userScore, computerScore;
boolean playIntro = true;
boolean playGame = true;
//this method will run the entire progrma
public void playRPS(){
//while loop for beginning of game
while(playIntro){
System.out.println("This is a game of Rock Paper Scissors!");
System.out.println("Please enter your name: ");
name = scan.nextLine();
//while loop for the actual part of the game
while(playGame){
System.out.println("Type R (Rock), P (Paper), or S (Scissors): ");
choice = scan.nextLine().charAt(0);
computerChoice = generator.nextInt(3)+1;
//using switch and case for each choice
switch (choice){
//case for Rock
case 'R':
if(computerChoice==1){
System.out.println("Tie between you and the computer! Go again.");
break;
}
else{
if(computerChoice==2){
System.out.println("The computer beat you this round");
computerScore++;
break;
}
else{
System.out.println("You won this round");
userScore++;
break;
}
}
//case for Paper
case 'P':
if(computerChoice==2){
System.out.println("Tie between you and the computer! Go again.");
break;
}
else{
if(computerChoice==3){
System.out.println("The computer beat you this round");
computerScore++;
break;
}
else{
System.out.println("You won this round");
userScore++;
break;
}
}
//case for Scissors
case 'S':
if(computerChoice==3){
System.out.println("Tie between you and the computer! Go again.");
break;
}
else{
if(computerChoice==1){
System.out.println("The computer beat you this round");
computerScore++;
break;
}
else{
System.out.println("You won this round");
userScore++;
break;
}
}
}
System.out.println("You have "+userScore+" points and the computer has "+computerScore+" points");
if (userScore==5){
System.out.println("\nOut of 5 rounds, You beat the computer!");
playGame = false;
}
else if (computerScore==5){
System.out.println("\nOut of 5 rounds, The computer beat you.");
playGame = false;
}
}
askUser();
}
}
public void askUser(){
System.out.println("\nDo you want to play this Rock Paper Scissors again? Type yes: ");
response = scan.nextLine();
if (response.equalsIgnoreCase("yes")){
playGame = true;
userScore=0;
computerScore=0;
}
else{
playGame = false;
scan.nextLine();
}
}
public static void main() {
Rock prog = new Rock();
prog.playRPS();
}
}
I wouldn't say this is necessarily more efficient or even better but it is a little more concise. It's major elements are.
use Lambdas to decide the winner based on the chosen move.
use a map to call the proper Lambda based on the user's move. The lambda then evaluates the two moves to decide the outcome.
for simplicity, moves are selected by number
Of course, the important thing is that your code works.
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.function.Function;
public class RockPaperScissors {
final static int PAPER = 1;
final static int ROCK = 2;
final static int SCISSORS = 3;
// the next two declarations allows the previous three to take on any values.
private Set<Integer> allowedMoves = Set.of(PAPER, ROCK, SCISSORS);
private List<String> moves = List.of("PAPER", "ROCK", "SCISSORS");
private String ROCK_WINS_MSG = "Rock crushes scissors";
private String SCISSORS_WINS_MSG = "Scissors cuts paper";
private String PAPER_WINS_MSG = "Paper covers rock";
private String COMPUTER_WINS = ", computer wins!";
private String YOU_WIN = ", you win!";
private Function<Integer, String> CHECK_PAPER =
(c) -> c == PAPER ? "It's a tie!" :
c == ROCK ? PAPER_WINS_MSG + YOU_WIN :
SCISSORS_WINS_MSG + COMPUTER_WINS;
private Function<Integer, String> CHECK_ROCK =
(c) -> c == ROCK ? "It's a tie!" :
c == SCISSORS ? ROCK_WINS_MSG + YOU_WIN :
PAPER_WINS_MSG + COMPUTER_WINS;
private Function<Integer, String> CHECK_SCISSORS =
(c) -> c == SCISSORS ? "It's a tie!" :
c == PAPER ? SCISSORS_WINS_MSG + YOU_WIN :
ROCK_WINS_MSG + COMPUTER_WINS;
private Map<Integer, Function<Integer, String>> evalUser =
Map.of(PAPER, CHECK_PAPER, ROCK, CHECK_ROCK, SCISSORS,
CHECK_SCISSORS);
public static void main(String[] args) {
new RockPaperScissors().play();
}
public void play() {
Random r = new Random();
Scanner scan = new Scanner(System.in);
while (true) {
System.out.printf("%n%d : %s%n%d : %s%n%d : %s%n%s%n",
PAPER, "PAPER", ROCK, "ROCK", SCISSORS,
"SCISSORS", "Any other integer to quit.");
System.out.print("Your move! ");
String str = scan.nextLine();
int move;
try {
move = Integer.parseInt(str);
if (!allowedMoves.contains(move)) {
break;
}
} catch (IllegalArgumentException ie) {
System.out.println("Only integers permitted.");
continue;
}
System.out.println("\nYou chose " + moves.get(move - 1));
int cmove = r.nextInt(3);
System.out.println(
"The computer chooses " + moves.get(cmove));
System.out.println(evalUser.get(move).apply(cmove + 1));
}
System.out.println("\nGame over!");
}
}
Once suggestion for your code would be to look at the switch cases. The code for each case is practically identical. I would look for similarities and make the evaluation a single method (something I didn't really do in my code). Then in each case, call that method with the appropriate arguments. One such argument would be either "computer" or "you" based on the context.
There's nothing that ever sets playIntro false, and therefore the outer loop will never terminate.
When askUser() sets playGame false the inner loop terminates, and you fall into the outer loop, which keeps on looping.
I don't see any reason for the outer loop to exist at all. You only want to print the introduction and ask the player's name once.
This isn't so much a matter of 'efficiency' as of correctness.
Incidentally, it would be better to make askUser() return a true/false value rather than set a member variable. Then you can use it directly in a 'while' expression.
The overall structure of playRPS() then looks like:
public void playRPS() {
... print intro, ask name ...
do {
... play one game ...
} while (askUser());
}
I wrote a simlpe dice game and would like to know a way to reset the program after typing something like "Reset". I use cmd to run my programs. There is no graphics included in any of my programs whatsoever.
import java.util.Scanner;
import java.util.Random;
public class Dice
{
public static void main(String[] args)
{
String personPlay; //User's play
String computerPlay = ""; //Computer's play
int computerInt; //Randomly generated number used to determine computer's play
String response;
Scanner scan = new Scanner(System.in);
Random generator = new Random();
System.out.println("Let's play some dice!");
//Generate computer's play
computerInt = generator.nextInt(6)+1;
//Translate computer's randomly generated play to
//string using if statements
if (computerInt == 1)
computerPlay = "1";
else if (computerInt == 2)
computerPlay = "2";
else if (computerInt == 3)
computerPlay = "3";
else if (computerInt == 4)
computerPlay = "4";
else if (computerInt == 5)
computerPlay = "5";
else if (computerInt == 6)
computerPlay = "6";
//Get player's play from input
System.out.println("Choose a number between 1 and 6.");
personPlay = scan.next();
//Print computer's play
System.out.println("The dice rolled " + computerPlay);
//See if you won.
if (personPlay.equals(computerPlay))
System.out.println("You won!");
else System.out.println("You lost!");
}
}
You should use an infinite loop and get input from user, check if user entered "RESET", if so roll the dice again or do whatever you're doing now.
If he entered a phrase like "EXIT" infinite loop ends or your program ends.
Usually I don't like giving full answers, but there are some improvements I wanted to show and just listing them would be a lot of work as well.
import java.util.Scanner;
import java.util.Random;
public class Dice
{
private static void play(Scanner scan, Random generator)
{
int computersPlay, usersPlay;
System.out.println("Let's play some dice!");
computersPlay = generator.nextInt(6) + 1;
System.out.print("Give a number:");
usersPlay = scan.nextInt();
System.out.printf("The dice rolled %d\n", computerPlay);
if (computersPlay == usersPlay) {
System.out.println("You win !");
}
else {
System.out.println("You lose!");
}
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Random generator = new Random();
do {
play(scan, generator);
System.out.println("If you want to continue type:'Reset'");
} while(scan.next().equals("Reset");
}
}
Changes moving the play to a different method to keep oversight, using the Scanners nextInt method to obtain a number directly and compare that instead, and the do {} while(); statement to let it repeat an arbitrary amount of times (given that you type reset)
By "reset" I assume you meant "repeat"? Use a while loop.
Also, no real need to store String values other than capture what the user entered.
public class DiceGuess {
// Global variables for this class
static Random generator = new Random();
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Let's play some dice!");
// Initialize some variables
int computerInt;
String response;
while (true) { // Play forever
computerInt = generator.nextInt(6) + 1;
System.out.println("Choose a number between 1 and 6. ('quit' to stop playing)");
response = scan.nextLine();
if (response.equalsIgnoreCase("quit")) break; // Stop the game
try {
System.out.println("The dice rolled " + computerInt);
if (Integer.parseInt(response) == computerInt) {
System.out.println("You won!");
} else {
System.out.println("You lost!");
}
} catch (NumberFormatException e) {
System.err.println("That wasn't a number!");
}
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
package kbc;
import java.io.*;
import java.util.*;
public class qa {
String question;
String answer1,answer2,answer3,answer4;
String correctanswer;
}
class mykbc{
final static int noques=25;
public static void main(String []args){
try{
Scanner input;
input=new Scanner(System.in);
RandomAccessFile raf=new RandomAccessFile("hello.txt","r");
ArrayList<Integer>al=new ArrayList<Integer>();
TreeMap<Integer,qa>tm=new TreeMap<Integer,qa>();
long filelength= raf.length();
for(int loop=0;loop<15;++loop){
int currentques;
do{
currentques=(int)(Math.random()*noques);
if(!al.contains(currentques)){
al.add(currentques);
break;
}
}
while(true);
raf.seek(0);
int track=0;
qa cqa=new qa();
while(raf.getFilePointer()< filelength){
cqa.question=raf.readLine();
cqa.answer1=raf.readLine();
if(cqa.answer1.charAt(0)=='$'){
cqa.answer1=cqa.answer1.substring(1,cqa.answer1.length());
cqa.correctanswer=cqa.answer1;
}
cqa.answer2=raf.readLine();
if(cqa.answer2.charAt(0)=='$'){
cqa.answer2=cqa.answer2.substring(1,cqa.answer2.length());
cqa.correctanswer=cqa.answer2;
}
cqa.answer3=raf.readLine();
if(cqa.answer3.charAt(0)=='$'){
cqa.answer3=cqa.answer3.substring(1,cqa.answer3.length());
cqa.correctanswer=cqa.answer3;
}
cqa.answer4=raf.readLine();
if(cqa.answer4.charAt(0)=='$'){
cqa.answer4=cqa.answer4.substring(1,cqa.answer4.length());
cqa.correctanswer=cqa.answer4;
}
if(++track==currentques){
tm.put(loop+1,cqa);
break;
}
}
}
System.out.println("Welcome to KBC");
Set myset=tm.entrySet();
Iterator itr =myset.iterator();
while(itr.hasNext()){
Map.Entry me=(Map.Entry)itr.next();
System.out.println("Question No"+me.getKey());
qa temp=(qa)me.getValue();
System.out.println("A:"+temp.answer1);
System.out.println("B:"+temp.answer2);
System.out.println("C:"+temp.answer3);
System.out.println("D:"+temp.answer4);
System.out.println("Enter the Correct option :");
System.out.println("Answer is:");
String opt = input.nextLine();
if(opt.equals("A"))
{
if(temp.answer1.equals(temp.correctanswer))
{
temp.correctanswer = temp.answer1;
System.out.println ("correct answer");
System.out.println("You Won 1000rs :)\n");
}
else
{
System.out.println("Wrong Answer");
System.out.println("");
System.out.println("You Lost :(");
break;
}
}
if(opt.equals("B"))
{
if(temp.answer2.equals(temp.correctanswer))
{
temp.correctanswer = temp.answer2;
System.out.println ("correct answer");
System.out.println("You Won 20000rs :)\n");
}
else
{
System.out.println("Wrong Answer");
System.out.println("You Lost :(");
break;
}
}
if(opt.equals("C"))
{
if(temp.answer2.equals(temp.correctanswer))
{
temp.correctanswer = temp.answer2;
System.out.println ("correct answer");
System.out.println("You Won 30000rs :)\n");
}
else
{
System.out.println("Wrong Answer");
System.out.println("You Lost :(");
break;
}
}
if(opt.equals("C"))
{
if(temp.answer3.equals(temp.correctanswer))
{
temp.correctanswer = temp.answer3;
System.out.println ("correct answer");
System.out.println("You Won 40000rs :)\n");
}
else
{
System.out.println("Wrong Answer");
System.out.println("You Lost :(");
break;
}
}
if(opt.equals("D"))
{
if(temp.answer4.equals(temp.correctanswer))
{
temp.correctanswer = temp.answer4;
System.out.println ("correct answer");
System.out.println("You Won 50000rs :)\n");
}
else
{
System.out.println("Wrong Answer");
System.out.println("You Lost :(");
break;
}
}
}
raf.close();
}
catch(IOException ex ){
System.out.println(ex.getLocalizedMessage());
}
}
}
Hey Guys.What to ask how i am going to implement a 50 50 lifeline in my KBC or WHO WANTS TO BE A MILLIONAIRE? in the following code of mine?
Another text file of question with the name of hello containing 50 questions.
Simple, just give the player 2 tries to guess. I know that this is not exactly a 50/50 life line However it should act the same. this is because the probability of choosing the correct answer remains the same. For example, in a proper 50 50 life line, the probability of winning is 1/2. the probability of winning normally is 1/4. So, the probability of winning with 2 guesses is 2*1/4 = 2/4 = 1/2. Therefore the chance of winning is the same.
You can accomplish this by using a simple for loop
Where you have String opt = input.nextLine();, you can add:
String opt = input.nextLine();
if(opt.equals("50-50"))
{
Vector v = new Vector(); //java.util.Vector;
v.addElement(temp.answer1);
v.addElement(temp.answer2);
v.addElement(temp.answer3);
v.addElement(temp.answer4);
v.removeElement(temp.correctanswer);
String wa = v.elementAt(new Random().nextInt(3)); // java.util.Random; 1 wrong answer
String opca="", opwa="";
switch(temp.correctanswer)
{
case temp.answer1:
opca = "A";
break;
case temp.answer2:
opca = "B";
break;
case temp.answer3:
opca = "C";
break;
case temp.answer4:
opca = "D";
break;
}
switch(wa)
{
case temp.answer1:
opwa = "A";
break;
case temp.answer2:
opwa = "B";
break;
case temp.answer3:
opwa = "C";
break;
case temp.answer4:
opwa = "D";
break;
}
System.out.println("After 50-50 lifeline, Your options are :");
System.out.println(opca+": "+temp.correctanswer);
System.out.println(opwa+": "+wa);
}
So I wrote a java code for a numbers guessing game. The entire thing is pretty much done. It works by choosing a random number then asking the user for console inputs and then saying whether that is higher or lower than the random number. Once you guess it, it then asks if you want to play again. When you finally say no to this (be it one game or several) it prints out your Overall results including total games, total guesses, avg guesses/game and your best game. I have everything worked out except I cant figure out how to make it print your overall best game.
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) {
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.println("Guesses/game = " + totalGuesses/totalGames);
System.out.println("Best game = ");
}
}
In order to get the best game you need a keep track of the best best after each game, such as a variable that checks it there is a new best game after each game.
Keep track of the best score, which is the lowest number of guesses.
int bestGame = Integer.MAX_VALUE; // at the top
bestGame = Math.min(bestGame, numberOfTries); // at the end of your inner while loop
The worst possible score is the highest number of guesses, which is limited by Integer.MAX_VALUE, so you start there.
By the best game u mean minimum number of tries needed to answer is the best game.
/* int mintries,bestgame,gamenumber=0;
bestgamenumber=0;mintreies=Integer.MAX_VALUE:*/
Add the above lines above your while(play)
gamenumber++;
/*if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
betgame=gamenumber;
}*/
Add the if condition just before closing while(play).
So it will be like
int mintries;
mintreies=Integer.MAX_VALUE:
int gamenumber=0;
int bestgamenumber=0//if you want to print the which game is the best game(!st,2nd,3rd..) ;
while(play)
{
// do all your stuff
gamenumber++;
if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
bestgamenumber=gamenumber;
}
}
}
System.out.println("Game number +bestgamenumber+"was the best game with"+ mintries+"tries);
I am considering that you want to print which game (1st,2nd,3rd)is best and minimum tries made to guess the best game.Correct me if i am wrong.
To fit into the code you have already written, You could
Create a new 'global' variable, for example int bestGame = Integer.MAX_VALUE;.
Whenever the user is done with a game do a check if the current numberOfGuesses is smaller than the current bestGame, and if it is, then overwrite bestGame with the current numberOfGuesses.
At the end, you simply need to output bestGame.
My code is running fine, but every line where I use a scanner it warns me that there is a "Resource leak; 'userGuess' is never closed" I don't understand what it means and could use some help solving it. Also if there is anything else in my code worth fixing I could use the help. Be warned I have a limited knowledge of Java programming. I also cannot get my TryCounter++ to work...
package masterMind2_1;
import java.util.Scanner;
public class MasterMind2_1 {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is(The Numbers Range from 1-4)");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Declare Array
int [] answerArray;
answerArray= new int [4];
//Initialize Array
//Change these value to change the answers needed to win
answerArray[0]=2;
answerArray[1]=3;
answerArray[2]=2;
answerArray[3]=2;
// //Create Board
// System.out.println("-- -- -- --");
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
System.out.println("What is the first Number?");
Scanner userGuess = new Scanner(System.in);
int num = userGuess.nextInt();
if (num==answerArray[0]) {
guessedCount++;
}
System.out.println("What is the Second Number?");
Scanner userGuess1 = new Scanner(System.in);
int num1 = userGuess1.nextInt();
if (num1==answerArray[1]) {
guessedCount++;
}
System.out.println("What is the Third Number?");
Scanner userGuess2 = new Scanner(System.in);
int num2 = userGuess2.nextInt();
if (num2==answerArray[2]) {
guessedCount++;
}
System.out.println("What is the Fourth Number?");
Scanner userGuess3 = new Scanner(System.in);
int num3 = userGuess3.nextInt();
if (num3==answerArray[3]) {
guessedCount++;
}
System.out.println("Your guess was "+ num+" "+num1+" "+num2+" "+num3);
if (num==answerArray[0]) {
System.out.println("First number was correct");
} else {
System.out.println("First number was incorrect");
}
if (num1==answerArray[1]) {
System.out.println("Second number was correct");
} else {
System.out.println("Second number was incorrect");
}
if (num2==answerArray[2]) {
System.out.println("Third number was correct");
} else {
System.out.println("Third number was incorrect");
}
if (num3==answerArray[3]) {
System.out.println("Fourth number was correct");
} else {
System.out.println("Fourth number was incorrect");
}
if (guessedCount==4) {
System.out.println("YAY you won!!");
guessedAll=true;
tryCounter=10;
} else {
System.out.println("Try again, except this time don't fail!");
guessedAll=false;
tryCounter++;
guessedCount=0;
}
}//What if I collected all of the values first
} //then told them if they were right or Wrong?
//Black and White Pegs?
//Fix TryCounter...Why isn't it working
}
Thank you for the Help!
The error message is telling you that you never call the close() method on your Scanner object. A worse problem is that you create multiple Scanners when you only need one.
As for tryCounter not working...
while(tryCounter<9 || !guessedAll)
This will keep looping if either part of the condition is true. My guess is that !guessedAll is evaluating to true beyond 9 guesses, so your loop keeps running. You'll need to change the || to an && to get it stop looping after 9 tries. (Also, print out the values of your variables or use a debugger so you can verify that they are changing when you expect them to.)