I'm getting this error in a really simple code and I am not able to figure it out.
Also, please suggest what is the best way to read two consecutive strings, like in this case. I face InputMismatchException and I think that it could be the cause.
it's strange that the code fails to accept the integer too. I'm getting an exception while reading the integer.
I'm not sure when to use Scanner.next() and Scanner.nextLine().
import java.util.Scanner;
class Customer
{
private int id;
private String name;
private String city;
private double salary;
Customer(){}
Customer(int id, String name, String city, double salary)
{
this.id=id;
this.name=name;
this.city=city;
this.salary=salary;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public String getCity(){
return city;
}
public double getSalary(){
return salary;
}
public void setId(int id){
this.id=id;
}
public void setName(String name){
this.name=name;
}
public void setCity(String city){
this.city=city;
}
public void setSalary(double salary){
this.salary=salary;
}
}
public class Solution{
public static void main(String []args){
Scanner in = new Scanner(System.in);
Customer c = new Customer();
int id = in.nextInt();
String name = in.next();
String city = in.next();
double sal = in.nextDouble();
c.setId(id);
c.setName(name);
c.setCity(city);
c.setSalary(sal);
System.out.println(c.getId() + " " + c.getName() + " " + c.getCity() + " " + c.getSalary());
}
}
Input
1
ABC
MH
2000.25
Stack Trace
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Solution.main(Solution.java:61)