سؤال

I'm having trouble with an assignment. What's happening is that a file is being read that reads numbers and validates if they're correct values. One of these values contains a letter and I'm trying to get my program to detect that and save the total value that should not be there. Here's the code. I'm reading the data as Strings and then converting the strings into doubles to be compared. I want to validate if the strings being read in are all numbers and then save that value for a later use. Does that make sense? for example the numbers have to be between 0 and 99999 and one value is 573S1, which wouldn't work because it contains an S. I want to save that value 573S1 to be printed as an error from the file at a later point in the code.

public static void validateData() throws IOException{
            File myfile = new File("gradeInput.txt");
            Scanner inputFile = new Scanner(myfile);
            for (int i=0; i<33; i++){
                    String studentId = inputFile.next();
                    String toBeDouble = studentId;
                    Double fromString = new Double(toBeDouble);
                    if (fromString<0||fromString>99999){
                            System.out.println();
                    }

Any help would be greatly appreciated. Thanks a lot!

Edit: Here's what I get if I try to run the program.

Exception in thread "main" java.lang.NumberFormatException: For input string: "573S1"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
    at java.lang.Double.valueOf(Double.java:475)
    at java.lang.Double.<init>(Double.java:567)
    at Paniagua_Grading.validateData(Paniagua_Grading.java:23)
    at Paniagua_Grading.main(Paniagua_Grading.java:6)
هل كانت مفيدة؟

المحلول

Because you are using Scanner on a file, Scanner can actually tell you this information with hasNextDouble.

while(inputFile.hasNext()) {
    if(inputFile.hasNextDouble()) {

        // the next token is a double
        // so read it as a double
        double d = inputFile.nextDouble();

    } else {

        // the next token is not a double
        // so read it as a String
        String s = inputFile.next();
    }
}

This kind of convenience is the main reason to use Scanner in the first place.

نصائح أخرى

You could try something like the method below, which will check if a string contains only digits -

private static boolean onlyDigits(String in) {
  if (in == null) {
    return false;
  }
  for (char c : in.toCharArray()) {
    if (Character.isDigit(c)) {
      continue;
    }
    return false;
  }
  return true;
}

public static void main(String[] args) {
  System.out.println(onlyDigits("123"));
  System.out.println(onlyDigits("123A"));
}

The output is

true
false
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top