-1

Using a scanner to read a line of input. I thought there was a way to directly insert the line into an array and have it separate into string elements (divided by spaces).

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        int numberOfStudents = input.nextInt();
        input.nextLine();
        String[][] partners = new String[2][numberOfStudents];
        partners[1] = input.nextLine();
    }
}
Elrond_EGLDer
  • 47,430
  • 25
  • 189
  • 180
Charles
  • 3
  • 2

1 Answers1

1

I attempted to rewrite your code to possibly be what you want. Could you try to specify exactly what you're trying to do?

import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {
       Scanner input = new Scanner(System.in);
       int numberOfStudents = input.nextInt();
       //input.nextLine();
       String[][] partners = new String[2][numberOfStudents];
       for(int i=0; i<numberOfStudents; i++)
       {
          partners[1][i] = input.nextLine();
       }
    }
}

I think you're looking for split. For example:

    String val="I am a String";
    String [] tabDelimitedVals=val.split(" ");

This is seen in the stack overflow post here: How to split a string in Java

To read from a file, you can use

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();
} 

The above was taken from: Reading a plain text file in Java

Together, you can do:

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
    String val=br.readLine();
    String [] splitted=val.split(" ");
}
finally {
   br.close();
}
Community
  • 1
  • 1
Edward Jezisek
  • 502
  • 4
  • 11