Suppose that you have a binary file that contains numbers whose type is either int or double. You dont know the order of the numbers in the file, but their order is recorded in a string at the beginning of the file. The string is composed of the letters i for int, and d for double, in the order of the types of the subsequent numbers. The string is written using the method writeUTF.
For example the string "iddiiddd" indicated that the file contains eight values, as follows: one integer, followed by two doubles, followed by two integers, followed by three doubles.
My problem is that, if there are more letters in the string than numbers, how can I create an if statement telling the user there is an error in the file they are trying to read?
I tried using this, where "count" is the amount of numbers and "length" is the length of the string, but this 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);
}
}
}
Aucun commentaire:
Enregistrer un commentaire