java - Reading and storing names in an array from user input -
i'm in midst of creating program takes in 10 names user input, stores them in array , prints them out in upper case. know there's been similar threads/questions asked none of them helped me. per, appreciated.
my code:
import java.util.scanner; public class readandstorenames { public static void main(string[] args) throws exception { scanner scan = new scanner(system.in); //take 10 string values user system.out.println("enter 10 names: "); string n = scan.nextline(); string [] names = {n}; //store names in array (int = 0; < 10; i++){ names[i] = scan.nextline(); } //sequentially print names , uppercase them (string : names){ system.out.println(i.touppercase()); } scan.close(); } }
the current error i'm getting (after 3 inputs may add):
enter 10 names: tom steve phil exception in thread "main" java.lang.arrayindexoutofboundsexception: 1 @ readandstorenames.main(readandstorenames.java:22)
your problem here:
string [] names = {n};
the size of names
1, value 10. want is:
string [] names = new string[n];
the latter correct syntax specifying size
of arrays.
edit:
it seems want read n
using scanner. nextline
can anything, not integer. change code this:
import java.util.scanner; public class readandstorenames { public static void main(string[] args) throws exception { scanner scan = new scanner(system.in); system.out.println("how many names enter?") int n = scan.nextint(); //ensures take integer system.out.println("enter " + n + " names: "); string [] names = new string[n]; //store names in array (int = 0; < names.length; i++){ names[i] = scan.nextline(); } //sequentially print names , uppercase them (string : names){ system.out.println(i.touppercase()); } scan.close(); } }
Comments
Post a Comment