Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop not counting correctly, counting from wrong variable somehow? [closed]

Okay so, I'm making a program for my programming class and I am trying to get it so when I type the column and row, it will get an output showing a multiplication table. Here is an example for you to visualize it: Sample run output for printTable(4,6):

Example:

Now, here is my code:

 import java.util.Scanner;

 public class Pictures {

public static int row;
public static int column;
public static Scanner input = new Scanner(System.in);

public static void main(String[] args){
int x = 1;
int y = 1;

System.out.println("Input Row: ");
row = input.nextInt();
System.out.println("Input Column: ");
column = input.nextInt();

for(x = 1; x < row; x++){
    System.out.print(x * y +  "    ");

    for(y = 1 ; y < column; y++){

        System.out.print(y * x + "    ");
    }
    System.out.println();   
}   
}
}

Now, when I input the row 5, and column 5, my output looks like this:

1    1    2    3    4    
10    2    4    6    8    
15    3    6    9    12    
20    4    8    12    16

I know I am not seeing something rather simple, but I just don't understand why this is happening. If anyone could offer a suggestion, it would help a lot.

Thanks, Sully

like image 660
Sully Brooks Avatar asked Jul 20 '26 16:07

Sully Brooks


1 Answers

For learning purposes, use a debugger to understand your code.

To fix it, delete those lines:

int x = 1;
int y = 1;

and have your loops like:

for(int x = 1; x < row; x++){
    // System.out.print(x * y +  "    "); // no print needed here
    for(int y = 1 ; y < column; y++){
        System.out.print(y * x + "\t");
    }
    System.out.println(); 
}  

Here is a link to the section of the Oracle Java tutorials explaining for loops. Thank's Mike for mentioning the even spacing in the comments. Updated the code.

like image 134
jlordo Avatar answered Jul 23 '26 04:07

jlordo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!