问题
(Print a table) Write a program that displays the following table. Cast floating point numbers into integers.
a b pow(a, b)
1 2 1
2 3 8
3 4 81
4 5 1024
5 6 15625
I am having trouble conceptualizing how I can make this code simpler using loops.
public class Exercise_02_eighteen {
public static void main(String[] args) {
float a, b;
System.out.println("a b pow(a, b)");
a = 1;
b = 2;
System.out.println((int)a + " " + (int)b +
" " + (int)Math.pow(a, b));
a++;
b++;
System.out.println((int)a + " " + (int)b +
" " + (int)Math.pow(a, b));
a++;
b++;
System.out.println((int)a + " " + (int)b +
" " + (int)Math.pow(a, b));
a++;
b++;
System.out.println((int)a + " " + (int)b +
" " + (int)Math.pow(a, b));
a++;
b++;
System.out.println((int)a + " " + (int)b +
" " + (int)Math.pow(a, b));
}
}
回答1:
You can just loop over a (notice it just varies from 1 to 5) and for each a, b is a + 1
回答2:
public class Exercise_02_eighteen {
public static void main(String[] args) {
System.out.println("a b pow(a, b)");
for(int a = 1, b = 2, i = 0; i < 5; a++, b++, i++) { // <--
System.out.println((int)a + " " + (int)b + " " + (int)Math.pow(a, b)); // <--
} // <--
}
}
回答3:
Just move your print under for loop:
public class Exercise_02_eighteen {
public static void main(String[] args) {
System.out.println("a\tb\tpow(a, b)");
for (int a = 1, b = 2; a <= 5; a++, b++)
System.out.format("%d\t%d\t%d\n", a, b, (long)Math.pow(a, b));
}
}
回答4:
You do not need two variables. You can do it using a single variable as follows:
public class Main {
public static void main(String[] args) {
System.out.println("a\tb\tpow(a, b)");
for (int i = 1; i <= 5; i++) {
System.out.println(i + "\t" + (i + 1) + "\t" + (int) Math.pow(i, i + 1));
}
}
}
Output:
a b pow(a, b)
1 2 1
2 3 8
3 4 81
4 5 1024
5 6 15625
回答5:
I think the below code will help you, there are so many approaches but your question is very basic so I just show use of loop in your program.
public class Exercise_02_eighteen {
public static void main(String[] args) {
float a, b, numberOfRows = 5;
System.out.println("a\tb\tpow(a, b)");
//removed unused space and use \t : tab
a = 1;
b = 2;
for(int i=1; i< numberOfRows; i++)
{
System.out.println((int)a + "\t" + (int)b + "\t" + (int)Math.pow(a, b));
a++;
b++;
}
}
}
If you want to write for the same series you show in question then you may write code without extra variables, like below or may be take one variable if required.
public class Exercise_02_eighteen {
public static void main(String[] args) {
int i, numberOfRows = 5;
System.out.println("a\tb\tpow(a, b)");
//removed unused space and use \t : tab
for(i=1; i< numberOfRows; i++)
{
System.out.println((int)i + "\t" + (int)(i+1) + "\t" + (int)Math.pow(i, i+1));
}
}
}
来源:https://stackoverflow.com/questions/60919735/how-do-i-solve-this-java-question-of-printing-a-table-using-a-for-loop