H.Ing H.Ing - 1 month ago 23
Java Question

Create Single Integer Constant Java

How can we make SIZE used below in the code as a "Single Integer Constant", to influences how many lines should be drawn? I'm learning Java. Thanks!

for (int line = 1; line <= SIZE; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
System.out.print(line);
for (int j = 1; j <= (line - 1); j++) {
System.out.print(".");
}
System.out.println();
}

Answer

If you want to have an int that cannot be changed (a constant), use the keyword final when initializing the variable, like so:

final int SIZE = 5;

Be wary, you can't change the value of SIZE after that, so if you want to have a constant that you could change depending on the situation, this will not work. You'll just need to define a variable and then change it depending on what input you get.