In this java Method, the point is for scanner to receive an int between the min and the max values. If an int is received that is outside those bounds, the program correctly outputs "Invalid input". However if something like "g" or "h" or something other than an int is entered, an endless loop is created.
I tried to reinitialize Scanner in multiple locations in the code but it looks like when something other than an int is entered from a System.in, it just flies right by scanner again and keeps the loop going. Any Thoughts
public static int promptInt(int min, int max) {
while (false != true) {
int b = 0;
Scanner scnr = new Scanner(System.in);
System.out.print("Choose a value between " + min + " and " + max + ": ");
if (scnr.hasNext()) {
if (scnr.hasNextInt()) {
b = scnr.nextInt();
if (b <= max) {
return b;
} else {
System.out.println("Invalid Value");
}
}
else if (scnr.hasNextInt() == false) {
System.out.println("Not an Int");
}
}
}
}
As per some comments above, a scnr.next() was needed otherwise it was continuing to check the first scanner that was initialized. Here is the revised code which now functions.
public static int promptInt(int min, int max) {
Scanner scnr = new Scanner(System.in);
while (false != true) {
int b = 0;
System.out.print("Choose a number between " + min + " and " + max + ": ");
if (scnr.hasNext()) {
if (scnr.hasNextInt() == false) {
System.out.println("Invalid value.");
//the scnr.next was needed here
scnr.next();
}
else {
b = scnr.nextInt();
if (b <= max) {
return b;
} else {
System.out.println("Invalid value.");
}
}
}
}
}
Related
Im trying to make this program work but im getting the error that it cant find the variable min and max in the system.out.print statement in main method. I guess it is because main doesnt know what those variables are since the MinMax destroys those variables once its ran. But how can I transfer the results over from my MinMax method so that results will be printed in system.out.print in main method statement?
class MethodMinMaxWithUnlimitedValues {
public static void main(String[]args) {
Scanner console = new Scanner (System.in);
int value;
char choice;
do{
System.out.print ( " enter value " );
value = console.nextInt();
isMinMax(value);
System.out.print ("enter more numbers? (y/n) ");
choice = console.next().charAt(0);
}
while (choice == 'y' || choice == 'Y');
System.out.print("min value is = " + min + " max value is = " + max);
}
public static void isMinMax (int n) {
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
if (n > max) {
max = n;
} else if (n < min) {
min = n;
}
}
}
Make them static and global
import java.util.Scanner;
class MethodMinMaxWithUnlimitedValues {
static int min = Integer.MIN_VALUE;
static int max = Integer.MAX_VALUE;
public static void main(String[]args) {
Scanner console = new Scanner (System.in);
int value;
char choice;
do{
System.out.print ( " enter value " );
value = console.nextInt();
isMinMax(value);
System.out.print ("enter more numbers? (y/n) ");
choice = console.next().charAt(0);
}
while (choice == 'y' || choice == 'Y');
System.out.print("min value is = " + min + " max value is = " + max);
}
public static void isMinMax (int n) {
if (n > max) {
max = n;
} else if (n < min) {
min = n;
}
}
}
NOTE: that can have side effects
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!
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;
}
}
I'm new to Java so forgive me. I'm writing a small little Guessing Game program.
import java.util.Scanner;
public class GuessingGame {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int menuOption;
// Main Screen //
System.out.println("Guessing Game");
System.out.println("---------------------");
System.out.println("1.) Play Game");
System.out.println("2). Exit");
System.out.println();
while (true) {
System.out.print("Please select a menu option: ");
menuOption = userInput.nextInt();
if (menuOption == 2) {
System.out.println("Exiting the game. Thanks for playing!");
break;
} else if (menuOption == 1) {
System.out.println("Let's start the game!");
getRandomRange();
} else {
System.out.println("Sorry, that's not a valid option. Please try again.");
continue;
}
}
}
/**
* Determine the range of numbers to work with
*/
public static void getRandomRange() {
int min;
int max;
System.out.print("Choose a minimum number: ");
min = userInput.nextInt();
System.out.print("Choose a maximum value: ");
max = userInput.nextInt();
getRandomNumber(min, max);
}
public static void getRandomNumber(int min, int max) {
int randomNumber = (int) (Math.random() * (max - min + 1)) + min;
getAGuess(min, max, randomNumber);
}
public static void getAGuess(int min, int max, int randomNumber) {
int guess;
while (true) {
System.out.print("Guess a number between " + min + " and " + (max) + ": ");
guess = userInput.nextInt();
if (guess == randomNumber) {
System.out.println("Correct! The random number is: " + randomNumber);
break;
}
}
}
}
When I prompt the user to guess a number and the number is incorrect, I want to be able to flush immediately flush the input stream and enter another guess on the same line.
For example:
Guess a number between 0 and 5: I enter my guesses here on this one line only.
I could take the print out of the loop but in that case, if I enter an inccorect number, the cursor jumps to the next line.
Hope this makes sense. Thanks!
If your goal is only to clear the console, then you could do:
Runtime.getRuntime().exec("cls");
Or if you are on Linux or OS X:
Runtime.getRuntime().exec("clear");
Now if you add previous line that you wanted to keep, you will need to keep then in an Array and reprint after each clear.
This won't work in IDE's.
If you want a more system-independent way, there is a library named JLine (GitHub), which is designed for a better console usage. It actually contains a method clearScreen.
You could also do:
System.out.print("\033[H\033[2J");
This will clear the screen and return the cursor to the first row.
A quick and dirty solution...
public class Main {
public static final void main(String[] data) {
Scanner userInput = new Scanner(System.in);
int min = 0;
int max = 10;
int randomNumber = (int) ((Math.random() * max) + (min + 1));
while (true) {
System.out.print("Guess a number between " + min + " and " + max + ": ");
int guess = userInput.nextInt();
if (guess == randomNumber) {
System.out.println("Correct! The random number is: " + randomNumber);
break;
} else {
for (int i = 0 ; i < 25; i++) {
System.out.println();
}
}
}
}
}
here is the Menu class
import java.util.Scanner;
public class Menu {
private String[] menu_options;
public Menu(String[] menu_options) {
this.menu_options = menu_options;
}
public int getUserInput() {
int i = 1;
for (String s : this.menu_options) {
System.out.println(i + ". " + s);
i++;
}
int selection = getint_input(menu_options.length);
return (selection);
}
private int getint_input(int max) {
boolean run = true;
int selection = 0;
while (run) {
System.out.print("Select an option: ");
Scanner in = new Scanner(System.in);
if (in.hasNextInt()) {
int value = in.nextInt();
if(value>=1 || value<=max){
selection = value; //fixed this now working
run = false;
}
} else {
System.out
.print("Invalid input. Please enter a integer between 1 and "
+ max + ": ");
}
}
return selection;
}
}
and here is the menudriver i was using
public class Menutester {
public static void main(String[] args) {
String[] menuitems = new String[2];
menuitems[0] = "option one";
menuitems[1] = "option two";
Menu tm = new Menu(menuitems);
int choice = tm.getUserInput();
System.out.println("Got input");
}
}
the first time i input something it dosn't regester at all and when i try to debug it in eclipse it gives me the error FileNotFoundException(Throwable).(String) line: 195 on the first input.
this is what it returns
option one
option two
Select an option: 1(i entered this and pressed enter)
1(same here only it regestered the input)
Got input
nextInt reads the input and removes it from the buffer. You can't call it like that without storing the value.
Call it once, store the value, and then do all the checks needed.
Change this:
if (in.hasNextInt() && in.nextInt() >= 1 || in.nextInt() <= max) {
selection = in.nextInt();
//...
for this:
if(in.hasNextInt()) {
int selection = in.nextInt();
if(selection >= 1 || selection <= max) {
run = false;
}
}
replace:
if (in.hasNextInt() && in.nextInt() >= 1 || in.nextInt() <= max) {
selection = in.nextInt();
run = false;
System.out.println(run);
}
as:
int input = in.nextInt();
if (input >= 1 || input <= max) {
selection = in.nextInt();
run = false;
System.out.println(run);
}
and try it again.