有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组Java Scanner请求输入两次

我试图首先通过使用我编写的“计数器”方法来检测输入包含多少个数值,然后我想将这些数值添加到数组中,因此我使用“计数器”作为数组的大小。然而,我的代码需要写两次输入,而不是一次

    import java.util.Scanner;
    import java.util.Arrays;

    public class ConverterApp {

    public static void main( String[] args ) {

        System.out.print("Enter a unity to convert: ");
        Scanner theInput = new Scanner(System.in);

        double[] theValues = new double[ theCounter(theInput.nextLine()) ];

        while ( theInput.hasNextDouble() ) {

            for( int i = 0; i < theValues.length; i++ ) {

                theValues[ i ] = theInput.nextDouble();
            }

            if ( !theInput.hasNextDouble() ) {

                break;
            }

        }
        theInput.close();
        System.out.println( Arrays.toString(theValues));



    }

    public static int theCounter( String input ) {

        int count = 0;
        boolean previousDigit = false;

        for ( int i = 0; i < input.length(); i++ ) {

            if ( Character.isDigit( input.charAt( i ) ) ) {

                if ( !previousDigit ) {

                    count++;
                    previousDigit = true;

                }

            }
            else {

                previousDigit = false;
            }

        }

        return count;
    }                                                                  
}

示例输出:

Enter a unity to convert: 10 11 l
10 11 l
[10.0, 11.0]

我想看到的是:

Enter a unity to convert: 10 11 l
[10.0, 11.0]

我也是关于阵列的开放式解决方案,我指的是一种在不检测阵列大小的情况下做我想做的事情的方法或其他方法

提前感谢。:)


共 (0) 个答案