Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a File character by character then putting them into a for loop pattern in java

Tags:

java

I am currently working on a small for-loop pattern and I stumbled upon a road block in my project. Basically, what I want is to make a for loop pattern from my .java file that reads the source char by char and replace the asterisks in my current for-loop pattern:

Into something like this

enter image description here

Here's the current code that I have that does the for-loop pattern

for( i = 1; i <= 5; ++i, z = 0) { // first line
    for(int space = 1; space <= segments - i; ++space) {
        System.out.print("  ");
    }

    while(z != 2 * i - 1) {
        System.out.print("* ");
       z++;
    }

    System.out.println();
}   
for( i = 1; i <= 10; ++i, z = 0) { // second line
    for(int space = 1; space <= segments - i; ++space) {
        System.out.print("  ");
    }

    while(z != 2 * i - 1) {
        System.out.print("* ");
       z++;
    }

    System.out.println();
} 

Thanks in Advance!

like image 661
an hero Avatar asked Nov 06 '22 21:11

an hero


1 Answers

This is sample for how you can read a file char by char,

try {
    BufferedReader r=new BufferedReader(new FileReader("file.txt"));
    int ch;
    while((ch=r.read())!=-1){
        System.out.print((char)ch);
    }
} catch(Exception e) {
    System.out.print((char)ch);
}

To implement it in your code, just put this while loop in your while loop of asterisk's.

like image 71
Saurabh Narhe Avatar answered Nov 14 '22 23:11

Saurabh Narhe