is it possible in Java to check if a certain input is between a certain range and also an integer?
I have written the following code:
public void getBetAmountFromUser() {
//Get Amount of Bet
int x = 0;
System.out.println("Your current pot is: " + potAmount);
System.out.println("Enter your bet amount: ");
x = input.nextInt();
//Error message if bet is larger than pot and less than 0
while (x>potAmount || x<0 || !(input.hasNextInt())){
System.out.println("Error - cannot bet less than 0 or more than " + potAmount + "..Enter your bet amount: ");
x = input.nextInt();
}
//Bet should be less than or equal to pot if 0 user quit
if (x > 0 && x <= potAmount) {
betAmount = x;
potAmount = potAmount - betAmount;
} else if (x == 0) {
System.out.println("You end the game with pot " + potAmount);
System.exit(0);
}
}
The following loop did not work on validating Integer
while (x>potAmount || x<0 || !(input.hasNextInt())){
System.out.println("Error - cannot bet less than 0 or more than " + potAmount + "..Enter your bet amount: ");
x = input.nextInt();
}
You can try to use String in lieu of int. Then, you can go ahead with again int using Integer.parseInt(x) because it's already been verified as being valid integer after do-while
String x;
String regex = "[0-9]+"; // to check the string only is made up of digits
int potAmount = 10;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input an integer");
x = input.next();
} while (!x.matches(regex) || Integer.parseInt(x) > potAmount || Integer.parseInt(x) < 0);
int validBet = Integer.parseInt(x);
/* .
.
. *\
Related
My code has to guess the hidden number from 0 to 100 in 7 attempts. And every time I need to call the same operations again. How can I move these operations into a separate method and call them from there?
public class Main {
public static void main(String[] args) throws IOException {
int min = 0;
int max = 100;
int midrange = Math.round((min + max)/2);
String strInput = "";
Scanner scan = new Scanner(System.in);
while (!strInput.equals("1")){
System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
strInput = scan.nextLine();
}
while (!strInput.equals("+") && !strInput.equals("-") && !strInput.equals("=")){
System.out.println("Is this number greater than, less than or equal to " + midrange + "? " +
"Enter '+', if it's greater, '-' if it's less and '=' if it's equal:");
strInput = scan.nextLine();
}
if (strInput.equals("=")) System.out.println("Great! Thank you for the game.");
else if (strInput.equals("+")){
// reduce the range
min = midrange;
// find a new midrange
midrange = Math.round((min + max)/2);
} else if (strInput.equals("-")){
max = midrange;
midrange = Math.round((min + max)/2);
}
strInput = "";
while (!strInput.equals("+") && !strInput.equals("-") && !strInput.equals("=")){
System.out.println("Is this number greater than, less than or equal to " + midrange + "? ");
strInput = scan.nextLine();
}
// ... and so on until the correct number is found.
}
}
You don't need multiple while loops. Just check for equality and put your if-else-block into the while loop. If you guessed the number correct just break out of the loop.
public static void main(String[] args) throws IOException {
int min = 0;
int max = 100;
int midrange = Math.round((min + max) / 2);
String strInput = "";
Scanner scan = new Scanner(System.in);
System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
strInput = scan.nextLine();
while (!strInput.equals("=")) {
System.out.println("Is this number greater than, less than or equal to " + midrange + "? " +
"Enter '+', if it's greater, '-' if it's less and '=' if it's equal:");
strInput = scan.nextLine();
if (strInput.equals("=")) {
System.out.println("Great! Thank you for the game.");
break;
} else if (strInput.equals("+")) {
min = midrange;
midrange = Math.round((min + max) / 2);
} else if (strInput.equals("-")) {
max = midrange;
midrange = Math.round((min + max) / 2);
}
}
}
I have a program that prompts a user for integers until they type a value to continue the program onto the next step. How would I increment a variable called count every time the user inputs an integer? I'm using count++ to increment the count amount by the way, I just don't know how to make it go up when the user puts in data.
Code so far
//variables
int num, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
//loop
do {
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
high = num;
low = num;
//higher or lower
if(count > 0 && num > high)
{
high = num;
}
else if(count > 0 && num < low)
{
low = num;
}
else
{
System.out.println("You did not enter any numbers.");
}
} while (num != -99);
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
It's simple. Just put count++ inside the while loop as follows,
// variables
int num, count = 0, high, low;
Scanner userInput = new Scanner(System.in);
// loop
do {
System.out.print("Enter an integer, or -99 to quit: --> ");
num = userInput.nextInt();
count++; // here it goes
high = num;
low = num;
// higher or lower
if(count > 0 && num > high)
{
high = num;
}
else if(count > 0 && num < low)
{
low = num;
}
else
{
System.out.println("You did not enter any numbers.");
}
} while (num != -99);
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
You can put count++; anywhere in your do loop.
I understand why you're using it but why use the counter at all?
The code below uses a different technique to acquire integers from the User. It also ensures that the supplied number is indeed a integer that falls within the Integer.MIN_VALUE and Integer.MAX_VALUE range:
Scanner userInput = new Scanner(System.in);
String ls = System.lineSeparator();
int high = 0;
int low = Integer.MAX_VALUE;
int num;
String input = "";
while(input.equals("")) {
System.out.print("Enter an integer, (q to quit): --> ");
input = userInput.nextLine().toLowerCase();
if (input.equals("q")) {
if (low == Integer.MAX_VALUE) {
low = 0;
}
break;
}
if (!input.matches("^-?\\d+$")) {
System.err.println("Invalid Entry (" + input + ")! "
+ "You must supply an Integer (int) value!" + ls);
input = "";
continue;
}
boolean invalidInteger = false;
long tmpVal=0;
try {
tmpVal = Long.parseLong(input);
} catch(NumberFormatException ex) {
invalidInteger = true;
}
if (invalidInteger || tmpVal < Integer.MIN_VALUE || tmpVal > Integer.MAX_VALUE) {
System.err.println("Invalid Entry (" + input + ")! " + ls
+ "Number too large (Minimum Allowable: " + Integer.MIN_VALUE
+ " Maximum Allowable: " + Integer.MAX_VALUE + ")!" + ls
+ "You must supply an Integer (int) value!" + ls);
input = "";
continue;
}
num = Integer.parseInt(input);
if (num > high) {
high = num;
}
if (num < low) {
low = num;
}
input = "";
}
System.out.println("Largest integer entered: " + high);
System.out.println("Smallest integer entered: " + low);
If you want to keep track of how many entries the User made then you can still apply a counter if you like.
I am creating a program that will determine and print the number of odd, even, and zero digits in an integer from the keyboard. I have tried a few different ways and have gotten the same result with each. I cannot get java to recognize 0 as 0, but only as an even number. Ex. 1005 will give 2 Odds and 2 Evens.
public static void main(String[] args) {
int odd = 0;
int even = 0;
int zero = 0;
int input;
Scanner scan = new Scanner (System.in);
System.out.println("Input an integer please: ");
input = scan.nextInt();
System.out.println("Your number is: " + input);
String x = Integer.toString(input);
for (input = 0; input < x.length(); input++){
char a = x.charAt(input);
System.out.println(a);
Character.getNumericValue(a);
if (a==0){
System.out.println ("+1 Zero");
zero++;
}
else if (a%2 == 0 && a>1){
System.out.println("+1 Even");
even++;
}
else {
System.out.println("+1 Odd");
odd++;
}
}
System.out.println("There are " + odd + " odd numbers!");
System.out.println("There are " + even + " even numbers!");
System.out.println("There are " + zero + " zero numbers!");
}
you haven't assigned Character.getNumericValue(a) to int value .
char a = x.charAt(input);
System.out.println(a);
int y= Character.getNumericValue(a);
if (y==0){
System.out.println ("+1 Zero");
zero++;
}
else if (y%2 == 0 && y>1){
System.out.println("+1 Even");
even++;
}
else {
System.out.println("+1 Odd");
odd++;
}
the Character.getNumericValue(a); method returns an int. It does not implicitly change the parameter (the character variable 'a' in this case).
Thus, you should compare the return value of the getNumericValue method and not the original character.
int a;
int b;
int c;
Scanner input = new Scanner (System.in);
//how to read three integers with white space delimiter
System.out.print("Enter the 3 edges of the triangle to be calculated: ");
int numbers = input.nextInt();
//then turn 3 integers into boolean form
//this is only the algorithm
Boolean isTriangle = ((a+b>c) && (b+c > a) && (c+a > b));
System.out.print(isTriangle);
else
System.out.print(isTriangle);
So instead of entering 3 integers in a separate line or in a newline i want them all to be in the same line just separated with whitespace. Do I need to change standard input as string then just parse it after for the boolean part? I am confuse because after entering the integers I don't know where to store them to use for the boolean part.
Edited part:
public static void main(String[] args){
int x;
int y;
int z;
Scanner input = new Scanner(System.in);
System.out.println("Enter three edges: ");
x = input.nextInt();
y = input.nextInt();
z = input.nextInt();
boolean isTriangle = ((x+y>z) && (y+z > x) && (z+x > y));
if (isTriangle){
System.out.print("Can edges " + x + ", " + y + ", " + z + " form a triangle"+ isTriangle);
}
else {
System.out.print("Can edges " + x + ", " + y + ", " + z + " form a triangle"+ isTriangle);
}
}
why is it that when i call x y and z in system.out they don't show the entered input but when i only put the isTriangle on system.out it gives me output
Just call the nextInt three times.
System.out.print("Enter the 3 edges of the triangle to be calculated: ");
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
With input
5 5 5
It prints true.
You'll have to check wether there are three numbers available (use input.hasNextInt() before input.nextInt()):
System.out.print("Enter the 3 edges of the triangle to be calculated: ");
if(input.hasNextInt()) {
a = input.nextInt();
} else {
//handle it, you don't have ints!
}
if(input.hasNextInt()) {
b = input.nextInt();
} else {
//handle it, you have just one int!
}
if(input.hasNextInt()) {
c = input.nextInt();
} else {
//handle it, you have just two ints!
}
DEMO
It's better to use below.
String values=scanner.next();//if your input 5 5 5
String numinString[]=values.split(" ");
int a=Integer.parseInt(numinString[0]);//a=5
int b=Integer.parseInt(numinString[1]);//b=5
int c=Integer.parseInt(numinString[2]);//c=5
You can do it this way:
int a;
int b;
int c;
Scanner input = new Scanner(System.in);
// how to read three integers with white space delimiter
System.out.print("Enter the 3 edges of the triangle to be calculated: ");
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
// then turn 3 integers into boolean form
// this is only the algorithm
Boolean isTriangle = ((a + b > c) && (b + c > a) && (c + a > b));
if (isTriangle)
System.out.print(isTriangle);
else
System.out.print(isTriangle);
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.