I wasn't sure how to give a title for this problem, but basically this is part of my blackjack program. Also, since I did not know how to title this, I wasn't sure how to look it up, which is why I am asking here. So I am saying that when the user enters either 1 or 11 for the ace value, if they enter something other than 1 or 11, it asks the user again to put in 1 or 11. In my program everything works fine except when the user enters 1, then it just asks the question again. The program should only asks again if the input is not equal to 1 or 11. Here is my code as I made sure it always gives an ace for testing purposes:
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1=="A"){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
int player_ace_selection=input_var.nextInt();
if ((1|11)!=(player_ace_selection)){
System.out.println("Please enter a 1 or 11: ");
int new_selection=input_var.nextInt();
total=total + new_selection;
}
else {
total=total + player_ace_selection;
}
}
System.out.println(total);
Thanks in advance.
The expression (1|11) uses binary OR, which produces 11:
11 = 01001
1 = 00001
(11|1) = 01001
Hence, the comparison is the same as 11!=player_ace_selection
You should change the code to use logical OR, i.e.
if (1!=player_ace_selection && 11!=player_ace_selection) {
...
}
In addition, you need to fix card1 == "A" comparison for card1.equals("A")
Instead of an If statement, try a while loop. A while loop ensures that your program waits for your user to pick the right answer. You also made a mistake with your logical operations. The correct way to use "OR" in this context is to compare your user input to both '1' and '11' separately using '||'.
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1.equals("A")){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
int player_ace_selection=input_var.nextInt();
while(player_ace_selection != 1 && player_ace_selection != 11){
System.out.println("Do you want a 1 or 11 for the Ace?: ");
player_ace_selection = input_var.nextInt();
}
total += player_ace_selection;
}
System.out.println(total);
There are some problems in your code, please consider this example and compare it with yours.
String card1="A";
int total=0;
Scanner input_var=new Scanner(System.in);
if (card1.equals("A")){ // compare the content not the reference (==)
System.out.println("Do you want a 1 or 11 for the Ace?: ");
try{ // wrap with try-catch block
int player_ace_selection = Integer.parseInt(input_var.nextLine()); //read the entire line and parse the input
if ((player_ace_selection!=1)&&(player_ace_selection!=11)){
System.out.println("Please enter a 1 or 11: ");
try{
int new_selection = Integer.parseInt(input_var.nextLine()); //again read the entire line and parse the input
total=total + new_selection;
}catch(NumberFormatException e){
// do something to catch the error
}
}
else {
total=total + player_ace_selection;
}
}catch(NumberFormatException e){
// do something to catch the error
}
System.out.println(total);
}
Related
I'm doing a basic java tutorial that is basically a mad libs program. The idea came up in the tutorial to try making sure a user is at least 13, but the example hard coded the age into the program. I wanted to try getting the age from the user, but at this point, my code gives me an error because a "string cannot be converted to an integer." Looking at my code, I don't see why it's giving me this error. Here is what I used:
int age = console.readLine("Enter your age: ");
if (age < 13) {
//enter exit code
console.printf("Sorry but you must be at least 13 to use this program.\n");
System.exit(0);
}
I have looked for other answers, but I didn't see any that I could discern from the specific problems they were trying to fix.
You should use
try{
int age = Integer.parseInt(console.readLine("Enter your age: "));
// do stuff
} catch (NumberFormatException e) {
// User did not enter a number
}
Java doesn't cast between the two automatically. The above method however will throw an exception when you don't enter a number which you will have to handle
You can use
Scanner input = new Scanner(System.in);
int Age = input.nextInt();
input.nextLine();
Okay, I'm not sure if it's cool to answer your own question. I managed to get this to work, so in case someone else encounters the same problem. Here is the code that I used:
String ageAsString = console.readLine("Enter your age: ");
int age = Integer.parseInt(ageAsString);
if (age < 13) {
//enter exit code
console.printf("Sorry but you must be at least 13 to use this program.\n");
System.exit(0);
}
Im trying to write code for a school project, the main objective is to get the average gpa of a students semester depending on how many Subjects and Units you input, however, if I try typing 0, the program goes into an infinite try-catch loop with "You can only type positive numbers" Im using valueOf() because I want the user to be able to type "salir" which means exit, to exit the program.
Scanner LeerTeclado = new Scanner(System.in);
int n=0, i=0, suma=0, promedio=0;
String materia, cadena;
//---------------------------------------------------------------------------
out.println("---------------------------");
out.println("-- School Grades --");
out.println("---------------------------");
//---------------------------------------------------------------------------
out.println("\nType 'salir' to terminate the program");
out.println("-----------------------------------------");
out.print("Type the number of subjects to grade: ");
cadena = LeerTeclado.nextLine();
int z = 0;
if("salir".equals(cadena)){
System.exit(0);
}
if("Salir".equals(cadena)){
System.exit(0);
}
///////////////////////////////////////////////////////////////////
do{
try{
z = Integer.valueOf(cadena);
if(z <= 0){
out.println("...............................................");
out.println(" You can only type positive numbers ");
out.println("...............................................");
out.println("\n");
continue;
}
break;
}catch(NumberFormatException ex){
out.println("\n*You have entered non-numeric characters*");
out.print("\nPlease type the number of subjects again: ");
LeerTeclado.nextLine();
}
}while(true);
In the try block, before you write
continue;
but after "You can only type positive numbers," you should prompt the User for another line of input, and wait for the user to enter that.
The "continue" statement skips to the end of the loop and causes the 2nd part of the loop not to run. That is why the loop is running indefinitely.
Move reading cadena into the try block
int z = 0;
do {
try {
cadena = LeerTeclado.nextLine(); // <-- re-read
if ("salir".equalsIgnoreCase(cadena)) { // <-- you might test once.
System.exit(0);
}
// if ("Salir".equals(cadena)) {
// System.exit(0);
// }
z = Integer.valueOf(cadena); // <-- or this loops forever.
Alberto,
There are a few things that need to be changed in order to get this program to work the way you wish. Since you are a student I'm not going to solve it for you. I will answer your question, however.
When you type zero on the command line your program will execute from the z<=0 test down to the continue statement. The continue statement tells the code to ignore everything after and return to the beginning of the loop so it goes back to the beginning of the do statement and repeats. You need some way to end the loop.
May I suggest writing the program a little at a time and test as you go along. That is, write the part that's not in the loop. Once that works write a little something in the loop and test. Keep doing this until the programs works the way you want it to.
Good Luck
do{
try{
z = Integer.valueOf(cadena);
if(z <= 0){
out.println("...............................................");
out.println(" You can only type positive numbers ");
out.println("...............................................");
out.println("\n");
continue;
}
You want to use break
if(z <= 0){
System.out.println("...............................................");
System.out.println(" You can only type positive numbers ");
System.out.println("...............................................");
System.out.println("\n");
break;
}
continue just hops to the top of the if and keeps at it, same thing.
I am writing a small program (student, though not an assignment for class...but rather a play on a previous assignment). Previously for class, while learning do/while loops, I wrote a program that prompted a user to input integers. When the user typed in 0, it served to get out of the loop, and then outputted the sum of the squares of all the integers typed.
Example output (double spaced for line breaks):
Type an integer: 3
Type an integer: 0
The sum of the squares is 9
My goal now is to take it a step farther. As written, the program crashes if the user types in anything other than an integer. I have been playing around trying to find ways to allow the user to type in other forms of values, without having it crash. In referencing the code below (which is the program at the moment that does crash at any value sans ints), I tried putting in variations of if statements with the console.hasNextInt() method. Yet my attempts in this would cause an error that number in the do/while test may not have been referenced.
Can anyone offer me any tips? It would be appreciated.
public static void userInterface() {
Scanner console = new Scanner(System.in);
int number;
int numberSquared;
int squaredOutput = 0;
do {
System.out.print("Type an integer (0 to quit): ");
number = console.nextInt();
if (number > 0 || number < 0) {
numberSquared = number * number;
squaredOutput += numberSquared;
}
} while (number != 0);
System.out.println("The sum of the squares is " + squaredOutput);
}
The problem is that you are using console.nextInt(); which only takes the next int.
You can use: console.nextLine();.
It would allow your program to accept a string and you can parse it into an Int when necessary:
try {
number=Integer.parseInt(console.nextLine());
} catch(NumberFormatException e) {
System.out.println("Please input an Integer");
}
Just use this function
public static int next(String message) {
while (true) {
System.out.println(message);
try {
return new Scanner(System.in).nextInt();
} catch (Exception e) {
System.out.println("Invalid input.");
}
}
}
There is problem with your code. When you use console.nextInt() and the scanner try to parse every string as Integer. Better solution is to use console.nextLine() and by your own parse it to your number and catch exception that might be thrown if that string is not parsable as any number that you want.
simply it might look like this.
String yourValue = console.nextLine();
try{
int value = Integer.parseInt(yourValue);
}catch(NumberFormatException e){
System.out.println("watch out this value is unparsable!");
}
I'm trying to wrap my head around exceptions and the problem I'm running into is that I'm being required to create a program that asks for user input for a number 9-99. This number must be error-checked using 3 different exceptions.
e1: number is outside of the range (200)
e2: number is of a data type other than integer (double)
e3: input is another data type other than number (char)
I have tried to create patterns in my if structure to make all three work, however I can't get it to differentiate between e2 and e3. It will always default to e2. This is what I have with only two exceptions, but I would greatly appreciate help with figuring out how to implement the third. Thank you.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean tryAgain = true;
do {
try {
System.out.println("Please enter an integer between 9 and 99: ");
int inInt = input.nextInt();
if (inInt >= 9 && inInt <= 99){
System.out.println("Thank you. Initialization completed.");
tryAgain = false;
}
else if (inInt < 9 || inInt > 99){
throw new NumberFormatException("Integer is out of range.");
}
}
catch (NumberFormatException e1) { // Range check
System.out.println("* The number you entered is not between 9 and 99. Try again.");
System.out.println();
input.nextLine();
}
catch (InputMismatchException e2) { // Something other than a number
System.out.println("* You did not enter an integer. Try again.");
System.out.println();
input.nextLine();
}
} while(tryAgain);
}
}
Here is the output I get right now:
Please enter an integer between 9 and 99:
2
The number you entered is not between 9 and 99. Try again.
Please enter an integer between 9 and 99:
f
You did not enter an integer. Try again.
Please enter an integer between 9 and 99:
88
Thank you. Initialization completed.
https://www.ideone.com/ZiOpGH
In catch (InputMismatchException e2), test to see if input.hasNextDouble() (or input.hasNextFloat() ? Not sure which one is more general...) is true. If it is, then you can distinguish between the case 'user entered a double' and 'user entered a non numeric type'
If you've got to detect three circumstances, you need to have three sets of logic.
Check if the entered characters are a valid numeric value.
Check that the entered number is an integer.
Check that the entered number falls between the low and high bounds.
And you pretty much have to check them in that order.
Scanner conveniently has the hasXXX methods to see whether the characters about to be read match a given pattern.
I am writing a program that accepts two ints within the program using nextInt(); and have it wrapped in a try catch block to stop bad inputs such as doubles or chars.
When multiple wrong inputs are entered the loop repeats that same number of times. I assume this is because my scan.next() has to loop around enough times to catch the bad inputs w/o error. Is there a way to know this number on the first run through to make a loop to run next in that many times?
In the output the
if(cont == 'N') System.out.print("\nPlease re-enter\n\t:"); will output and mirror the amount of times a mismatched input was written. That is, if I input 3 3.3 it will repeat one extra time, if input s 3.3 2.5 it will repeat three extra times.
I tried putting a loop around scan.next() to default it to ten times, but was overboard and I had to input an extra 8 characters before it started reading again. Maybe a while loop but what would its condition be, I tried while(scan.next() != null){} but that condition never stopped.
//input error checking
char cont = 'Y';
do{
if(cont == 'N')
System.out.print("\nPlease re-enter\n\t:");
cont = 'Y';
/* to stop the accidential typing of things other
* than integers from being accepted
*/
try{
n1 = scan.nextInt();
n2 = scan.nextInt();
}catch(Exception e){
cont = 'N'; //bad input repeat loop
scan.next();//stops infinite loop by requesting Scanner try again
}
} while(cont == 'N');//do loop while told N for continue
Not sure what you want your code to do. From reading what you have posted I assume you want the user to input 2 ints and if he/she doesn't you want to prompt him/her to re-enter something until he/she inputs 2 ints.
If this is the case I would just add
scan = new Scanner(br.readLine());
after this if statement:
if(cont == 'N')
{System.out.print("\nPlease re-enter\n\t:");}
This will solve your looping issue
First try :
change the line in the exception catch from
scan.next();
to
while(scan.hasNext()){
scan.next();
}
You can try to do the following in your catch block:
while(scan.hasNext())
scan.next();
make it a method and do it with that method.
sth like this:
// do it until getting two Integers
boolean isItInteger = false;
while (isItInteger == false) {
isItInteger = getInt();
}
.
.
.
// your method for getting two Integers
public static boolean getInt() {
try {
Scanner sc = new Scanner(System.in);
n1 = sc.nextInt();
n2 = sc.nextInt();
} catch (Exception e) {
System.out.println("Please re-enter");
return false;
}
return true;
}