Search code examples
javaarraysfileloopstext

how to read 1 line of numbers and convert it to an array with all consecutive ints java?


I have 2500 text files that all need to be read in these 4 for loops. the first 2 for loops are for looping trough the 2500 files named: 1_1.txt, 1_2.txt and so on to 1_50.txt and then it goes on like this: 2_1.txt, 2_2.txt etc...

The other 2 for loops are for drawing a square of 16X16 pixels. the colors of these pixels are being determined by the numbers in the text files which all have 1 row of 256 numbers.

 color(number)

returns the color it should be. somehow the array returns all random numbers between 47 and 52 which are not stated in any text file.

I want it to read all the numbers 1 by 1 and store it into an int array because the char array is not doing the trick.

int counter = 0;
for(int plotZ = 1; plotZ < 50; plotZ ++)
{
    for(int plotX = 1; plotX < 50; plotX ++)
    {
        String theString = "";
        String filename = "maps/" + plotX + "_" + plotZ + ".txt";
        File file = new File(filename);
        Scanner scanner;
        char[] charArray = null;
        try {
            scanner = new Scanner(file);
            theString = scanner.nextLine();
            while (scanner.hasNextLine()) {
                theString = theString + "\n" + scanner.nextLine();
                
                charArray = theString.toCharArray();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
        counter = 0;
        for(int blockX = plotX * 16; blockX < plotX * 16 + 16; blockX ++)
        {
            for(int blockZ = plotZ * 16; blockZ < plotZ * 16 + 16; blockZ ++)
            {
                int number = charArray[counter];
                g2d.setColor(color(number));
                g2d.drawLine(blockX, blockZ, blockX, blockZ);
                counter ++;
            }
        }
    }
}

Solution

  • You're reading the text file as a character array so you're getting the ASCII character values of the numbers when you read it them as ints (e.g. 0 = 48, 4 = 52). You should parse each integer character from the line in the text file.