简体   繁体   中英

Txt file to 2D array in java

I am striving to meet the requirements of this community. I have bashed my head against this problem for ten hours or so. I rarely ask for help, so forgive me if I am not fully compliant.

I have been assigned to make a java code that will read a text file that is an ASCII image. The first line of the text file is the dimensions of the image, ignoring the first line. I am having a devil of a time filling the character array. When I use dummy text the program outputs an array of the correct size, but I can't get it to store the actual characters from the file. I'm absolutely certain that I am experiencing some 1D1OT errors, there's probably a lot of junk code. I've tried to clean it up, but the frustration from writing the file has been my main focus.

Also: yes this is absolutely a homework assignment. Full disclosure. I wouldn't be using an array for this task otherwise. However, the assignment isn't due for more than a week. I really don't want to be one of those individuals that want you to do their work for them.

import java.util.*;
import java.io.*;


public class Shell{

    private static String fileName = null;
    private static int imageHeight =0;
    private static int imageWidth=0;
    private static char[][] buffer = null;
    private static Scanner input;
    private static Scanner in;
    private static Scanner in2;
    private static Scanner inFile;

    /*
    FUNCTION NAME: Main ;
    INPUT: none.
    OUTPUT: a message to the user of this program, all of the
    prompts and a final display according to user specifications.
    PRECONDITIONS:  None.
    POSTCONDITIONS: Variables and calls made according to users input
                    output set to start on a new line.
    CALLERS: None.
    CALLEES: askPermission, getParameters(), getImage(), and doTileJob().

     */

    public static void main(String args[]) throws FileNotFoundException
    {

    //in = new Scanner(System.in);
    //System.out.println("What file name would you like to print?");
    //String fileName = in.nextLine();
    //input = new Scanner(new File(fileName));

    boolean a = askPermission();
        if (a == true) { 
            while (a == true) {
                System.out.println("What is the name of the file you want printed?");
                in = new Scanner(System.in);
                fileName = in.nextLine();
                new Scanner(new File(fileName));
                System.out.println(fileName);
                getParameters();
                buffer = new char[imageHeight][imageWidth];
                getImage();
                printImage();
                a = askPermission();}
        }
        //else if (a == false) {
            System.out.println("Goodbye!");

        //}

    }



    /*
    FUNCTION NAME: askPermission ;
    INPUT: none.
    OUTPUT: a message to the user of this program.
    PRECONDITIONS:  output set to start on a new line.
    POSTCONDITIONS: variable response has user's answer stored in it.
    CALLERS: the main program
    CALLES: None.

     */

    public static boolean askPermission()
    {
        System.out.println("Would you like to print an image in a file?");
        System.out.println("If yes, type 'y'. If no, type 'n'");

        in2 = new Scanner(System.in);
        String Ans = in2.nextLine();
        if (Ans.equals("y")){
        return true;}

        else {
        return false;
        }
    }


    /*
   FUNCTION NAME getParameters ;
   INPUT: the file name, number of tiles across and down.
   OUTPUT: message "Getting Image".
   PRECONDITIONS: the variable response has 'y' in it.
   POSTCONDITIONS: variables set with the values entered by user.
   CALLERS: the main program
   CALLEES: none
     */

    static void getParameters() throws FileNotFoundException
    {   
        inFile = new Scanner(new File(fileName));
        imageHeight = (inFile.nextInt());  
        imageWidth = (inFile.nextInt());

    }

    /*
    FUNCTION NAME: getImage ;
    INPUT:the file name and the height and width of the pattern to be made.
    OUTPUT: the message "Getting Image".
    PRECONDITIONS: array for image declared, the variables fileName, 
                   imageHeight and imageWidth set with proper values.  
    POSTCONDITIONS: the image is stored in the array.
    CALLERS: the main program
    CALLEES: none
     */
    public  static void getImage() throws FileNotFoundException
{   
    String string = "";
    input = new Scanner(new File(fileName));

        {
        for (int n = 0; n<(imageHeight);) 
        {  

            string = input.nextLine();
            char[] charArray = new char[n];
            string = string + input.nextLine();
            charArray = string.toCharArray();       
            System.out.println(charArray[n]);
            char q = charArray[n];
            buffer[n][0] = (q);


            for(int p = 1; p<(imageWidth); p++) 
            {

                char[] charArrayW = string.toCharArray();       
                char a = charArrayW[p];
                buffer[n][p] = (a);

            }
           n=n+1;
        }
    }
}








    /*
    FUNCTION NAME: printImage
    INPUT:the buffer with the image and the height and width of the
          pattern to be made
    OUTPUT: the patterns structured according to users input.
    PRECONDITIONS: All of the variables are set and pattern is stored in 'buffer'.
    POSTCONDITIONS: Output displayed according to users input.
    CALLERS: the main program
    CALLEES: none
     */
    //  This function uses for loops to display the images. The inner most for loop prints one line of the picture.


    public  static void printImage()
    {
        for ( int i=0; i<imageHeight; i++) {
            System.out.print (buffer[i][0]);
            //System.out.println();
            for(int j=0; j<imageWidth; j++) 
                System.out.print (buffer[i][j]);
                System.out.println();}
    }
    }

Right now it seems like I am so close. The problem I'm getting is that in getImage() I'm receiving a "No line found" exception at line 126. It prints a very small amount of the file, just a few characters on the first vertical line.

You have several problems in your getImage method. First, you should skip the first line from the file which contains width/height. Second you are reading the line (call input.nextLine() twice per loop iteration), so effectively you need 2*imageHeight lines. No wonder you cannot read them correctly. Next, you concatenate the string for some reason with previous string ( string = string + input.nextList() ). It's completely unnecessary. Next I see meaningless to extract n-th character from the line in char q = charArray[n] and print it. The n variable is the row number, while charArray indices correspond to the columns! Also no need to call toCharArray() on every nested loop iteration. Finally you need to close files using try-with-resources statement. Here's the fixed code:

public static void getImage() throws FileNotFoundException {
    String string = "";
    try(Scanner input = new Scanner(new File(fileName)))
    {
        input.nextLine(); // skip width/height
        for (int n = 0; n < (imageHeight);) {

            string = input.nextLine();
            char[] charArray = string.toCharArray();

            for (int p = 0; p < (charArray.length); p++) {

                char a = charArray[p];
                buffer[n][p] = (a);

            }
            n = n + 1;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM