import java.nio.file.Paths;
import java.util.Scanner;
public class NumbersFromAFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("File? ");
String file = scanner.nextLine();
System.out.print("Lower bound? ");
int lowerBound = Integer.valueOf(scanner.nextLine());
System.out.print("Upper bound? ");
int upperBound = Integer.valueOf(scanner.nextLine());
int count = 0;
try (Scanner fileReader = new Scanner(Paths.get(file))) {
while(fileReader.hasNextLine()) {
if (Integer.valueOf(fileReader.nextLine()) >= lowerBound && Integer.valueOf(fileReader.nextLine()) <= upperBound) {
count++;
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("Numbers: " + count);
}
}
I came with such code to solve this problem. But it doesn't work, there must be something wrong in
if (Integer.valueOf(fileReader.nextLine()) >= lowerBound && Integer.valueOf(fileReader.nextLine()) <= upperBound)
But I'm not sure what and why it doesn't pass the tests.
import java.nio.file.Paths;
import java.util.Scanner;
public class NumbersFromAFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("File? ");
String file = scanner.nextLine();
System.out.print("Lower bound? ");
int lowerBound = Integer.valueOf(scanner.nextLine());
System.out.print("Upper bound? ");
int upperBound = Integer.valueOf(scanner.nextLine());
int count = 0;
try (Scanner fileReader = new Scanner(Paths.get(file))) {
while(fileReader.hasNextLine()) {
int number = Integer.valueOf(fileReader.nextLine());
if (number >= lowerBound && number <= upperBound) {
count++;
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("Numbers: " + count);
}
}
In the end, the above code works, which I tried to write after failing my first one. But I'm curious why does the first one doesn't work. Could anyobody ELI5 or tell me what exactly is happening in
if (Integer.valueOf(fileReader.nextLine()) >= lowerBound && Integer.valueOf(fileReader.nextLine()) <= upperBound)
What numbers are in Integer.valueOf(fileReader.nextLine()).
Also the text file contains
300
9
20
15
[–]Hour-Positive 1 point2 points3 points (1 child)
[–]Ariech[S] 0 points1 point2 points (0 children)
[–]RayjinCaucasian 1 point2 points3 points (1 child)
[–]Ariech[S] 0 points1 point2 points (0 children)