Reputation: 19
Is there any method to give input to the Character data type without using String. for eg : if I have to initialize the character array then usually we do in this format :
c[i]=string.next().charAt(i);
I don't want to use the next() method.
Could you tell me any other methods?
//System.out.println("Enter the String");
c[i]=s1.next().charAt(i);
int n;
Scanner s1=new Scanner(System.in);
System.out.println("Enter the number of string arrays");
n=s1.nextInt();
char[] c=new char[n];
for(int i=0;i<n;i++)
{
//System.out.println("Enter the String");
c[i]=s1.next().charAt(i); // I dont want to use this .
}
for(int i=0;i<n;i++)
{
System.out.print(c[i]);
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 at java.lang.String.charAt(Unknown Source) at CountingValleys.main(CountingValleys.java:16)
Upvotes: 1
Views: 355
Reputation: 1107
To accept character as input in java, we do not have any specific input stream like for Integer {nextInt()
}.
So the choice we are left with is to make use of next()
with a bit twist in it like below-
Scanner sc = new Scanner(System.in);
char inputCharacter = sc.next().charAt(0);
In your case if you want to read multiple characters you can read them at index 0 and keep appending them to you character array.
Below is the code snippet-
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
char arr[] = new char[n];
for(int i=0;i<n;i++) {
arr[i] = sc.next().charAt(0);
}
for(int i = 0; i< n; i++){
System.out.println(arr[i]);
}
}
Upvotes: 1