On a game I am making, I have 4 doors, all with if's and else if's. But the code only allows for the first two doors, I don't know why exactly?
EDIT: VERY SORRY! I ASKED THE WRONG QUESTION. HERE IS THE REPHRASED:
The i1 is the input. i1==1 and i1==2 works, but i1==3
and i1==4 causes a break in the software, what is the issue?
Here is the complete code:
/**
* Write a description of class GameE02 here.
*
* #Aakarsh
* #1.0 (18 October 2015)
*/
import java.util.*;
//System.out.print('\f'); clear everything.
public class GameE02
{
public static void main(String [] args) throws InterruptedException{
Scanner reader = new Scanner(System.in);
int i1, i2, i3, i4, i5, i6, i7, i8, i9;
int o1, o2, o3, o4, o5, o6, o7, o8, o9;
String s1, s2, s3, s4, s5, s6, s7, s8, s9;
boolean loop = false;
boolean thugloop = false; //thug hop scotch loop
int counter = 1; //staircase counter
int counter2 = 1; //thug hopscotch counter
//somewhere, add in a never ending loop cycle (game over basically). Secret code required to end the game.
System.out.println("Do you want to play a game? (y = yes, n = no)");
s1 = reader.next();
System.out.println("You walk into a room, there are 5 doors on the left one room on the right, you look at the room; do you wish to enter?");
s2 = reader.next();
//Begin the stairchase choice - Step 1 of the game.
if(s2.equals("y")){
Thread.sleep(1000);
System.out.println("You have entered the room, you see a spiral staircase going up or chance to exit; you look at the staircase, do you wish to enter?");
s3 = reader.next();
Thread.sleep(1000);
loop = true;
System.out.println("You walk up the stairs, but you shockingly see yourself back in the same room, same position, climb again?");
s3 = reader.next(); //begin the staircase loop
while(loop==true){
if(s3.equals("y")){
System.out.println("You walk up the stairs, but you shockingly see yourself back in the same room, same position, climb again?");
s3 = reader.next();
counter++;
}else if(s3.equals("n")){
System.out.println("You have chosen not to climb the staircase.");
loop=false;
break;
}
} //loop ends here.
Thread.sleep(1000);
System.out.println("You are frightened and you walk back and see six doors, pick one (1, 2, 3, 4, 5, 6)");
//pun - pick one
s5=reader.next();
if(s5.equals("1")){
System.out.println("Good, you understood the pun; you may still have a chance at surviving.");
Thread.sleep(1000);
//add in the rest of the code here.
}else{
System.out.println("Damn, you really suck at reading - what are you, an AP Computer Science student? I said: 'six doors.. pick ONE...");
Thread.sleep(3950);
System.out.println("Since you lost that, I need to put you in the maze, sorry!");
}
} if(s2.equals("n")){
counter=0;
Thread.sleep(1000);
System.out.println("You see four doors, which one do you pick? (1, 2, 3, 4)");
i1 = reader.nextInt(); //door choice number.
if(i1 == 1){
Thread.sleep(500);
System.out.println("You go inside a dungeon, and meet a skeleton there; ");
Thread.sleep(1000);
System.out.println("You talk to the skeleton; Press 'y' if you want to play thug hop-scotch, or 'n' if you want to fight.");
s4=reader.next();
if(s4.equals("y")){
Thread.sleep(1000);
System.out.println("Enter some 5 (after this) from 1 to maximum-17 (inclusive) individually. Repeats are allowed.");
i4=reader.nextInt();
i5=reader.nextInt();
i6=reader.nextInt();
i7=reader.nextInt();
i8=reader.nextInt();
int sumhop = i4 + i5 + i6 + i7 + i8;
System.out.println("Through a complex algorithm your sequence of numbers read " + sumhop);
Thread.sleep(3700);
System.out.println("Fortunately (or unforunately) the thug you were playing hopscotch against was confident so he had this program generate him a random number.");
Thread.sleep(2500);
int randomhop = 3 + (int)(Math.random()*84); //thug hop scotch random.
System.out.println("His random number generated was: " + randomhop);
Thread.sleep(1000);
if(sumhop < randomhop){
System.out.println("Seriously? READ CAREFULLY - When asking the question, I told you: 'Enter 5 SUM-numbers-MAXIMUM'.");
Thread.sleep(3000);
System.out.println("You should have done 17*5 = 85 to outbeat the thug");
Thread.sleep(3000);
System.out.println("Anyway, time to do battle with the thug skeleton!");
counter2=0;
} else if(sumhop > randomhop){
System.out.println("Woah, you beat the thug; but now the thug is angry and he won't rest until he beats you.");
Thread.sleep(2000);
thugloop = true;
System.out.println("Pick your numbers again");
o4=reader.nextInt();
o5=reader.nextInt();
o6=reader.nextInt();
o7=reader.nextInt();
o8=reader.nextInt();
int sumhop2 = o4+o5+o6+o7+o8;
int angrythug = 3 + (int)(Math.random()*85);
while(thugloop == true){
if(sumhop2>angrythug){
counter2++;
Thread.sleep(1000);
System.out.println("The thug picked: " + angrythug + " .Woah, you are really good at this!");
Thread.sleep(1500);
System.out.println("But the thug is getting angrier. Pick again!");
o4=reader.nextInt();
o5=reader.nextInt();
o6=reader.nextInt();
o7=reader.nextInt();
o8=reader.nextInt();
sumhop2 = o4+o5+o6+o7+o8;
angrythug = 3 + (int)(Math.random()*85);
}else if(sumhop2<angrythug){
thugloop = false;
break;
}
}
System.out.println("Aha, the thug picked: " + angrythug + " -- you couldn't outdo the thug, could you? Well, it was a good run; time to do battle with the skeleton.");
Thread.sleep(3000);
s4="n";
}
} if(s4.equals("n")){
Thread.sleep(1000);
System.out.println("Now -- it is time to fight the skeleton");
Thread.sleep(2000);
System.out.println("Your survival depends on your mathematics skills.");
Thread.sleep(2700);
System.out.println("Type in your answers one-by-one.");
Thread.sleep(2500);
System.out.println("By the way, Fetty Wap's song six-seven-nine is missing something.");
Thread.sleep(3500);
System.out.println("(1) What is the highest power of 2 that divides 10! (factorial)");
Thread.sleep(4000);
System.out.println("(2) You write the numbers from 1... onwards like: 123456789(10)(11)..(643)..(707)..(984)... What is the number that starts on the 2013th digit of this sequence?" );
int a1 = reader.nextInt();
int a2 = reader.nextInt();
int suma = a1+a2;
if(suma==715){
System.out.println("Wow, you're pretty damn smart; you beat the skeleton and all the odds. You might have won the game, all there is left is one question. READ CAREFULLY.");
Thread.sleep(5000);
System.out.print('\f');
System.out.println("Read carefully: Write your answers AFTER ALL QUESTIONS APPEARED;");
System.out.println("I hope you remembered everything; one-by-one, in order- write how many times you:");
System.out.println("(1) Walked up the stairs (including loops, everything)");
System.out.println("(2) How many times you beat the thug at hopscotch (including loops etc..)");
int f1, f2;
f1 = reader.nextInt();
f2 = reader.nextInt();
int sumf = f1+f2;
if(sumf==counter+counter2){
System.out.println("Congratulations, you have beaten the odds and won the game. Now, do something worthwhile =)");
System.exit(0);
}
}
}
} if(i1 == 2){
Thread.sleep(500);
System.out.println("You go inside a dungeon, and meet a skeleton there; ");
Thread.sleep(1000);
System.out.println("You talk to the skeleton; Press 'y' if you want to play thug hop-scotch, or 'n' if you want to fight.");
s4=reader.next();
if(s4.equals("y")){
Thread.sleep(1000);
System.out.println("Enter some 5 (after this) from 1 to maximum-17 (inclusive) individually. Repeats are allowed.");
i4=reader.nextInt();
i5=reader.nextInt();
i6=reader.nextInt();
i7=reader.nextInt();
i8=reader.nextInt();
int sumhop = i4 + i5 + i6 + i7 + i8;
System.out.println("Through a complex algorithm your sequence of numbers read " + sumhop);
Thread.sleep(3700);
System.out.println("Fortunately (or unforunately) the thug you were playing hopscotch against was confident so he had this program generate him a random number.");
Thread.sleep(2500);
int randomhop = 3 + (int)(Math.random()*84); //thug hop scotch random.
System.out.println("His random number generated was: " + randomhop);
Thread.sleep(1000);
if(sumhop < randomhop){
System.out.println("Seriously? READ CAREFULLY - When asking the question, I told you: 'Enter 5 SUM-numbers-MAXIMUM'.");
Thread.sleep(3000);
System.out.println("You should have done 17*5 = 85 to outbeat the thug");
Thread.sleep(3000);
System.out.println("Anyway, time to do battle with the thug skeleton!");
counter2=0;
} else if(sumhop > randomhop){
System.out.println("Woah, you beat the thug; but now the thug is angry and he won't rest until he beats you.");
Thread.sleep(2000);
thugloop = true;
System.out.println("Pick your numbers again");
o4=reader.nextInt();
o5=reader.nextInt();
o6=reader.nextInt();
o7=reader.nextInt();
o8=reader.nextInt();
int sumhop2 = o4+o5+o6+o7+o8;
int angrythug = 3 + (int)(Math.random()*85);
while(thugloop == true){
if(sumhop2>angrythug){
counter2++;
Thread.sleep(1000);
System.out.println("The thug picked: " + angrythug + " .Woah, you are really good at this!");
Thread.sleep(1500);
System.out.println("But the thug is getting angrier. Pick again!");
o4=reader.nextInt();
o5=reader.nextInt();
o6=reader.nextInt();
o7=reader.nextInt();
o8=reader.nextInt();
sumhop2 = o4+o5+o6+o7+o8;
angrythug = 3 + (int)(Math.random()*85);
}else if(sumhop2<angrythug){
thugloop = false;
break;
}
}
System.out.println("Aha, the thug picked: " + angrythug + " -- you couldn't outdo the thug, could you? Well, it was a good run; time to do battle with the skeleton.");
Thread.sleep(3000);
s4="n";
}
} if(s4.equals("n")){
Thread.sleep(1000);
System.out.println("Now -- it is time to fight the skeleton");
Thread.sleep(2000);
System.out.println("Your survival depends on your mathematics skills.");
Thread.sleep(2700);
System.out.println("Type in your answers one-by-one.");
Thread.sleep(2500);
System.out.println("By the way, Fetty Wap's song six-seven-nine is missing something.");
Thread.sleep(3500);
System.out.println("(1) What is the highest power of 2 that divides 10! (factorial)");
Thread.sleep(4000);
System.out.println("(2) You write the numbers from 1... onwards like: 123456789(10)(11)..(643)..(707)..(984)... What is the number that starts on the 2013th digit of this sequence?" );
int a1 = reader.nextInt();
int a2 = reader.nextInt();
int suma = a1+a2;
if(suma==715){
System.out.println("Wow, you're pretty damn smart; you beat the skeleton and all the odds. You might have won the game, all there is left is one question. READ CAREFULLY.");
Thread.sleep(5000);
System.out.print('\f');
System.out.println("Read carefully: Write your answers AFTER ALL QUESTIONS APPEARED;");
System.out.println("I hope you remembered everything; one-by-one, in order- write how many times you:");
System.out.println("(1) Walked up the stairs (including loops, everything)");
System.out.println("(2) How many times you beat the thug at hopscotch (including loops etc..)");
int f1, f2;
f1 = reader.nextInt();
f2 = reader.nextInt();
int sumf = f1+f2;
if(sumf==counter+counter2){
System.out.println("Congratulations, you have beaten the odds and won the game. Now, do something worthwhile =)");
System.exit(0);
}
}
} if(i1 == 3){
Thread.sleep(1);
System.out.println("Oooooooooh... you picked the maze - good luck");
Thread.sleep(2000);
System.out.println("You stepped on a trap and fall in a dungeon. One way you see the light, the other, darkness. Press 'y' for light-way and 'd' for dark-way.");
String dun = reader.next();
if(dun.equals("y")){
System.out.println("Good you saw the light, now you see a white board with a math question. Press 'y' to proceed or 'n' to go to the dark side.");
String pro = reader.next();
if(pro.equals("y")){
System.out.println("You have chosen to answer the math question.... smart choice.");
Thread.sleep(2000);
System.out.println("what is 2^2?");
int ans = reader.nextInt();
Thread.sleep(7700);
System.out.println("You really thought it would be that easy?");
Thread.sleep(1000);
System.out.println("You are given a 12th degree polynomial is the form: P(x) = 23x^(12) + ax^(11) + ... + 8");
Thread.sleep(1500);
System.out.println("The roots are respectively: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12");
Thread.sleep(3000);
System.out.println("What is the absolute value of the coefficient 'a' in the poylnomial P(x)?");
int poly = reader.nextInt();
if(poly==161){
System.out.println("You have done what many others never could. Now do something worthwhile!");
System.exit(0);
}
} else if(pro.equals("n")){
dun="n";
}
} if(dun.equals("n")){
System.out.println("Okay, you chose the dark side - what is the first name of the 4th US President? (No caps)");
String res = reader.next();
if(res.equals("james")){
System.out.println("Nice. Suddenly, an earthquake appears and you fall down the dungeon.");
Thread.sleep(1500);
System.out.println("You are stuck with a skeleton who wants to play thug hopscotch really badly; you must play - get ready!");
Thread.sleep(4300);
}
} if(i1 == 4){
System.out.println("Huh - smart guy, you won the game.");
System.exit(0);
}
}
}
}
}
}
There is the complete code; please help me out!
Your braces are "missalligned". You are closing the if (i1 == 2) block in the wrong place, and it encapsulates the checks for 3 and 4.
Your IDE should be able to highlight matching braces to help you see where the block ends.
You can use the switch-case construct if you have learned it, it usually makes this type of job easier.
Related
I'm new to Java programming and taking a college course where I have an assignment to create a Hi/Lo guessing game. The game provides up to 5 attempts for the user to input a number between 1 and 100 (inclusive). The program must provide the logic back of whether the answer is too low, too high or correct. The program must provide the option to play again after either winning or the 5 failed attempts.
I've recreated this program about 10 times :(. I cannot get he logic to work to follow the instructions above. I cannot stop the tries at 5 attempts... and I cannot get the program to execute a new game.
Any help is greatly appreciated. I've spent countless hours writing and re-writing this code with MANY different results - but not the intended ones.
This is my first time posting so, I apologize if the format to post is not correct.
I've looked through more forums and examples than I care to admit and none of code I've reviewed and tried implementing have given me the results of limiting the user input to 5 tries each time and ability to play again multiple times.
Here is my code:
public class HiLoGuessingGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Initialize scanner and random number gennerator
Scanner input = new Scanner(System.in);
Random generator = new Random();
//State the rules of the game
System.out.println("The Hi-Lo Guessing Game. Guess a number between 1-100");
System.out.println("You have 5 attempts!");
/* define the variable Guess (user iput)
define the variable Answer (random generator)
define the variable Counter (track number of tries and limit to 5)
define the variable PlayAgain (Y/N question)*/
int guess = 0;
int answer = generator.nextInt(100)+1;
int counter = 1;
String playAgain;
boolean gameOver = false;
//Ask the Hi-Lo question - pick number 1-100 (inclusive)
//Provide feedback answer too high, too low or you win!
//Limit number of tries in the game to 5
while (guess != answer) {
System.out.print("Enter your guess: ");
guess = input.nextInt();
counter++;
if (guess < answer) {
System.out.println("Your guess " + guess + " is too low. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess > answer) {
System.out.println("Your guess " + guess + " is too high. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess == answer) {
System.out.println("Your guess " + guess + " is correct! You win!");
System.out.println();
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
}
if (counter ==6) {
System.out.println("Sorry, you've reached your max atttempts.");
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}
// Play again logic
boolean isValid;
do {
System.out.print("Would you like to play again (Y/N)?");
playAgain = input.next().toUpperCase();
isValid = playAgain.equals("Y") || playAgain.equals("N");
playAgain = input.next();
counter = 1;
if ( !isValid ) {
System.out.println("Error, please enter Y or N");
System.out.println();
}
} while (!isValid);
}
}
You can add an extra condition to your while-loop:
while (guess != answer && counter < 5) {
// ...
}
Alternatively, you can break the loop when you get a right answer:
while (counter < 5) {
// ...
if (answer == guess){
// ...
break;
}
}
Assignment Instructions:
-Prompt the user in main() if he she want to play the game or not. Display a brief description of how the game should be played first.
-Code a method that allows the user to play
-Code a method for the computer throwing two dices.
-Code a method that displays the outcome by showing what the user entered, the user to play as many times as he.she wish...and each time, you must keep track of the number of wins and losses by the player.
-Code a method that display the statistics for all games played and as soon as the player chooses to abort the game. You must display the number of games played, how may were won, how many were lost, and the percentile for each
My problem is keeping track of the number of wins and losses by the player and displaying the correct amount of games that was played, won and loss after multiple turns at the game. (Specifically in the stats() method) I tried to add to the userwins and userloss with "++" but it doesn't remember the amount of games played when the user plays 1 to play another game. If the ++ doesn't work, I believe I should do a counter for it. However, I don't know if this counter should go in main or within the Stats() method.
public class DiceGame_
{
//declarations:
static int answer = 1;//1 to continue or 0 to quit
static Scanner get = new Scanner(System.in);
static int guess = 0;
static int dice1 = 0;
static int dice2 = 0;
static int dicesum = 0;
static int games = 0;
static int userWins = 0;
static int userLoss = 0;
static double percentW = 0;
static double percentL = 0;
static Random random = new Random();
public static void main(String[] args)
{
//Display the game's description and Prompt the user if they would like to play
System.out.println("In this game, you are playing against the computer. The computer will throw 2 dices"
+ " to randomly select 2 numbers between 1 and 6.\nYou will then guess a number between 2 and 12, if the number"
+ " you guess matches the sum of the two dices the computer throws,\nthen you win! Otherwise, the computer wins.");
//input:
while (answer != 0) //while will allow the user to play again
{
GuessNum(); //call GuessNum method
DiceThrow();//call DiceThrow method
//Output:
DispOutcome();//Display outcome method
//ask user if they would like to continue
System.out.println("Would you like to play again? Press 1 for yes or 0 for no: ");
answer = get.nextInt();
}//end while
Stats();//Stats Method (Display # of games played, won and loss, and percentiles of wins/losses)
}//end main
//==========================================================
public static void GuessNum() //The user guesses a number Method
{
System.out.println("Please enter a number between 2-12 for your guess.");
guess = get.nextInt();
while(guess < 2 || guess > 12) //will make sure the user is asked again if they enter a value greater than 12 or less than 2
{
System.out.println("You must select a number between 2 and 12! Please re-enter a guess: ");
guess = get.nextInt();
}//end while
}//end GuessNum method
//==========================================================
public static void DiceThrow() //The computer generates 2 numbers from dice rolls
{
dice1 = random.nextInt(6) + 1;
dice2 = random.nextInt(6) + 1;
dicesum = dice1 + dice2;
}//end DiceThrow method
//==========================================================
public static void DispOutcome() //Displays the outcome of what the user entered, the values of the 2 dice thrown and who won
{
System.out.println("Computer: Dice 1 = " + dice1 + " and Dice 2 = " + dice2);
System.out.println("Player: entered " + guess);
System.out.println("You played " + guess + " and the compuer threw " + dice1 + " and " + dice2 +
" for a total of " + dicesum + "....");
{
if(guess == dicesum)
System.out.println("You won!");
else if(guess != dicesum)
System.out.println("Sorry! You lost!");
}//end if
}//end DispOutcome method
//==========================================================
public static void Stats() //Displays the stats of the game (wins, losses, percentile of each)
{
{
if(guess == dicesum)
userWins ++; //adds 1 to the user's win count if the user wins a game
else if (guess != dicesum)
userLoss ++; //adds 1 to the user's loss count if the user losses the game
}
games = (userWins + userLoss); //total of games is the losses + wins
System.out.println("You've played: " + games + " games");
System.out.println("You've won: " + userWins + " games");
System.out.println("You've loss: " + userLoss + " games");
percentW = (userWins / games);
percentL = (userLoss / games);
System.out.println ( String.format("Your win percentage is %.2f", + (percentW * 100)) + "%");
System.out.println ( String.format("Your loss percentage is %.2f", + (percentL * 100)) + "%");
}//end Stats method
}//end class DiceGame_
You are only calling the Stats() method once, when done, so the userWins++ and userLoss++ statements are only called once. You should move those statements inside the DispOutcome() method so they get called for every game. You already have a check for (guess == dicesum) there, which is where they go.
I can see 2 problems:
Problem #1.
percentW = (userWins / games);
percentL = (userLoss / games);
The variables userWins, games and userLoss are all integers. So the divisions are going to be treated as integer arithmetic. That is going to cause percentW and percentL to be 0.0.
Hint: to force the division to be done using floating point, convert either or both operands to be double. Have you been taught how to convert from one primitive type to another?
Problem #2.
The incrementing of the variables happens in the Stats method. The Stats method is called only once. Therefore the variables only get incremented once.
Hint: if the purpose of Stats is to print out the stats, then you are incrementing the score in the wrong method.
By the way, there are a few problems with style and other things:
Method names should not start with an uppercase letter in Java.
The indentation is inconsistent. I suspect that you are using TAB characters in the source file. This causes problems if you cut-and-paste code into Markdown ... and in other contexts. For example Linux/Mac versus Windows!
It is better to configure your IDE to use SP characters for indentation.
There are issues with how you are using { ... }. For example:
{
if (guess == dicesum)
System.out.println("You won!");
else if (guess != dicesum)
System.out.println("Sorry! You lost!");
}
If you look at that, the braces serve no real purpose there.
In a statement like this:
GuessNum(); //call GuessNum method
the comment is (IMO) harmful. It says nothing that isn't totally obvious from the code. In fact, all it really does is distract the reader.
This code should be OO. You are relying heavily on static methods and static variables. (Maybe that is the next lesson ....)
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 7 years ago.
Im in AP computer science as a high school student. I was bored so i decided to write a rock paper scissor code. It runs a while loop to play a few games in a row and determine a winner, but the first run on the while loop doesnt take in the user input. Its as if the user = scan.nextLine doesnt work on the first run
Scanner scan = new Scanner (System.in);
String answer = "none";
System.out.println("How many games of Rock, Paper, Scissors would you like to play?");
int games = scan.nextInt();
int count = 0;
int computerWins = 0;
int userWins = 0;
int computer = 0;
String user = " ";
while (count < 10)
{
System.out.println("Enter Rock, Paper, or Scissors");
user = scan.nextLine();
computer = ((int)(Math.round((Math.random () * 2) + 1)));
if (computer == 1)
{
answer = "Rock";
}
else if (computer == 2)
{
answer = "Paper";
}
else if (computer == 3)
{
answer = "Scissors";
}
System.out.println("The Computer Chose: " + answer);
if ((answer.equals("Rock")) && (user.equals("Scissors")))
{
System.out.println("The Computer's Rock beats your Scissors");
computerWins++;
}
else if ((answer.equals("Paper")) && (user.equals("Rock")))
{
System.out.println("The Computer's Paper beats your Rock");
computerWins++;
}
else if ((answer.equals("Scissors")) && (user.equals("Paper")))
{
System.out.println("The Computer's Scissors beat your Paper");
computerWins++;
}
else if (answer.equals(user))
System.out.println("TIE! Your " + user + " is the same as the Computer's " + answer);
else
{
System.out.println("Your " + user + " beats the Computer's " + answer);
userWins++;
}
count++;
System.out.println("Score Stands: Computer " + computerWins + " You " + userWins);
}
Firstly, I think you might find you're using Java.
In terms of your question, this comes up frequently on Stackoverflow (eg. Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?, or practically an exact copy of your problem, Why doesn't this for-loop let me input text the first cycle?). As a high school student, I'm a little surprised you haven't been taught to research what you can before calling on others.
Anyway ... if you use nextInt the scanner will not move to the next line, so when you use nextLine you are actually reading to the end of the same line as your integer.
There are several ways of dealing with this but, for simplicity, you could just use a scan.nextLine statement after you have acquired the integer. So that part of your code would look like this:
System.out.println("How many games of Rock, Paper, Scissors would you like to play?");
int games = scan.nextInt();
scan.nextLine();
int games = scan.nextInt();
scan.nextLine();
Just add this portion of code after your nextInt() call to consume the rest of the line.
If this is not done,
user = scan.nextLine();
at this line, user will take the value of the rest of the line where the int was.
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.
I am having some problems making a small game for myself. The piece of code I am having problems with is a timeout for user input. For example: The game will show a letter on the screen. The user has to enter that letter by a certain time; if they don't, they take damage. If someone could explain what I could use to fix this problem it would be great.
package weapons;
import java.util.Random;
import java.util.Scanner;
class wepons {
public static void main(String args[]){
int weapondamage =0 , health = 0 , hits = 0, potion = 0, beast = 0, beastdmg = 0, letter = 0;
String weapon;
;
Scanner in = new Scanner (System.in);
System.out.println ("please pick a wepon that will kill the boss \n");
weapon = in.nextLine().toLowerCase();
if (weapon.equals("sword")){
System.out.println("you have picked the sword");
weapondamage = (int) ((Math.random()*100));
health = weapondamage*3;
}
System.out.println("Sword damage is " + weapondamage);
System.out.println("Boss health is " + health);
System.out.println("Enter the amount of hits it will take to kill the boss.");
hits = in.nextInt();
if(hits == health/weapondamage) {
System.out.println("you have killed the boss.The boss had droped a potion.\nYou pick up the potion and drink it!\nYour health has now gone up to 350hp");
}
else {
System.out.print("You have failed to kill the boss");
}
potion = (int)350;
beastdmg = (int) ((Math.random()*60));
System.out.println("By killing the boss you have awoken the beast!");
System.out.println("The beast nocks you onto your back");
System.out.println("The beast will hit you for"+beastdmg+"damage");
System.out.println("You can block the beast damage by hitting the write key");
Random r = new Random();
int c = r.nextInt(26) + (byte)'a';
System.out.println((char)c);
letter = in.next().charAt(0);
if( letter == ((char)c)){
System.out.println("You blocked the beast damage");
}
else {
System.out.print("You took damage");
}
}
} // main
There are various ways to do this, I'm answering using the OP's style, in the simplest possible way, so measuring user time to press the letter. Here's a functioning snippet:
System.out.println("You can block the beast damage by hitting the write key");
long startTime = System.currentTimeMillis();
Random r = new Random();
int c = r.nextInt(26) + (byte) 'a';
System.out.println((char) c);
char letter = in.next().charAt(0);
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
if (letter == ((char) c) && elapsedTime <=5000) {
System.out.println("You blocked the beast damage");
} else {
System.out.print("You took damage");
}
Hope it helps.
You'd need to take a look at Threads.
With threads, you can execute several processes at once, rather than just linear coding line by line.
For example, you could say:
while(health > 0){
Thread.sleep(5000); //parameter for sleep is milliseconds, so this is 5 seconds
if(weapon == null){
health -= damage;
}else{ break; }
}
The problem with this is that you might need to create a separate class which extends Thread to invoke the damage loss... If the timed aspect is that necessary I would suggest reading up on threads. Don't take this code snipped literally, this is just a basic outline... From my experience with threads you would need to create a method that would return the weapon value, because you want your Thread to check if the user inputed the value for a weapon.
You also may want to refer to this threading tutorial:
https://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html