get input from user and store it in String Array in Java -
i write 1 program input user "enter number of students:" add student names , print in console. write 1 code run fine problem loop ramble 1 time code not working want know how inputs using command line argument without scanner , store in string array
here code please , in learning phrase of java
import java.util.scanner; public class stringscanner { public static void main(string args[]) { scanner in = new scanner(system.in); //get input number of students: system.out.println("enter number of students:"); int totalstudents = in.nextint(); //store string array string studentname[] = new string[totalstudents]; for(int = 0; < studentname.length;i++) { system.out.println(i); system.out.println("enter student names: "); studentname[i] = in.nextline(); } for(string names:studentname) { system.out.println(names); } }
}
next(): finds , returns next complete token scanner.
nextline(): advances scanner past current line , returns input skipped.
try placing
scanner.nextline();
after eachnextint()
if intend ignore rest of line.
public class stringscanner { public static void main(string args[]) { scanner in = new scanner(system.in); //get input number of students: system.out.println("enter number of students:"); int totalstudents = in.nextint(); in.nextline();// ignore line //store string array string studentname[] = new string[totalstudents]; for(int = 0; < studentname.length;i++) { system.out.println("enter student names: "+i); studentname[i] = in.nextline(); } for(string names:studentname) { system.out.println(names); } } }
Comments
Post a Comment