首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >java中的正方形应用程序

java中的正方形应用程序
EN

Stack Overflow用户
提问于 2018-10-19 03:23:36
回答 1查看 59关注 0票数 0

这里是编程新手。我需要编写执行以下操作的应用程序...Squaring application instructions

到目前为止,我的代码如下所示。我遇到了一个问题,我的代码不能从负整数读取字符串,也不能正确提示用户输入有效数据。我认为我需要嵌套我的循环,但我在这样做时遇到了麻烦。任何帮助都将不胜感激。谢谢。

代码语言:javascript
复制
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.") ;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-10-19 03:46:42

不带任何try-catch:

代码语言:javascript
复制
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.") ;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52881144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档