0

I am trying to fill a char[][] array from a text file and I cannot seem to figure out how to do it. I've tried to use .toCharArray() but it doesn't seem to work. If you can give any insight on how to make this work that would be awesome!

String filename = "ArrayHW2.txt";
        int numTests = 6;
        char[][] testAnswers = new char[50][5];
        char[] key = new char[4];

        Scanner input = null;
        try
        {
            input = new Scanner(new File(filename));
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error Opening File");
            System.exit(1);
        }

        for(int row = 0; row < testAnswers.length; row++)
        {
            for(int col = 0; col < testAnswers[row].length; col++)
            {
                testAnswers[row][col] = input.next().toCharArray();
            }
        }
        input.close();
5
  • may we see the text file? Commented Jan 21, 2016 at 23:47
  • but it doesn't seem to work is not very descriptive. Please edit your question to add information that describes your input, expected vs actual output, errors, etc. Commented Jan 21, 2016 at 23:49
  • Whats the error you get when you try to execute that code? Commented Jan 21, 2016 at 23:50
  • T. Wielgos, is your intent to create a 2D array where each row represents a line and each column represents a character on the given line? Commented Jan 21, 2016 at 23:50
  • The text file is 6 rows and 5 columns of letters that represent answers to a true-false test Commented Jan 23, 2016 at 20:55

2 Answers 2

1

The basic problem is that you are trying to assign a character array to something was meant to hold a character. You might think of char[] type as storing the location in memory where characters are recorded, and a char type as the character itself.

When you call toCharArray() on a String, the return type is char[]. It looks like you expect this array to have a single character, like the A, B, C, or D of a multiple-choice test. You could get the first (and only?) character of that array with something like ...toCharArray()[0], but this is wasteful because a new array is created, and characters are copied into it from the source string. It's simpler to use the getCharAt() method on the String directly.

String filename = "ArrayHW2.txt";
char[][] testAnswers = new char[50][5];
try (Scanner input = new Scanner(Paths.get(filename))) {
  for(int row = 0; row < testAnswers.length; row++) {
    for(int col = 0; col < testAnswers[row].length; col++) {
      String token = r.next();
      if (token.length() != 1)
        throw new IllegalArgumentException("Answers must be one character");
      testAnswers[row][col] = token.charAt(0);
    }
  }
} catch (IOException ex) {
  System.err.println("Error reading file: " + ex.getMessage());
  System.exit(1);
}
Sign up to request clarification or add additional context in comments.

4 Comments

A char[] is not like the memory address at which a char can be found, it is an object which contains a fixed number of chars, stored contiguously in memory. Perhaps you're thinking of C where a char[] decays to a char * in certain contexts.
@erickson I understand what you mean, but I think that the explanation that an address can't fit in the 16 bits used by a char is a red herring. You can't assign a long[] to a long either, even though the size of an address probably can fit in the space taken by a long. It is sufficient to just say you can't assign an array to a primitive.
@DavidConrad I've modified that statement, but I maintain that it's useful to think of a char[] as a pointer to characters. Handles and offsets and JIT optimizations make this conceptualization imprecise, but not misleading in this context.
Fair enough, but it could be confusing if the reader has a background in C. I do think it's useful for Java programmers to know an array is an Object.
0
String filename = "ArrayHW2.txt";
        int numTests = 6;
        char[][] testAnswers = new char[50][5];
        //char[] key = new char[4];

        Scanner input = null;
        try
        {
            input = new Scanner(new File(filename));
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error Opening File");
            System.exit(1);
        }
        int counter = 0;
        while(scanner.hasNext())
        {
            copyString(testAnswers[counter], scanner.nextLine());

        }

        input.close();

its been a while i haven't code in java and im not sure about the methods but consider it a pseudo code . you can use this copy :

void copyString(char[] arr, String x)
{
   int size = x.length();
   for (int i=0; i<size; i++){
   arr[i] = x.CharAt(i);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.