In: Computer Science
import java.util.Scanner; public class Squaring { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num=0; String s = ""; while (true) { System.out.println("Enter an integer greater than 1: "); try { // reading input s = sc.nextLine(); // converting into int num = Integer.parseInt(s); break; } catch (Exception e) { System.out.println(s + " is not valid input."); } } // Now we have a valid number // putting into square int square = num; int count = 0; // loop until it execced 1M while (square < 1000000) { // printing System.out.println(square); // couting squares count++; // squre square = square * square; } // printing result System.out.println(square); System.out.println(num + " exceeded 1,000,000 after " + count + " squarings."); } }
What can I replace the while(true) try { and catch (exception e) with? Also my program crashes when I put 1, why?
Beginner code please
Dear Student ,
As per the requirement submitted above , kindly find the below solution.
Here a new java class with name "Squaring.java" is created, which contains following code.
Squaring.java :
import java.util.Scanner;//import package
//java class
public class Squaring {
// main() method
public static void main(String[] args) {
// object of Scanner class
Scanner sc = new
Scanner(System.in);
int num = 0;// declaring variable
to store number
String s = "";
do {
System.out.println("Enter an integer greater than 1: ");
// reading
input
s =
sc.nextLine();
// converting
into int
num =
Integer.parseInt(s);
// checking
number
if (num <= 1)
{
// if number is less than or equal to 1
System.out.println(s + " is not valid
input.");
}
} while (num <= 1);
// Now we have a valid
number
// putting into square
long square = num;
int count = 0;
// loop until it exceeded 1M
while (square < 1000000) {
//
printing
System.out.println(square);
// couting
squares
count++;
// squre
square = square
* square;
}
// printing result
System.out.println(square);
System.out.println(num + " exceeded
1,000,000 after " + count + " squarings.");
}
}
======================================================
Output : Compile and Run Squaring.java to get the screen as shown below
Screen 1 :Squaring.java
Screen 2:
NOTE : PLEASE FEEL FREE TO PROVIDE FEEDBACK ABOUT THE SOLUTION.