This question already has answers here:
why cant we use <, <=, >,>= relational operators on String?
(4 answers)
Closed 1 year ago.
I have no idea why this doesn't work. Please help, I am new to java
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("what is your first number ");
String firstNum = scanner.nextLine();
System.out.println("what is your second number ");
String secondNum = scanner.nextLine();
System.out.println("what is your Third number ");
String thirdNum = scanner.nextLine();
if (firstNum > secondNum) {
System.out.println("the firs number is bigger than the firs number");
Scanner.nextLine() is used to input string . Instead use scanner.nextInt() to input number and store in an integer variable.
This is an illegal comparison. You cannot compare a String to a String. You should use Scanner.nextInt(). If you want to use a string to store a numerical value than you can use Integer.parseInt() to convert string into int.
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm making a simple calculator, but I've run into a problem where a string input is skipped.
Here is my code:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Calculator\n");
while (true) {
System.out.print("Number: ");
float num1 = input.nextFloat();
System.out.print("Operator: ");
String optr = input.nextLine();
System.out.print("Number: ");
float num2 = input.nextFloat();
System.out.println(num1 + num2);
}
}
}
I have tried doing \n but I don't know what else I should really do as I don't know what the problem is.
I know input is never closed, but I have tried closing it. It has no affect and I don't want to add it right now as I am making the base system.
Instead of using...
System.out.print("Operator: ");
String optr = input.nextLine();
...use this...
System.out.print("Operator: ");
String optr = input.next();
The method nextLine() is a bit finnicky. Long story short, if you use nextLine(), beware that it doesn't play well with next(), nextInt(), nextFloat(), etc.
If you want the long story, here is a more detailed explanation -- https://stackoverflow.com/a/13102066/10118965
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
i was practicing scanner usage and syntax and below is the code i wrote, where I am trying to take 4 inputs from the user :
Scanner s= new Scanner(System.in);
int a = s.nextInt();// taking an integer as input, it works fine.
String b = s.nextLine();//was supposed to take a string input, but not working
String c=s.nextLine();//takes a string as input from user
String d=s.nextLine();//takes another string as input from user
System.out.println("integer entered: "+a);
System.out.println("first string entered: "+b);
System.out.println("second string entered: "+c);
System.out.println("third string entered: "+d);
but the user is able to give only 3 inputs, the first integer and other two string inputs and by printing the values of these 4 variables, it is clear that input for first string String b is skipped.I then tried to rearrange the sequence in which the input was taken, i.e,
String b = s.nextLine();//takes a string input
int a = s.nextInt();// taking an integer as input
String c=s.nextLine();//was supposed to take a string as input from user
String d=s.nextLine();//takes another string as input from user
in this case, the input for the second string String cis skipped.
So, is it because of the integer input that skips the next string input?
This is a common question.
Fixed code
Scanner s= new Scanner(System.in);
int a = s.nextInt();
s.nextLine();
System.out.print("Enter a string: ");
String b = s.nextLine();
System.out.print("Enter another string: ");
String c=s.nextLine();
System.out.print("Enter one more string: ");
String d=s.nextLine();
System.out.println(a+"\n"+b+d+c);
Ref:
Scanner is skipping nextLine() after using next() or nextFoo()?
I'm having a problem when trying to run my program. What my program is supposed to do is to receive a number and compare it to an int. I understand that the program thinks that I'm trying to compare String with an int and not happy about it. What can I do?
import java.util.Scanner;
public class C {
public static void main(String args[]) {
Scanner input = new Scanner (System.in);
String age = input.nextLine();
if (age < 50){
System.out.println("You are young");
}else{
System.out.println("You are old");
}
}
}
You cannot compare a String to an int using a numerical comparison-operator. §15.20.1 of the Java Language Specification describes exactly what you are seeing:
The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.
Since String is not convertible to a primitive numeric-type, you cannot compare it against an integer. Therefore you have two options:
You can convert the String into an int using Integer#parseInt:
int age = Integer.parseInt(ageString);
But in your case, since you are already reading in input, it would be better to bypass the whole parseInt bit and read in an int directly:
int age = input.nextInt();
Keep in mind though that you still have to deal with the possibility of invalid input.
You need age to be an integer in order to compare it to 50.
You have two options :
int age = input.nextInt();
or
int age = Integer.parseInt(input.nextLine());
Note that both options would throw exceptions if the input you enter is not an integer.
Before comparing you need to convert it to integer using parseInt().
You need to parse the String as an Integer.
String age = input.nextLine();
if (Integer.parseInt(age) < 50) {
System.out.println("You are young");
}
The scanner class actually has an input method called nextInt() that you can use:
Scanner input = new Scanner(System.in);
int age = input.nextInt();
// Comparisons
You cannot compare a String and a int values using "<",">","<=",">=" operators. That is the problem with your code. to fix that you can either,
take input from the user as int by replacing the line 5 as int age = input.nextInt();
or you can convert your age String to integer after taking inputs from the user using something like this int intage=Integer.parseInt(age);. Then you can replace your age variable with intage variable
This question already has answers here:
Scanner issue when using nextLine after nextXXX [duplicate]
user input string and integers in Java [duplicate]
(3 answers)
Closed 8 years ago.
int id;
float grade;
String name;
Scanner z= new Scanner(System.in);
System.out.println("Give the id:\n");
id=z.nextInt();
System.out.println("your id is :"+id+"\n");
System.out.println("Give the name:");
name=z.nextLine();
System.out.println("your name is :"+name);
System.out.println("Give the grade:\n");
grade=z.nextFloat();
The problem goes like this.It inputs the integer but when it comes to the String, it prints "Give the name" but it doesn't waits until I type something, it skips to the next instruction.
Why's that?
You have used name=z.nextLine(), hence such behavior, Replace it with name=z.next(). Below is the edited code:
int id;
float grade;
String name;
Scanner z= new Scanner(System.in);
System.out.println("Give the id:\n");
id=z.nextInt();
System.out.println("your id is :"+id+"\n");
System.out.println("Give the name:");
name=z.next();
System.out.println("your name is :"+name);
System.out.println("Give the grade:\n");
grade=z.nextFloat();
When you read int value using nextInt, it reads only the int value, it skips the new line character. The latter will be read in the next nextLine causing it to skip the "real" input.
You can fix this by adding another nextLine before the "real" nextLine, it'll swallow the '\n' that you don't want to read.
Important note: Don't use int to store ID value! Use String instead!
The problem is with the input.nextInt() command it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine()
id = z.nextInt();
System.out.println ("your id is :"+id+"\n");
z.nextLine ();// add this line between the next line read
System.out.println("Give the name:");
or
id = Integer.parseInt(z.nextLine());
System.out.println ("your id is :"+id+"\n");
System.out.println("Give the name:");
I have the following Java code:
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter your name>>");
String name = input.next();
System.out.println("Enter your year of birth>>");
int age = input.nextInt();
System.out.println("Name: " + name);
System.out.println("Year of Birth: " + age);
System.out.println("Age: " + (2012 - age));
} catch (InputMismatchException err) {
System.out.println("Not a number");
}
When I enter a name with a space (e.g. "James Peterson"), I get the next line output correctly (Enter your year of birth) and then an InputMismatchException immediately. The code works with a single name without spaces. Is there something I'm missing?
System.out.println("Enter your name>>");
String name = input.next();
System.out.println("Enter your year of birth>>");
int age = input.nextInt();
Scanner, breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
When you enter "James Peterson", Scanner#next() takes "James" as a token and assigns it to String name and then you do a Scanner#nextInt() which takes "Peterson" as the next token, but it is not something which can be cast to int and hence the InputMismatchException asnextInt() will throw an InputMismatchException if the next token does not match the Integer regular expression, or is out of range.
Actually the problem in your code has been clearly pointed out. In your case, there are two typical ways to achieve that:
One
Using useDelimiter method to delimite the input and after each input, you need to hit the Enter.
Sets this scanner's delimiting pattern to a pattern constructed from the specified String.
In your case, you need to
Scanner sc = new Scanner(System.in);
sc.setDelimiter("\\n");
// hit the "Enter" after each input for the field;
Two
Also you can achieve the same result using readLine
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
In this way, you can do
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name>>");
String name = sc.nextLine();
...
System.out.println("Enter your year of birth>>");
int age = sc.nextInt();
P.S.
Actually you can achieve it in a more restrictive way, controlling the pattern using next(Pattern pattern), if you need it.
int age = sc.next(Pattern.compile("\\d+{1,3}"));
In this case, if the input DOES NOT match the pattern, it will throw InputMismatchException as you were trying to nextInt while the input is a string.
When I enter a name with a space (e.g. "James Peterson"), I get the next line output correctly (Enter your year of birth>>) and then an InputMismatchException immediately.