-1

i have file

Which contains numbers and strings in this form

1,2,ssh,4,5
sor,7,8,bbt,10

How can I read the numbers/string one by one in a loop?

I tried to read like that:

  input = new Scanner(data_to_insert);
  String data;
  while (input.hasNext()) {
    data = input.next();
    data = data.replaceAll(",", "");
    println("data to hash ->" + data);

But I get for example:

data to hash ->12345

And I wanted to get first 1 after that 2 and so on

like this:

data to hash ->1
data to hash ->2
.
.
.
data to hash ->5
daniel
  • 143
  • 5
  • 2
    What have you tried so far, and where exactly are you stuck? – Mureinik Jan 03 '21 at 20:28
  • 2
    !) What form? I don't see a consistent format. The first line starts with numbers, the second line starts with text. 2) You can use `String.split(...)` to split the data into an array of Strings. – camickr Jan 03 '21 at 20:28
  • I edited to explain what I meant – daniel Jan 03 '21 at 20:34
  • 1
    @Tom that would be if he was asking how to split the string, but that wasn't his question. it might not have come to his mind that splitting the string would work. – null_awe Jan 03 '21 at 20:48
  • Does this answer your question? [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Tom Jan 03 '21 at 20:51

1 Answers1

1

Use a for loop in your while loop to loop through everything in each line (and String.split(","); to separate by the commas. In your example code, you printed out each line instead of each comma-separated token.

input = new Scanner(data_to_insert);
String data;
while (input.hasNext()) {
  String[] words = input.next().split(",");
  for (String word : words) System.out.println("data to hash -> " + data);
}

This should work.

null_awe
  • 483
  • 6
  • 17