A JAVA code read each line in the input file, check if there is no negative number and ignore all space
时间: 2024-05-09 14:20:30 浏览: 116
JAVA 文件读写
characters.
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
String filePath = "input.txt";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
line = line.replaceAll("\\s", ""); // remove all spaces
boolean hasNegative = false;
String[] nums = line.split(",");
for (String num : nums) {
if (Integer.parseInt(num) < 0) {
hasNegative = true;
break;
}
}
if (!hasNegative) {
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
This code uses a `BufferedReader` to read each line in the input file. It then removes all spaces from the line using the `replaceAll` method. It then checks if there are any negative numbers in the line by splitting it into an array of numbers using the `split` method and then iterating over each number to check if it is negative. If there are no negative numbers, the line is printed to the console.
阅读全文