Hi i have a txt file with loads of numbers each number is randomly scattered across the file and when i read the file in as a string and try to subdivide it into individual numbers in an array i get the issue of ie my file contains
1234
3467
22222
i didvide the numbers into string array String sub[] however every number goes into sub[0] ie sub[0] = 1234 3467 22222
whereas my desired output for sub[0] would be 1234 my code is below `
File file = new File(s);
String gg;
try {
Scanner in = new Scanner(file);
while (in.hasNext()) {
gg = in.nextLine();
// String temp = gg.replaceAll("\\s*[\\r\\n] \\s*", "").trim();
String temp = gg.replace('\n', ' ');
String[] sub = temp.split(" ");
System.out.println(sub[0]);
`
and the output im getting for sub[0] is a whole bunch of numbers when i only want one which in above example it should be 1234
the comment is one of the ways i tried i also tried using .replaceall the char one '\n' but it didnt work and .replaceall "\s"
CodePudding user response:
Your code (from what I can see) should work fine - you are trying to split a line on the " " character - but it is only a single line...
public static void main (String[] args) throws FileNotFoundException{
File file = new File("numbers.txt");
Scanner in = new Scanner(file);
String gg = "";
while (in.hasNext()) {
gg = in.nextLine().trim(); // <- trim of whitespace
System.out.println(gg);
// maybe the line is all blank ??? best to check
// convert the number to an int here...
// determine min/max/average - need some variables :)
}
}
CodePudding user response:
put string array outside scope of while loop i assumed length is 3 btw replace this with whatever it is
String line;
String sub[] = new String[100];
try {
while((line = buffread.readLine()) != null) {
int i=0;
sub[i] = line;
i ;
}
System.out.println(sub[0]);
}
output is 1234