Question: What am I doing wrong in my code? It is supposed to display the * symbol if the text in the file is not long

What am I doing wrong in my code? It is supposed to display the * symbol if the text in the file is not long enough to fill the array. As written, it works with a long sentence. But if you shorten the data file to a small sentence such as "Today was a sunny day." and then run the program you get error messages. Any help would be appreciated.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 21 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48) at java.base/java.lang.String.charAt(String.java:712) at CharArray.main(CharArray.java:38)

Code:

// 2-D Character Array // Author Jennifer Ferris

import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner;

// a program that reads text from a file public class CharArray { public static void main(String[] args) { File file = new File("Data.txt");

// create a 2-dimensional character array that is 6 * 7 char array[][]= new char[6][7]; // Fill any unused spaces in the 2-D array with the * character. for(int i=0;i<6;i++) { for(int j=0;j<7;j++) { array[i][j] = '*'; } } try {

Scanner sc = new Scanner(file); String content = ""; while (sc.hasNextLine()) { content+=sc.nextLine(); } sc.close(); // outputting text from file System.out.println("Content in the text file ------------------------ "+content); int index = 0;

// displaying the text in the 6 x 7 two dimensional array System.out.println(" Arrange data in 6 X 7 Two Dimensional Array -------------------------------------------");

// Store the characters read in your array in row major order (fill row 0 first, then row 1, etc.) // If you have more characters than space, ignore the excess characters for(int i=0;i<6;i++) { for(int j=0;j<7;j++) { array[i][j] = content.charAt(index); index++; System.out.print(array[i][j]+"\t"); } System.out.println(); } System.out.println(" Solution - Printing the data column wise ----------------------------------------"); String output = ""; // Extract the characters from your array in column-major order (pull from column 0 first, then column 1, etc.). for(int i=0;i<7;i++) { for(int j=0;j<6;j++) {

// Build a new string as you extract the characters output+= array[j][i]; } } // Display the new string. System.out.println(output); } catch (FileNotFoundException e) { e.printStackTrace(); } } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!