Reputation: 65
I need to write a program which reads the input line and store it in a two dimensional character array.
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
char[][] a = new char[4][5];
Scanner inn = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
a[i][j] = inn.next().charAt(i + j);
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
System.out.println(a[i][j]);
}
}
}
}
But i get runtime error.Can anyone say how to resolve it.
Upvotes: 0
Views: 976
Reputation: 11
Change the size of 2 Dimensional array as per your need. import java.util.*;
class StringToCharArray
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String");
char c[] = scan.next().toCharArray();
int i,j,k=0,m;
char data[][] = new char[10][10];
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
data[i][j] = c[k];
k++;
}
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
System.out.print(data[i][j]);
}
System.out.println("");
}
}
}
Upvotes: 1
Reputation: 14471
You should say what the error is for any reasonable answers.
But looking at your code it could be because you are trying to get inn.next()
multiple times in a loop.
Try this.
String value = inn.next();
for(int i=0;i<4;i++)
{
for(int j=0;j<5;j++)
{
a[i][j]=value.charAt(i*5+j);
}
}
Upvotes: 3
Reputation: 26077
Please have a look, enter a character then hit the enter key.
public static void main(String[] args) throws java.lang.Exception {
char[][] a = new char[4][5];
Scanner inn = new Scanner(System.in);
for (int i = 0 ; i < 4 ; i++) {
for (int j = 0 ; j < 5 ; j++) {
a[i][j] = inn.next().toCharArray()[0];
}
}
for (int i = 0 ; i < 4 ; i++) {
for (int j = 0 ; j < 5 ; j++) {
System.out.println(a[i][j]);
}
}
}
Upvotes: 0
Reputation: 69450
You have to read the whole String first and then you can get it char by char:
String s = inn.next();
for(int i=0;i<4;i++)
{
for(int j=0;j<5;j++)
{
a[i][j]=s.charAt(i+j);
}
}
But make sure that the string is long enough. If not you get an StringIndexOutOfBoundsException.
Upvotes: 0