Asking user input for an integer in java - java

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

Related

InputMismatch Avoidance with try-catch [duplicate]

This question already has answers here:
Why not use exceptions as regular flow of control?
(24 answers)
Closed 10 months ago.
To validate for an int input, I've seen the usage of try-catch using the InputMismatch exception. After inputting a string though, I simply get the catch code block played, then my program exits due to mismatch, but instead I want to allow the user to re-enter input. I implemented a boolean correct while loop after searching around but that still didn't do the trick.
int quantity = 0;
boolean correct = true;
while(correct){
try{
System.out.print("Input Quantity you would like to purchase: ");//Get quantity
quantity = input.nextInt();
}catch(InputMismatchException e){
System.out.println("Input must be a number");
input.nextInt();//Get the input as a string
correct = false;
}
System.out.println("Quantity: " + quantity);
}
I previously just used the Scanner's built in hasNextInt, and that works great, but wanted to test out try-catch. I've heard to use try-catch and not to use try-catch. Why would I avoid using it?
Here is the fix, use input.nextLine(); in catch and don't make the correct=false
while(correct){
try{
System.out.print("Input Quantity you would like to purchase: ");//Get quantity
quantity = input.nextInt();
}catch(InputMismatchException e){
System.out.println("Input must be a number");
input.nextLine();
continue;
}
System.out.println("Quantity: " + quantity);
}
But like others pointed out, try not to use Exceptions for general flow. Use it only for tracking unusual exceptions. So, I am discouraging you to use this code. Use, input.hasNextInt() instead

condition inside another in JAVA

let the user get 3 attempts only, after it he get his account suspenedI tried to ask the user to give a final password 3 times if he didn't it will give him that his account suspended and if it right gives him a grating message.
package EE;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
final String password= "Test";
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the password: ");
String pass = sc.next();
for (int i=0; i<2;) {
if (!pass.equals (password))
i++;
System.out.println("Try again! ");
String pass1 = sc.next();
if(pass.equals( password))
System.out.println("Welcome");
String pass2 = sc.next();
if (i == 2)
System.out.println("Sorry, your account is suspened");
}
}}
As Alea commented, you need to use braces { ... } around the blocks in your if statements:
for (int i=0; i<2;) {
if (!pass.equals (password))
i++;
System.out.println("Try again! ");
String pass1 = sc.next();
if(pass.equals( password))
System.out.println("Welcome");
String pass2 = sc.next();
if (i == 2)
System.out.println("Sorry, your account is suspened");
}
actually means this:
for (int i = 0; i < 2; ) {
if (!pass.equals(password)) {
i++;
}
System.out.println("Try again! ");
String pass1 = sc.next();
if (pass.equals(password)) {
System.out.println("Welcome");
}
String pass2 = sc.next();
if (i == 2) {
System.out.println("Sorry, your account is suspened");
}
}
Once we have indented the code correctly and added the braces at the places where the compiler expects them, we can start to see some of the problems.
For example:
When the password is correct, nothing will increment i. That means that i < 2 won't be true, and the loop will keep going around, and around.
You are calling next() twice for each loop iteration.
And so on.
Now I could just rewrite your code for you1. But you won't learn much from that. (You will learn best by writing the code for yourself, making mistakes and finding and correcting them ... yourself!)
Instead I am going to recommend to you to read about the Rubber Duck debugging technique. This may sound like a joke, but it is not. It is an important technique explained in a humorous way. And it is what I was taught as a way debug programs, back when I was 18 years old learning to program2.
The idea behind Rubber Duck debugging is to help you understand how a computer "thinks". Once you can do that, programming gets a lot easier. And this is why I strongly recommend that you do this yourself!
Anyway, once you can visualize what the code is doing wrong, then next step is to work out what it should be doing.
1 - It would be quicker for, for a start!
2 - Though we didn't call it by that name back then. We called it hand execution, and we did it with a pencil and paper. Generally on the back of old computer printouts. Yea, a long time ago. And in those days, we didn't have debuggers or IDEs. It was card punches and a 20 minute wait to get the printout back!

Getting "Exception in thread "main" java.util.InputMismatchException" Followed my guide book to the letter [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
Been looking for about an hour now, do not understand where I'm going wrong.
From what I understand it's Scanner looking for an integer but finding a String instead that is causing the issue?
I'm very new to coding but from what I can make out the issue starts here:
public void inputGrades()
{
Scanner input = new Scanner(System.in);
int grade;
System.out.printf("%s\n%s\n %s\n %s\n",
"Enter the integer grades in the range 0-100.",
"Type the end-of-file indicator to terminate input:",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
while( input.hasNext())
{
grade = input.nextInt();
total += grade;
++gradeCounter;
incrementLetterGradeCounter(grade);
}
}
I'm following one of Paul Deitel's books on my college course and I'm completely stumped!
Any help is much appreciated!
You can use Integer.parseInt() to convert the string to integer. But Does your printf statement stops getting input when you press Ctrl+Z?
I found something that might work for you. Follow those steps (code sample below):
Initialize your grade variable to something (usually 0 or 1):
int grade = 0;
Use next() instead of nextInt() so that you can read any input:
String nextInput = input.next();
Parse your input with Integer.parseInt(), converting your input into a number:
grade = Integer.parseInt(nextInput);
If your user types a String, it will throw an exception and end your program. You may surround your grade parsing with an try/catch. In your case, the exception thrown would be a NumberFormatException:
try {
grade = Integer.parseInt(nextInput);
System.out.println(grade);
} catch (NumberFormatException e) {
System.out.println("Mauvais format de nombre, veuillez recommencer");
}
Profit ! Below is your full method.
Scanner input = new Scanner(System.in);
int grade = 0;
System.out.printf("%s\n%s\n %s\n %s\n",
"Enter the integer grades in the range 0-100.",
"Type the end-of-file indicator to terminate input:",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
while( input.hasNext())
{
String nextInput = input.next();
try {
grade = Integer.parseInt(nextInput);
System.out.println(grade);
} catch (NumberFormatException e) {
System.out.println("Mauvais format de nombre, veuillez recommencer");
}
}
( Sorry for the poor formatting, I had a rough time with the layout. )
You should use matching has/next methods. Scanner.hasNext() matches Scanner.next(), and Scanner.hasNextInt() matches Scanner.nextInt(). If your input contains a token that is not a valid integer, then hasNextInt() will return false while hasNext() will return true. You can use that to your advantage as shown below.
Also, it's good practice to keep variables to the smallest possible scope; therefore I've moved the declaration of grade to inside the loop.
And finally, for portability, use %n instead of \n in your printf calls.
public void inputGrades()
{
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n %s%n %s%n",
"Enter the integer grades in the range 0-100.",
"Type the end-of-file indicator to terminate input:",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
while (input.hasNextInt())
{
int grade = input.nextInt();
total += grade;
++gradeCounter;
incrementLetterGradeCounter(grade);
}
if (input.hasNext()) {
System.out.printf(
"Fatal error: the token entered as \"%s\" is not a valid integer.%n",
input.next());
System.exit(1);
}
}
Right, I feel like a completed idiot.
Thank you all for your suggestions and I will take them on board and hopefully utilise them soon in my programming!
As it turns out, following Paul Deitel, he uses the command prompt to run his code and his way of showing an end-of-file indicator is by pressing Ctrl+Z, this had been labelled in one of the presentations as both + z as well as ^Z.
When I have tried to input either of those, that is where the error of a string rather than an integer has come up...
Thank you to those who tried to find me an answer!

Java Nested If statement-Or Compared to !=

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

Two if statements with different variables

Ok so im trying to make it so if the person does not want to enter their age the program will print out a different answer. However, when i do this it gives me an error for the string. I used // to make it so the int answer wasnt being played and it worked then. How exactly would I make it so they both work for the same question? I searched for an answer but I couldnt seem to find it so if there is a link for this please link me. Thanks!
System.out.println("So how old are you?");
TimeUnit.SECONDS.sleep(2);
System.out.println("If you dont want to answer you dont have to. ");
Scanner scan4 = new Scanner (System.in);
String user_imput_string1 = scan.nextLine();
if (user_imput_string1.equals("I dont know")) {
System.out.println("Ah thats cool. You look great regardless of your age anyway");
} else {
System.out.println("Ah thats cool. You look great regardless of your age anyway");
}
You would need to convert the String into an int in order to compare the value to 30. However, looking at your code, you seem to have two different variables already, user_imput_string1 and user_imput_int, the latter of which is still a String.
Here is the sample code you could use in order to correctly convert from a String to an int:
int result = Integer.parseInt(user_imput_int);
if (result > 30){
// do whatever
}
Also, as a side note, you are spelling input wrong.
You can do this by catching Exception
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("So how old are you? ");
String age = scanner.next(); //Read string by default
try{
int actualAge = Integer.parseInt(age);
//do your stuff with age
}catch(Exception e){ //Raises NumberFormatException if it's not a number
//e.printStackTrace();
System.out.println("Ah thats cool. You look great regardless of your age anyway");
}
}
The code is below,I hope it can help you.
System.out.println("So how old are you?");
TimeUnit.SECONDS.sleep(2);
System.out.println("If you dont want to answer you dont have to. ");
Scanner scan = new Scanner(System.in);
String user_imput_int = scan.next();
if ("I dont know".equals(user_imput_int)) {
System.out.println("Ah thats cool. You look great regardless of your age anyway");
} else {
try {
int age = Integer.parseInt(user_imput_int);
if(age > 30)
{
System.out.println("Oh wow you look so good");
}
else {
System.out.println("Oh thats ok. You look great regardless");
}
} catch (Exception e) {
System.out.println("your input is either 'I dont know' or int number");
}
}

Categories

Resources