## 如何在java中使用Squaring应用程序？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (38)

``````import java.util.Scanner;

public class Squaring {

public static int getValidInt(int greaterThan, Scanner scan) {
System.out.println("Enter an integer greater than " + greaterThan + ":" );
int input;

while ( !scan.hasNextInt() ) {
String garbage = scan.next();
scan.nextLine();
System.out.println(garbage + " is not valid input.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}

while ( !((input = scan.nextInt()) > greaterThan )) {
int garbage = input;
System.out.println(garbage + " is not greater than 1.");
System.out.println("Enter an integer greater than " + greaterThan + ":" );
}

return input;
}

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 1 ;
int total = 0;
a = getValidInt(a,scan);
int b = a;
System.out.println(a);
long n = a;
while ( n < 1000000 ) {
System.out.println(n*n);
n = n * n;
total = total + 1;
}
System.out.println(b + " exceeded 1,000,000 after " + total + " squarings.") ;
}
}``````

### 2 个回答

``````public static int getValidInt(int greaterThan, Scanner scan) {

int number = greaterThan;

do {
while (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
}
number = scan.nextInt();

if (number < greaterThan) {
System.out.println("input is: " + number + " minimum is: " + greaterThan);
}

} while (number < greaterThan);

return number;
}
``````

``````public static int getValidInt(int greaterThan, Scanner scan) {
int input = 0;
boolean valid = false;

while (!valid) {
System.out.println("Enter an integer greater than " + greaterThan + ":");

if (!scan.hasNextInt()) {
String garbage = scan.next();
System.out.println(garbage + " is not valid input.");
} else {
input = scan.nextInt();

if (input <= greaterThan) {
System.out.println(input + " is not greater than " + greaterThan);
} else {
valid = true;
}
}
}

return input;
}

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

int a = getValidInt(1, scan);
System.out.println(a);

int total = 0;
long n = a;

while ( n < 1000000 ) {
n = n * n;
System.out.println(n);
total++;
}

System.out.println(a + " exceeded 1,000,000 after " + total + " squarings.") ;
}``````