I need a Java Scanner 'reset' on invalid character fix - java

I am a new human learning to code!
I had a problem with my Scanner, which is that I need it to 'reset' on an invalid character.
My code:
public class Lemonade {
static int m = 150;
private static Scanner scan;
public static void main(String[] args) {
int day = 1;
for(int gameover = m; gameover > 0; day++) {
int Random = (int) (Math.random() * 100);
if(Random <= 25) {
System.out.println("Great Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 50) {
System.out.println("Good Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 75) {
System.out.println("Bad Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 100) {
System.out.println("Awful Chance!");
System.out.println("--------------------------------");
}
int count = 0;
int none = 0;
scan = new Scanner(System.in);
System.out.println("Enter a number between 0 and " + m + "!");
count = scan.nextInt();
if(count >= none && count <= m) {
System.out.println("You entered " + count + "!");
System.out.println("--------------------------------");
day = day + 1;
m = m - count;
System.out.println("Day " + day);
}
else {
System.out.println("Enter a number between 0 and " + m + ".");
count = scan.nextInt();
}
}
}
}
Now is my question how to get this to 'reset' on an invalid character like 'f', as Scanner only accepts numbers.
Thanks for the help!

If I understand you correctly then this is something you're looking for,
InputMismatchException will thrown if user enters invaild characters instead of int. You may use looping until the user enters an integer
import java.util.Scanner;
import java.util.InputMismatchException;
class Example
{
public static void main(String args[])
{
boolean isProcessed = false;
Scanner input = new Scanner(System.in);
int value = 0;
while(!isProcessed)
{
try
{
value = input.nextInt();
//example we will now check for the range 0 - 150
if(value < 0 || value > 150) {
System.out.println("The value entered is either greater than 150 or may be lesser than 0");
}
else isProcessed = true; // If everything is ok, Then stop the loop
}
catch(InputMismatchException e)
{
System.out.print(e);
input.next();
}
}
}
}
If this is not you're looking for please let me know!

Related

How to display error message instead of java exception?

I am trying to make a Guessing Game for a Java assignment, I have everything I need except exception handling, you see I'm trying to make it display an error message instead of displaying Exception in thread "main" java.util.InputMismatchException when someone tries to enter a numerical number in alphabetical form. The code I have is followed.
(I know I need a try and catch but I don't know what to put exactly.)
package guessNumber;
import java.util.Scanner;
public class GuessNumberApp {
public static void main(String[] args) {
final int LIMIT = 10;
System.out.println("Guess the number!");
System.out.println("I'm thinking of a number from 1 to " + LIMIT);
System.out.println();
// get a random number between 1 and the limit
double d = Math.random() * LIMIT; // d is >= 0.0 and < limit
int number = (int) d; // convert double to int
number++; // int is >= 1 and <= limit
// prepare to read input from the user
Scanner sc = new Scanner(System.in);
int count = 1;
while (true) {
int guess = sc.nextInt();
System.out.println("You guessed: " + guess);
if (guess < 1 || guess > LIMIT) {
System.out.println("Your Guess is Invalid.");
continue;
}
if (guess < number) {
System.out.println("Too Low.");
} else if (guess > number) {
System.out.println("Too High.");
} else {
System.out.println("You guessed it in " + count + " tries.\n");
break;
}
count++;
}
System.out.println("Bye!");
}
}
try something like that:
try {
int guess = sc.nextInt();
} catch(InputMismatchException e) {
System.out.println("some nice error message");
continue;
}
This would replace
int guess = sc.nextInt();

Adding the "Play Again?" feature on my random number guessing game in Java

I have been stuck on this and can't seem to loop again when user is asked to continue. Would a do-while loop be more appropriate for this type of play again feature? Any help would be appreciated, thanks!
import java.util.Scanner;
import java.util.Random;
public class HiLo
{
public static void main( String[] args )
{
boolean again = true;
while (again == true)
{
int MAX = 100;
int MIN = 1;
int guessCounter = 1;
int outOfRangeCounter = 0;
int userGuess = 0;
Random rand = new Random();
int computerGuess = rand.nextInt(MAX) + MIN;
System.out.printf("Welcome to the game of Hi-Lo...\n\n\n");
System.out.printf("I have chosen a random number for you to guess.\n\n");
Scanner keyboard = new Scanner(System.in);
String repeatAgain;
while (userGuess != computerGuess)
{
System.out.printf("Guess %d: Enter a number between %d and %d: ",guessCounter,MIN,MAX);
userGuess = keyboard.nextInt();
if (userGuess == computerGuess)
{
System.out.printf("%d is correct\n\n",userGuess);
}
else if (userGuess > MAX || userGuess < MIN)
{
System.out.printf("%d is not between %d and %d\n\n",userGuess,MIN,MAX);
outOfRangeCounter++;
}
else if (userGuess > computerGuess)
{
System.out.printf("%d is too high\n\n",userGuess);
MAX = userGuess - 1;
guessCounter++;
}
else if (userGuess < computerGuess)
{
System.out.printf("%d is too low\n\n",userGuess);
MIN = userGuess + 1;
guessCounter++;
}
}
System.out.printf("It took you %d valid guesses to find the number.\n",guessCounter);
System.out.printf("You had %d out of range guesses.\n\n",outOfRangeCounter);
System.out.printf("Do you want to play again? (Y or N): ");
repeatAgain = keyboard.nextLine();
if (repeatAgain.equalsIgnoreCase("Y"))
{
again = true;
}
else
{
again = false;
}
}
}
}
Change repeatAgain = keyboard.nextLine(); with repeatAgain = keyboard.next(); and it should be fixed.
nextLine() skip a line and returns the line that was skipped.
//change
//repeatAgain = keyboard.nextLine();
//to
repeatAgain = keyboard.next();

Multiple of an Integer inside range

I am doing a school project and I kinda got blocked.
I am looking forward building a javascript that asks the user of a number between 1 and 20 and then finds and lists all the multiples of that number inside range 0 and 100.
Here is what it looks like at the moment:
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%100) == 0) {
System.out.println(n1);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
I am obviously bad at math cause I can't get the formula to work.
Thank you in advance!
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%i) == 0) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
All multiples that fall between 0 and 100? That's the kind of thing for-loops are made for. After performing your IO and reading the number n1, change that while loop to the following.
for (int i = n1; i >= 0 && i <= 100; i = i + n1) {
System.out.println(i);
}
In case you aren't familiar with for loops, this basically says, set i to the value of n1, and keep adding n1 to it, printing each value as you go. When it leaves the range of 0..100, it terminates. So for instance, if 8 is entered it goes 8, 16, 24, 32, ..., 80, 88, 96.
If you really want to use a while loop, then try:
int i = n1;
while(i >= 0 && i <= 100) {
System.out.println(i);
i = i + n1;
}
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1*i) <= 100) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
This should work. You were just finding if the number n1 was divisible by 100.

Java classes and calling variables in other classes

I'm still fairly new in java programming and I've gotten some aspects down but the classes within Java are by far giving me the most trouble. What I'm trying to do is make a random number game where the player has to pick a number 1 through 10 and if it's wrong then try again and have the program record how many times they guessed (but not add to the number of guess when a number has been picked previously or if the number that was picked is outside the specified range) I have already worked out the logic code and was trying to make a class specifically for just the logic and a class that is specifically just for the I/O interface. But I'm having one heck of a time. Any input or tips will be very appreciated and I will provide the code that I already have below:
This is the Logic class where I want it to handle all the logic
package guessapp;
import java.util.HashSet;
import java.util.Scanner;
public class GuessLogic {
public static int Logic() {
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
int A;
int guess;
int NumGuess = 1;
do {
guess = keyboard.nextInt();
if (hs.contains(guess)) {
A = 1;
return A;
}
if (guess < 0 || guess > 10) {
A = 2;
return A;
}
if (guess == GuessLogic) {
A = 3;
return A; // this will stop the loop
} else if (guess < GuessLogic) {
NumGuess++;
A = 4;
return A;
} else if (guess > GuessLogic) {
NumGuess++;
A = 5;
return A;
}
hs.add(guess);
} while (true);
}
public static int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}
And this is the class I want to handle all I/O interface
import java.util.HashSet;
import java.util.Scanner;
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
r = GuessLogic.Logic();
w = GuessLogic.getGuess();
int NumGuess;
NumGuess = 2;
System.out.print("Enter a guess: ");
if (r == 1) {
System.out.println("You have already entered this number");
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess);
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess);
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess);
}
}
}
Below is the modified codes. There are some general ideas:
GuessLogic should be used as an instance rather than a static class. Because you need GuessLogic to save the operations and the target number.
The while loop should be coded in main. Because GuessLogic is responsible for logic only.
The elements is Set is unique, so there is no need to count how many different number by yourself.
GuessApp:
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
GuessLogic guessLogic = new GuessLogic();
while(true){
System.out.print("Enter a guess: ");
w = guessLogic.getGuess();
r = guessLogic.Logic();
if (r == 1) {
System.out.println("You have already entered this number");
continue;
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
continue;
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + guessLogic.getNumber());
break;
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + guessLogic.getNumber());
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + guessLogic.getNumber());
}
}
}
}
GuessLogic:
public class GuessLogic {
HashSet<Integer> hs = new HashSet<>();
int number = (int) (Math.random() * 10 + 1);
public int getNumber(){
return hs.size();
}
public int Logic(int guess) {
if (hs.contains(guess)) {
return 1;
}
if (guess < 0 || guess > 10) {
return 2;
}
if (guess == number) {
return 3; // this will stop the loop
} else if (guess < number) {
// just add to the set. The set will guarantee that there is no repetitive item.
hs.add(guess);
return 4;
} else if (guess > number) {
hs.add(guess);
return 5;
}
return -1;
}
public int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}

Guessing Game, with a While loop

i'm currently trying to create a while loop for my program, a Guessing game. I've set it up so the user can create a max value i.e 1-500 and then the user can proceed to guess the number. When the number has been guessed, the User can press 1, to close, anything else to continue running the loop again.
My problem, is that the code gives me an error when trying to continue the loop, no compiling errros
This is my Code:
import java.util.Random;
import java.util.Scanner;
public class Gættespil2
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Indsæt loftets højeste værdi : ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
while (win == false)
{
System.out.println(" Gæt et tal mellem 1 og "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Koldere, gæt igen");
}
else if (guess > TAL) {
System.out.println("Varmere, Gæt igen!!");
}
}
System.out.println(" Tillykke du vandt...endeligt!!! ");
System.out.println(" tallet var" + TAL);
System.out.println(" du brugte " + FORSØG + " forsøg");
System.out.println("Slut spillet? tast 1.");
System.out.println("tryk på hvadsomhelst for at spille videre");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Simple answer. You didn't initialize all the necessary values within your 'keepPlaying' loop before beginning a second round after the player successfully completed the first round. See annotations to your code, below:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Enter a maximum limit: ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
// *** LOOK HERE ***
// Reset the 'win' flag here, otherwise the player receives an
// automatic win on all subsequent rounds following the first
win = false;
while (win == false)
{
System.out.println("Guess the number between one and "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Colder, guess again!");
}
else if (guess > TAL) {
System.out.println("Warmer, guess again!");
}
}
System.out.println("You've found the number!");
System.out.println("The number was: " + TAL + ".");
System.out.println("You guessed " + FORSØG + " times.");
System.out.println("To quit, enter 1.");
System.out.println("Provide any other input to play again.");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Sorry for the translation into English -- I had to make sure I was reading things correctly. You might also want to substitute "higher" and "lower" for "warmer" and "colder." "Warmer" and "colder" tend to suggest a proximity to the correct answer, as opposed to the direction in which that correct answer lies.

Categories