Java Unexpected Programming Result - java

I would like to write a game about who would take the last marble and I've successfully run it. But when I attempted to add some error messages to it, such as showing "Incorrect range" when the inputs are out of range, it doesn't work properly. I know the problem is due to the incorrect recognition of variable "totalNum", but how to solve it? Thanks in advance :)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int pn = 1;
System.out.print("Intial no. of marbles [10 ~ 100]: ");
int totalNum = in.nextInt();
int input = 0;
int from = 1;
int to = totalNum/2;
if (totalNum < 10||totalNum > 100) {
System.out.println("Incorrect range. Try again!");
System.out.print("Intial no. of marbles [10 ~ 100]: ");
totalNum = in.nextInt();
}
else {
while (totalNum > 1) {
totalNum = in.nextInt();
System.out.print("Player" + pn + " [" + from + " ~ " + to + "]: ");
input = in.nextInt();
if (input < from||input > to) {
System.out.println("Incorrect range. Try again!");
continue;
}
totalNum = totalNum - input;
System.out.println("Remaining no. of marbles: " + totalNum);
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
}
}
System.out.println("Player" + pn + " takes the last marble.");
if (pn == 1) {
pn = 2;
}
else {
pn = 1;
}
System.out.println("Player" + pn + " wins!");
}

I imagine this line in the while loop is the problem:
totalNum = in.nextInt();
It keeps trying to take the next input from the user but there isn't a second integer. Not sure what happens after that.
Also, your entire program seems to be roughly equivalent to doing
totalNum%2+1
and printing the answer.

Related

How do I exit a for or a while loop with user input in java

import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("-------Welcome to the Radius calculator-------");
String input = new String (" ");
while(input.equals("END")==false) {
for (int i = 1; i < 5; i++)
for (int e = 5; e > 0; e--)
{
{
System.out.println("-----------------------------");
System.out.println("Hey you can use this calcultor " + e + " more time(s) till yoh have to purchase our full version only 3.99");
}
System.out.println("Please enter your Radius if not just type in END at any stage during the program");
Double num =sc.nextDouble();
System.out.println("Enter 1 if you would like to get the area");
System.out.println("Enter 2 if you would like to get the circumfrence");
int num1 = sc.nextInt();
if (num1 == 1) {
System.out.println("The area of the circle with the radius " + num + " is :" + (Math.PI) * (num * num));
} else if (num1 == 2) {
System.out.println("The circumfrence of the circle with the radius " + num + " is :" + (2) * (Math.PI) * (num));
} else {
System.out.println("No answer for you boss");
System.out.println("Try again!");
}
System.out.println("You have used this calculator effiently " + i + " time(s)");
System.out.println("-----------------------------");
}
}
}
}
Heres my code it works but when i type in END an ERROR comes up.(https://i.stack.imgur.com/ZZxEW.png)](https://i.stack.imgur.com/ZZxEW.png)
If theres any othere tips to make my code for effecient would be much appriciated too.
You forgot to ask for the end input during the loops.
The best way to ask for an input of different types is to use BufferedReader Class
BufferedReader reader =new BufferedReader(newInputStreamReader(System.in));
String input = null;
try {
input = reader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
if (input.equals("END")) {
break;
}
After that you can use :
Integer.parseInt(input);
to cast from String to Integer
And don't forget to clean and simplify your code.

I'm stuck with while loop on my random number guessing game

Want it to loop through everything until the user puts in the right number. When the user puts in wrong number it should say "type in a different number". When the user puts in the right number it should say "congrats you won". But until then it will loop and say "type in a different number" and after 5 tries I want it to say "you failed this mission! do you want to try again?"
If they guess it on 1 try they will be giving 500 dollar and second try 400 dollar and so on until 5 tries.
import javax.swing.*;
import java.util.Random;
public class Projekt_1 {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "WELCOME TO GUESS GAME!" + "\nYou gonna guess a number between 1 and 20 " + "\nYou have 5 tries to guess the number! " + "\nYou gonna get more money on less tries, highest win are 500 dollar on one try! " + "\nHOPE YOU LIKE IT :)");
Random talet = new Random();
int secretnumber = talet.nextInt(20) + 1;
int tries = 0;
int money = 600;
String number;
int guess;
boolean win = false;
while (win == false) {
number = JOptionPane.showInputDialog("Guess a number between 1 and 20");
guess = Integer.parseInt(number);
tries++;
if (guess == secretnumber) {
win = true;
} else if (guess > secretnumber) {
JOptionPane.showInputDialog("Your number is to low :(" + "\nType in a higher number!");
guess = Integer.parseInt(number);
} else if (guess < secretnumber) {
JOptionPane.showInputDialog("Your number is to high :(" + "\nType ina a lower number!");
guess= Integer.parseInt(number);
}
}
JOptionPane.showMessageDialog(null, "Congrats you won!" + "\nYour number was " + secretnumber + "\nit took you " + tries + "tries");
}
}
Adding an additional condition in while loop will work. If försök is the number of tries which can have maxium value of 5 (in your case) then condition should be :
while (win == false && försök<5) //if försök starts from 0
{
//code
if(win==true)
break;
försök++;
}
To display the message and score you can just check the value of försök after while loop:
if(försök==5)
{
// display this message: "you failed this mission! do you want to try again?"
score=0;
}
else
{
//display: "congrats you won"
score=(5-försök)*100;
}
Basically your code should be like this:
import javax.swing.*;
import java.util.Random;
class Projekt_1
{
public static void main(String[] args) {
final int maxTries = 5;
JOptionPane.showMessageDialog(null, "Welcome... " + maxTries + " tries ... 500 krones ");
final Random rnd = new Random();
final int hemligtnummer = rnd.nextInt(20) + 1;
int tryCounter = 0;
final int pengar = 500;
String nummer;
int guess = -1;
while (guess != hemligtnummer && tryCounter < maxTries) {
if(tryCounter==0)
nummer = JOptionPane.showInputDialog("...a number 1 and 20");
else
nummer = JOptionPane.showInputDialog("Enter no...");
guess = Integer.parseInt(nummer);
if (guess == hemligtnummer) {
break;
} else if (guess > hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + (tryCounter+1) + " was too big try a smaller one");
} else if (guess < hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + (tryCounter+1) + " too small try a bigger one");
}
tryCounter++;
}
if(tryCounter==5){
JOptionPane.showMessageDialog(null,"Grattis du vann!" + "\nteh number was " + hemligtnummer + "\nDet tog dig " + tryCounter + " försök");
JOptionPane.showMessageDialog(null, "Your price is :" + (pengar - tryCounter * 100) + " Krones");
}
else
{
JOptionPane.showMessageDialog(null,"congrats you won"+"Your price is :" + (pengar - tryCounter * 100) + " Krones" );
}
}
}
you can have a control break while loop. which will be broken when the number of attempts become more then 5 OR when the correct number is inputted.See the below for reference
Scanner s = new Scanner(System.in);
int numOfTries = 0;
int input;
int correctNumn = 15;
while (true) {
input = s.nextInt();
if (input != correctNumn && numOfTries <= 5) {
numOfTries++;
if (numOfTries == 5) {
System.out.println("Game Over");
break;
}
continue;
} else if (input == correctNumn) {
System.out.println("corect ans");
break;
}
}
It is really hard to help you if you post all in your native language... but here is my answer...
the issue with your code was in the hole logi, you never use the variable tries(försök) and If the user guess a wrong number then you read the try again but instead you should start the logic of the while again....
anyways....
Example:
public static void main(String[] args) {
final int maxTries = 5;
JOptionPane.showMessageDialog(null, "Welcome... " + maxTries + " tries ... 500 krones ");
final Random rnd = new Random();
final int hemligtnummer = rnd.nextInt(20) + 1;
int tryCounter = 0;
final int pengar = 600;
String nummer;
int guess = -1;
while (guess != hemligtnummer && tryCounter < maxTries) {
nummer = JOptionPane.showInputDialog("...a number 1 and 20");
guess = Integer.parseInt(nummer);
tryCounter++;
if (guess == hemligtnummer) {
break;
} else if (guess > hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + tryCounter + " was too big try a smaller one");
} else if (guess < hemligtnummer) {
JOptionPane.showMessageDialog(null, "Try " + tryCounter + "too small try a bigger one");
}
}
JOptionPane.showMessageDialog(null,
"Grattis du vann!" + "\nteh number was " + hemligtnummer + "\nDet tog dig " + tryCounter + " försök");
JOptionPane.showMessageDialog(null, "Your price is :" + (pengar - tryCounter * 100) + " Krones");
}

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

Java - Optional loop

This is my code:
/* Linear equation student quiz
* This program creates equations of the form ax + b = c for students to solve.
*/
import java.util.Random;
import java.util.Scanner;
public class MathFunction {
public static void main(String[] args) {
int a, b, c;
double userAnswer, correctAnswer;
int numCorrect = 0;
Random ranNum = new Random();
Scanner input = new Scanner(System.in);
for (int problem = 1; problem <= 10; problem++)
{
a = ranNum.nextInt(2) + 1;
b = ranNum.nextInt(41) - 20;
c = ranNum.nextInt(41) - 20;
System.out.print("\n"+ a + "x + " + b + " = " + c + " ... x = ");
userAnswer = input.nextDouble();
correctAnswer = 1.0 * (c - b) / a;
if (userAnswer == correctAnswer)
{
System.out.println("Correct!");
numCorrect =+ 1;
}
else
{
System.out.println("Sorry, correct answer is " + correctAnswer);
}
}//end for loop
System.out.println("You got " + numCorrect + " out of ten.");
System.out.println("\nWant to do 10 more questions? <y/n>");
}//end main
}//end class
I want to be able to return to the loop if the user enters the character 'y'. The user will be prompted of this option every time they complete 10 of the math problems. Would I use a 'do-while'?
Yes, you should wrap the for loop with a do-while loop that checks if the user entered 'y'.
do {
for (...) {
...
}
System.out.println("You got " + numCorrect + " out of ten.");
System.out.println("\nWant to do 10 more questions? <y/n>");
input.nextLine();
String repeat = input.nextLine();
} while (repeat.equals("y"));
Here what I mean by breaking your program into methods,
/* Linear equation student quiz
* This program creates equations of the form ax + b = c for students to solve.
*/
import java.util.Random;
import java.util.Scanner;
public class MathFunction {
int a, b, c;
double userAnswer, correctAnswer;
int numCorrect = 0;
Random ranNum = new Random();
Scanner input = new Scanner(System.in);
//You function to calculate
public static compute()
{
for (int problem = 1; problem <= 10; problem++)
{
a = ranNum.nextInt(2) + 1;
b = ranNum.nextInt(41) - 20;
c = ranNum.nextInt(41) - 20;
System.out.print("\n"+ a + "x + " + b + " = " + c + " ... x = ");
userAnswer = input.nextDouble();
correctAnswer = 1.0 * (c - b) / a;
if (userAnswer == correctAnswer)
{
System.out.println("Correct!");
numCorrect =+ 1;
}
else
{
System.out.println("Sorry, correct answer is " + correctAnswer);
}
}//end for loop
System.out.println("You got " + numCorrect + " out of ten.");
System.out.println("\nWant to do 10 more questions? <y/n>");
}
public static void main(String[] args) {
// Then start by sking a question like "Ready to staxt Y/N"
//get user responce or user input and if user input is Y then call the compute method else system exit.
if(userAnswer=="Y")
{
compute();
}
else{
//Thanks for participating system closes.
System.exit(0);
}
}//end main
}//end class
Here is the simple solution
String choice = "y";
while(choice.equals("y")){
for (int problem = 1; problem <= 10; problem++)
{
a = ranNum.nextInt(2) + 1;
b = ranNum.nextInt(41) - 20;
c = ranNum.nextInt(41) - 20;
System.out.print("\n"+ a + "x + " + b + " = " + c + " ... x = ");
userAnswer = input.nextDouble();
correctAnswer = 1.0 * (c - b) / a;
if (userAnswer == correctAnswer)
{
System.out.println("Correct!");
numCorrect =+ 1;
}
else
{
System.out.println("Sorry, correct answer is " + correctAnswer);
}
}//end for loop
System.out.println("You got " + numCorrect + " out of ten.");
System.out.println("\nWant to do 10 more questions? <y/n>");
choice = input.nextLine(); // get the input
}
-> Wrap your code in a do while loop.
-> Also use input.nextLine() for reading all user inputs (double value and string "y" or "n"), as switching between input.nextDouble() and input.nextLine() , can sometimes cause errors. Parse the input value to double after user input.
outer: //label
do{
for (int problem = 1; problem <= 10; problem++)
{
a = ranNum.nextInt(2) + 1;
b = ranNum.nextInt(41) - 20;
c = ranNum.nextInt(41) - 20;
System.out.print("\n"+ a + "x + " + b + " = " + c + " ... x = ");
try{
userAnswer = Double.parseDouble(input.nextLine()); //use this to get double input from user
}
catch(NumberFormatException e){
//warn user of wrong input
break outer;
}
correctAnswer = 1.0 * (c - b) / a;
if (userAnswer == correctAnswer)
{
System.out.println("Correct!");
numCorrect =+ 1;
}
else
{
System.out.println("Sorry, correct answer is " + correctAnswer);
}
}//end for loop
System.out.println("You got " + numCorrect + " out of ten.");
System.out.println("\nWant to do 10 more questions? <y/n>");
if(input.nextLine().equalsIgnoreCase("y")){
continue outer; //if user wants to continue
}
else{
break outer; //if user does not want to continue, break out of outer do-while loop
}
}
while(true);

Guessing number using lower,higher,correct options in java

I'm trying to write a java code in java that has following output.
---JGRASP exez: java Guess
Is the number 50? H
Ia the number 75? L
Is the number 62? L
Is the number 56? L
Is the number 53? L
Is the number 51? C
It took me 6 guesses!
---JGRASP: operation complete.
As you see it always cuts range in half.I spent hours trying to figure it out without results.I would really appreciate if you could at least give a hint.Here's my unsuccessful attempt to write the code.
import java.util.Scanner;
public class GuessNumber
{
public static void main(String[]args)
{
int num1 = 0,num2 = 100,guesses = 0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
System.out.print("Is the number " + <?> + "? "); //have no idea
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guessses++;
}
else if(answer.equalsIgnoreCase("H")){
? = (num1 + num2) / 2; //lost here
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
? = (num1 + num2) / 2; //lost here
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
}
public static void main(String[]args)
{
Random randomNumber = new Random();
int num1 = 0,num2 = 100,guesses = 0, guess=0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
guess=randomNumber.nextInt(num2-num1) + num1;
System.out.print("Is the number " + guess + "? ");
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guessses++;
}
else if(answer.equalsIgnoreCase("H")){
num1 = guess;
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
num2 = guess;
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
Try this, what it does is that, while the answer is not correct, It will take in num1(the min value for the guess) and num2(the max value for the guess) and find their average. If the number is higher than the latest guess, we set the lower bound to the latest guess, if it's lower, we set the upper bound to the latest guess.
import java.util.Scanner;
public class GuessNumber{
public static void main(String[]args)
{
int num1 = 0,num2 = 101,guesses = 0, guess=0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
guess=(num1+num2) /2 > 0? (num1+num2) /2:1;
System.out.print("Is the number " + guess + "? ");
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guesses++;
}
else if(answer.equalsIgnoreCase("H")){
num1 = guess;
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
num2 = guess;
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
}

Categories