In: Computer Science
Every time I attempt to execute this, I get an
inputmismatchexception, which looks like this:
Oops! Read Exception: java.util.InputMismatchExceptionInitial
input:
Input sorted by grade
Input sorted selection
This is my code.
import java.util.*;
import java.io.*;
import java.io.PrintStream;
public class jack {
PrintStream prt = System.out;
int n;
int i;
int j;
double grade[];
String name[];
jack() {
try {
Scanner inf = new Scanner(System.in);
n=inf.nextInt();
inf.nextLine();
grade=new double[n];
name = new String[n];
for (int i=0; i<n; i++){
name[i] = inf.next();
inf.nextLine();
grade[i] = inf.nextDouble();
inf.nextLine();
}
inf.close();
} catch (Exception e) {
prt.printf("\nOops! Read Exception: %s", e);
}
}
private void print() {
for(int i=0; i<n; i++)
{
System.out.println(name[i]+" "+grade[i]);
}
System.out.println();
}
private void sortbyname(){
String minStudent;
int index;
for(int i=0;i<n-1;i++){
minStudent=name[i];
index=i;
for(int j=i+1; j<n; j++){
if(name[j].compareTo(minStudent)<0)
{
minStudent = name[j];
index =j;
}
}
String beforewrd = name[index];
name[index]=name[i];
name[i]=beforewrd;
}
}
private void sortbygrade(){
for(int i=0;i<n;i++){
int index=i;
for(int j=i+1; j<n; j++){
if(grade[j]<grade[i]){
index = j;
}
}
double smallNum = grade[index];
grade[index] = grade[i];
grade[i]=smallNum;
}
}
public static void main(String args[]) throws Exception{
jack p = new jack ();
System.out.print("Initial input:");
p.print();
p.sortbyname();
System.out.print("Input sorted by grade");
p.print();
p.sortbygrade();
System.out.print("Input sorted selection");
p.print();
}
}
OUTPUT OF YOUR CODE:
3
abc
98.79
xyz
99.65
jkl
97.86
Initial input:abc 98.79
xyz 99.65
jkl 97.86
Input sorted by gradeabc 98.79
jkl 99.65
xyz 97.86
Input sorted selectionabc 97.86
jkl 98.79
xyz 99.65
...Program finished with exit code 0
I didn't make any changes to your code. No exceptions occurred.
Output2:
4
John
98.75
Steve
98.54
Harry
85.98
Noah
89
Initial input:John 98.75
Steve 98.54
Harry 85.98
Noah 89.0
Input sorted by gradeHarry 98.75
John 98.54
Noah 85.98
Steve 89.0
Input sorted selectionHarry 89.0
John 85.98
Noah 98.54
Steve 98.75
...Program finished with exit code 0