Java 扫描程序要求输入两次

时间:2021-04-21 06:37:31

标签: java arrays java.util.scanner

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

    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 个答案:

没有答案