【问题标题】:Asking user for multiple input询问用户多个输入
【发布时间】:2014-03-21 22:26:52
【问题描述】:

我正在尝试编写一个程序,该程序将不断向用户询问整数,直到他们输入一个不是整数的值,此时程序停止。

这是我目前所拥有的:

import java.util.Scanner;
import java.util.ArrayList;

public class InputStats {
    private static Scanner a;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        ArrayList InputArray = new ArrayList();
        Boolean Running = true;
        System.out.println("Please type an integer. To stop enter a non integer value");
        while (Running) {
            a = Scanner.nextLine();
            if (!a.hasNextInt()) {
                Running = false;
            }
            else {
                InputArray.add(input.nextLine());

        }

            System.out.println(InputArray);
        }

    }
}

但是,使用此代码,我收到了错误:

error: non-static method nextLine() cannot  be referenced from a static context (for the line a = Scanner.nextLine();)

error: incompatible types (for the line a = Scanner.nextLine();)

可能是什么问题?

【问题讨论】:

  • 有命名约定,变量以小写字符开头,类以大写字母开头。这样代码就更容易阅读了。

标签: java java-io


【解决方案1】:
String str = input.nextLine();

您根本不需要 Scanner a。只需将所有对它的引用替换为对 input 的引用即可。

【讨论】:

  • 非常感谢,非常感谢。
【解决方案2】:

我通过创建一个函数来查看字符串是否为数字来实现这一点。

import java.util.ArrayList;
import java.util.Scanner;

public class InputStats {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        ArrayList<Integer> inputArray = new ArrayList<Integer>();
        System.out.println("Please type an integer. To stop enter a non integer value");
        boolean canContinue = true;
        String a;
        while(canContinue) {
            a = input.next();
            if(isNumeric(a) == true) {
                int b= Integer.parseInt(a);
                inputArray.add(b);
            }
            else {
                canContinue = false;
            }

        }

        System.out.println(inputArray);
        input.close();
    }

    public static boolean isNumeric(String str) {
        try {
            int d = Integer.parseInt(str);
        }
        catch(NumberFormatException nfe) {
            return false;
        }
        return true;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-18
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多