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");
}
}
Related
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!
I'm trying to only accept numbers from a user. This code works for giving them an error message if they enter a letter. But it doesn't work for if they hit Enter or just white space. I've tried initializing a String called test as null and then setting scnr.nextLine() = test, and then checking if test is empty, but I didn't understand how to keep the rest of the program operating correctly when I did that. Scanner is very tricky to me. Please help!
double mainNumber = 0;
System.out.print("Enter a number: ");
if (scnr.hasNextDouble() ){
mainNumber = scnr.nextDouble();
System.out.println(mainNumber);
scnr.nextLine();
}
else {
System.out.println("Sorry, please enter a number.\n");
scnr.nextLine();
}
You have to use while-cycle and loop input as long as needed before user put a valid number.
This code
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double mainNumber = 0;
boolean isValidNumber = false;
System.out.print("Enter a number: ");
while (isValidNumber == false) {
String line = scnr.nextLine();
try {
mainNumber = Double.valueOf(line);
isValidNumber = true;
} catch (NumberFormatException e){
System.out.print("Sorry, please enter a number.\n");
}
}
System.out.println("Main number is: " + mainNumber);
}
Having this sample output :
Enter a number: sdfgsgxb
Sorry, please enter a number.
xcvbxcvb
Sorry, please enter a number.
gsfdfgsdf
Sorry, please enter a number.
aearg
Sorry, please enter a number.
15.77
Main number is: 15.77
Well I guess your code is in a while loop or something ? So that it keep asking until the user enter the right value.
Then you should (for convenience) use String str = scnr.nextString() instead of nextDouble() and analyze the string it returned.
You can use str.trim() to remove whitespaces (and then check if string is empty with str.isEmpty() ), and to check if it's a number you can use regexp ( How to check that a string is parseable to a double? and any regex tutorial you can find ) or just use this regex: str.matches("\\d+") (returns true if str is a number, but no comma here).
Of course, don't forget to cast your String as double after: Double.parseDouble( str.replace(",",".") );. I hope the "replace" part is obvious ;)
You might use the following snippet to read one double value:
Scanner scanner = new Scanner(System.in);
try {
double number = Double.parseDouble(scanner.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
So I'm writing code here just for fun but I've come up with an error that I just can't seem to fix. This block of code is supposed to take in an int... at first i had the hasNextInt() in the while loop alone to try and ensure i'm getting the correct input, but as fate would have it.. i got the exception. I then added a try catch to it thinking maybe i just did something wrong... and still i get the same error. I don't know whats wrong here. this is actually my 1st time using a try catch block (still kind of a noob). it looks good to me and i've looked at the documentation online and done some minor research but to no avail. can anyone identify whats wrong here?
check it out:
do{
System.out.println("How much AP do you want to allocate towards HP? ");
try {//added try catch... still throwing the exception..
while(!in.hasNextInt()){//this should've been enough, apparently not
System.out.println("That is not a valid input, try again.");
in.nextInt();
}
} catch (InputMismatchException e) {
System.out.print(e.getMessage()); //trying to find specific reason.
}
hpInput = in.nextInt();
}while(hpInput < 0 || hpInput > AP);
if i entered a string it would give me the "That is not a valid input, try again." line.. but the exception would still occur right after instead of just looping until an actual int is detected... help plz..
Your while loop should look something like this
while(!in.hasNextInt()){ // <-- is there an int?
System.out.println("That is not a valid input, try again.");
// in.nextInt(); // <-- there is not an int...
in.next(); // <-- this isn't an int.
}
Because the Scanner doesn't have an int.
You can't really validate the value in the Scanner until something has been input, but once it's input, it's too late to validate it...
Instead, you could use a second Scanner to validate the String result you are getting from the user via the keyboard, for example
Scanner kbd = new Scanner(System.in);
int result = -1;
do {
System.out.println("How much AP do you want to allocate towards HP? ");
String value = kbd.nextLine();
Scanner validate = new Scanner(value);
if (validate.hasNextInt()) {
result = validate.nextInt();
}
} while (result < 0);
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);
}
"if" statement only allows to put numbers in it.
Is there a way to make it read letters?
I'm only in my fifth lesson of Java (I study in a uni and the teacher is very slow but I want to learn things fast)
for example.
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int answer1;
System.out.println("Do you like Java?");
answer1 = scan.nextInt();
if (answer1 == yes)
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I want to put "yes" instead of the number 5.
So if the user types "yes" it will print "correct".
P.S. I didn't find a clear answer to that in the search engine.
It's not a duplicated thread as I'm trying to find a clear answer to that.
I need a detailed explanation about it.
I'm still a beginner, using those "high tech java words" won't help me.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's now a String. See this answer for more on comparing Strings.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner; public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
} }
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's
now a String. See this answer for more on comparing Strings.
Ok, what if you want the program to read both words and numbers:
Here's my program (more in depth, when you see the full thing), but this is one of 5 parts (that look a like) where I'm having the program...
public static void Gdr1() {
try {
System.out.print("[Code: Gdr1] Grade 1: %");
Scanner gdr1 = new Scanner(System.in);
Z = gdr1.next();
Z = Double.toString(Grd1);
Grd1 = Double.parseDouble(Z);
if ((Grd1<100)&&(Grd1>=5)) {
Gdr2();
} else if ((Grd1>=100)&&(Grd1<125)) {
System.out.println(" System> Great Job "+Stu+"!");
Gdr2();
} else if (Grd1<5) {
System.out.println("I'm sorry, the lowest grade I am allowed to compute is 5...");
Gdr1();
} else if (Z.equalsIgnoreCase("restart")) {
restart01();
} else {
System.out.println("("+Z+") cannot be resolved in my system...");
Gdr1();
}
} catch (Exception e) {}
}
Now everything works in the program, besides for when the End-User's input = "restart", I know some of the code in the program seems complicated, but it does work (most of it), can anyone help me try to figure this out, its for my portfolio at my school due latest by 1/25/2017 # 11:59 pm.
The things like Z (constant String), ""+Stu+"" (variable input), and [Code: Gdr1] are there for a purpose...