Suppose you have a binary file containing numbers whose type is either int or double. You do not know the order of the numbers in the file, but their order is written to the line at the beginning of the file. The string consists of the letters i for int and d for double, in the order of the types of subsequent numbers. A string is written using the writeUTF method.
For example, the line "iddiiddd" indicated that the file contains eight values, namely: one integer followed by two doubles, and then two integers followed by three doubles.
My problem is that if there are more letters than numbers in a line, how can I create an if statement telling the user that there is an error in the file they are trying to read?
I tried using this where "count" is the number of numbers and "length" is the length of the string, but that did not work.
if(count!=length){
System.out.println("Error in file: Length of string and numbers are not equal");
System.exit(0);
}
the rest of my code is this:
public static void main(String[] args) {
Scanner keyboard=new Scanner(System.in);
System.out.print("Input file: ");
String fileName=keyboard.next();
int int_num_check=0;
double double_num_check=9999999999999999999999999999.999999999;
int int_num=0;
double double_num=0.0;
int count=0;
try{
FileInputStream fi=new FileInputStream(fileName);
ObjectInputStream input=new ObjectInputStream(fi);
String word=input.readUTF();
int length=word.length();
for(int i=0;i<length;i++){
if(word.charAt(i)=='i'){
int_num=input.readInt();
System.out.println(int_num);
if(int_num>int_num_check){
int_num_check=int_num;
}
}
else if(word.charAt(i)=='d'){
double_num=input.readDouble();
System.out.println(double_num);
if(double_num<double_num_check){
double_num_check=double_num;
}
}
else{
System.out.println("Error");
System.exit(0);
}
count++;
}
System.out.println("count: "+count);
System.out.println("length "+length);
if(count!=length){
System.out.println("Error in file: Length of string and numbers are not equal");
System.exit(0);
}
String checker=input.readUTF();
if(!checker.equals(null)){
System.out.println("Error");
System.exit(0);
}
input.close();
fi.close();
}
catch(FileNotFoundException e){
System.out.println("Error");
System.exit(0);
}
catch(EOFException e){
System.out.println("Largest integer: "+int_num_check);
System.out.println("Smallest double: "+double_num_check);
System.exit(0);
}
catch(IOException e){
System.out.println("Error");
System.exit(0);
}
}
}
source
share