I have to get a number from a file, some files have letters and numbers convined. like (dsh8kuebw9) or have spaces like(8 8) how can I get those numbers? I have tried so many times. I have a method to find the occurences of a digit is in a number is the count8 method.
The parseInt converts the line of the file in a integer but because in some files there are letters I am having trouble with my method because it only accepts integers no Strings
File file_a = new File("C:\\name\\textFile8a.txt");
try
{
FileReader in = new FileReader(file_a);
BufferedReader readFile = new BufferedReader(in);
String n = readFile.readLine();
int num = Integer.parseInt(n);
System.out.println(count8(num, 8));
}
catch(IOException e)
{
System.out.println("file could not be founded");
System.err.println("OIException: " e.getMessage());
}
CodePudding user response:
You can remove all the numbers in your string before you parse it by replacing non-numberic characters with an empty string:
String n = readFile.readLine();
n = n.replaceAll("[^0-9]", "");
int num = Integer.parseInt(n);
CodePudding user response:
basic and simple solution
public static ArrayList<Integer> extractNumber(String s) {
ArrayList returnList = new ArrayList<Integer>();
Pattern regex = Pattern.compile("\\d[\\d.]*");
Matcher matcher = regex.matcher(s);
while (matcher.find()) {
returnList.add(matcher.group());
}
return returnList;
}
public static void main(String[] args) {
File file_a = new File("C:\\name\\textFile8a.txt");
try {
FileReader in = new FileReader(file_a);
BufferedReader readFile = new BufferedReader(in);
String n = readFile.readLine();
ArrayList<Integer> numberList = extractNumber(n);
System.out.println(numberList);
} catch (IOException e) {
System.out.println("file could not be founded");
System.err.println("OIException: " e.getMessage());
}
}