I am having trouble running my code as it is giving me Exception in thread "main" java.util.InputMismatchException. Can you please help me out. Here is the code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution1 {
public static void main(String args[] ) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int id;
String title;
String author;
double price;
Scanner sc=new Scanner(System.in);
Book [] book =new Book[4];
// try{
for(int i=0;i<book.length;i++){
id=sc.nextInt();
sc.hasNextLine();
title=sc.nextLine();
author=sc.nextLine();
price=sc.nextDouble();
book[i]=new Book(id,title,author,price);
}
sc.close();
Book[] res=sortBookByPrice(book);
if(res!=null){
for(int i=0;i<res.length;i++){
System.out.println(res[i].getId()+res[i].getTitle()+res[i].getAuthor()+res[i].getPrice());
}
}//}
//catch(InputMismatchException e){
// System.out.println(e);
//}
}
public static Book[] sortBookByPrice(Book[] book){
for(int i=0;i<book.length;i++){
if(book[i].getPrice()>book[i+1].getPrice()){
Book temp=book[i];
book[i]=book[i+1];
book[i+1]=temp;
}
}
return book;
}
}
class Book
{
private int id;
private String title;
private String author;
private double price;
Book(int id,String title,String author,double price){
this.id=id;
this.title=title;
this.author=author;
this.price=price;
}
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title=title;
}
public String getAuthor(){
return author;
}
public void setAuthor(String author){
this.author=author;
}
public double getPrice(){
return price;
}
public void setPrice(double price){
this.price=price;
}
}
This is the error I am getting
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at Solution1.main(Solution1.java:23)
I am using this to show the output in ascending order but as soon as I press enter after writing the author, the code is giving me the error. Please help.
This is the input that I am using...
1
hello
writer1
50
2
cup
writer2
55
3
Planet
writer3
45
4
India
writer4
40