import java.text.DecimalFormat; // for formatting doubles import uwcse.io.*; /** * Practicing using loops */ public class Loops { public static void main(String[] args) { new Loops().figuresOfStars(); } /** * Check that the sum of the cubes is the square of the sum *
*
* i.e. (^ means exponentiation (not available in java))
* 1^3 + 2^3 + 3^3 + ... + n^3 = (1 + 2 + 3 + ... + n)^2
* Use a loop to allow the user to test the formula with several values of
* n. Exit the loop if n is not a positive integer.
*/
public void sum3vsSum2() {
int n;
Input input = new Input();
System.out.println("Sum of the cubes / square of the sum");
do { // Input n until n<=0
n = input.readInt("Enter an integer (<=0 to quit): ");
int sum = 0; // sum
int sumCubes = 0; // sum of the cubes
// Compute sum and sumCubes
// use a for loop
for (int i = 1; i <= n; i++) {
sumCubes += i * i * i;
sum += i;
}
if (n > 0)
System.out.println("Sum of the cubes: " + sumCubes
+ "\nSquare of the sum: " + sum * sum);
} while (n > 0);
}
/**
* Display shapes of stars
*
* In a console window, display the following shapes using for loops * *
* * * * ** ** * *** *** * **** **** ** * Allow the user to select the number of lines. Repeat the process until * the user inputs a non positive value for the number of lines. */ public void figuresOfStars() { int n; Input input = new Input(); System.out.println("Display of stars"); do { n = input.readInt("Enter a positive integer (or <=0 to quit): "); for (int j = 1; j <= n; j++) { // print j stars for (int i = 1; i <= j; i++) { System.out.print("*"); } // print 2n - 2j spaces for (int i = 1; i <= 2 * n - 2 * j; i++) { System.out.print(" "); } // print j stars for (int i = 1; i <= j; i++) { System.out.print("*"); } // next line System.out.println(); } } while (n > 0); } /** * Sum the digits of a positive integer *
* Let the user enter an integer.
* If the integer is positive, sum all of the digits of the integer. Repeat
* the process until you get a single digit answer:
* for instance, 123456 gives 21 which gives 3
* Repeat the process until the user inputs a non positive value for the
* integer.
*/
public void sumDigits() {
int n;
Input input = new Input();
System.out.println("Sum the digits");
}
/**
* Rolling a die
*
* Let the user enter an integer n. Roll a dice n times and display how many
* times each face comes out.
* Repeat the process until the user enters a non positive value for n.
*/
public void rollADie() {
int n;
Input input = new Input();
System.out.println("Roll a die");
}
}