I new to java.I want to input studentId and studentName using Scanner and store these values to a array/s.
System.out.print("Enter StudentId :");
String studentId = input.nextLine();
System.out.print("Enter StudentName :");
String studentName = input.nextLine();
Can I store these values(not a single value) to a array?
CodePudding user response:
Try using BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter StudentID,StudentName");
String[] arr = br.readLine.trim().split(",");
Keep in mind
- While inputs provide studentid and studentname as comma separated (you can change it if you want as per you requirement).
- You need to import java.io.*;
- This throws exception. So you can either add throws IO Exception with your main method or put all this in try catch.
Input
101, Virat
CodePudding user response:
taking whole line as one input and splitting them. If input is seperated by comma, use split(",")
or if seperated by space, use split(" ")
String input = sc.nextLine();
String[] myArray = input.split(" ");
input :
R123 Ravi
myArray will become {"R123","Ravi"}
CodePudding user response:
Something like this
// short version
String[] myArray = new String[]{
studentId,
studentName
};
System.out.println(Arrays.toString(myArray));
// adding one by one
String[] myArray1 = new String[2];
myArray1[0] = studentId;
myArray1[1] = studentName;
System.out.println(Arrays.toString(myArray1));