import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
Servicecentre[] ab=new Servicecentre[4];
String n,b;
double c;
boolean o;
System.out.println("enter the details");
for(int i=0;i<4;i++)
{
n=sc.nextLine();
b=sc.nextLine();
c=sc.nextDouble();
sc.nextLine();
o=sc.nextBoolean();
ab[i]=new Servicecentre(n,b,c,o);
}
double ans1=findavg(ab);
if(ans1==0)
{
System.out.println("No online service available");
}
else
{
System.out.format("%.1f",ans1);
}
}
public static double findavg(Servicecentre[] ab)
{
double s=0;
double c=0;
for(int i=0;i<ab.length;i++)
{
if(ab[i].getonline())
{
s=s+ab[i].getcharge();
c=c+1;
}
}
if(c==0)
return 0;
else
return s/c;
}
}
class Servicecentre
{
String name;
String branch;
double charge;
boolean online;
Servicecentre(String name, String branch,double charge,boolean online)
{
this.name=name;
this.branch=branch;
this.charge=charge;
this.online=online;
}
String getname()
{
return name;
}
String getbranch()
{
return branch;
}
double getcharge()
{
return charge;
}
boolean getonline()
{
return online;
}
}
This is the code of my program. I am asked to get input of following types
- Name – String
- branch – String
- Charge – double
- Online – boolean.
and I am asked to find average of the charge only when online is true.the below are their inputs.
- TVS
- Cochin
- 2000
- false
- Bajaj
- Chennai
- 1500
- true
- TCH
- TVM
- 1000
- false
- Arrow
- Chennai
- 2500
- true
I am repeatedly getting error on that bold line and I don't know what I have done wrong .the error is like
"Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at HelloCodiva.main(Main.java:19)"
Kindly help me with the code. I am new to java.
Generally you get a java.util.InputMismatchException when you accidentally feed the wrong input. Validate your input before using it, and you won't receive this error.
Ex.