简体   繁体   English

Java中的系统输入无法正常工作

[英]System input in java doesn't work correctly

I'm trying to make a program that takes Ints and give me sum and I want to make it using regex. 我正在尝试制作一个使用Ints并给我加和的程序,我想使用正则表达式进行制作。 Input contains numbers, symbols and letters. 输入包含数字,符号和字母。 For example when I write: java GiveMeSum 4 2 1 -5 or java GiveMeSum 4k "2 1 !-5 program should write 2 But it not only give me wrong answer, but also doesn't read all my input. When I write: 例如,当我写:java GiveMeSum 4 2 1 -5或java GiveMeSum 4k“ 2 1!-5程序应该写2时,它不仅给我错误的答案,而且也不读我所有的输入。当我写时:

java GiveMeSum 4 2 1 -5

4 5 4 5 4 5 4 5 4 5 4 5 4 5 4 5

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at GiveMeSum.main(GiveMeSum.java:12)


public class GiveMeSum {

public static void main(String[] args) throws IOException {
    int sum = 0;
    Scanner sc = new Scanner(System.in).useDelimiter("(\\D|^-)");
    for ( int i = 0; i < args.length; i++) {
        sum += sc.nextInt();
    }
    System.out.println(sum);
}

} }

Also there wasn't that exception. 也没有那个例外。 It's just showed up suddenly 突然出现了

This happens because you pass "4 2 1 -5" not as input but as arguments so they come into args parameter of the main method. 发生这种情况是因为您传递的不是“ 4 2 1 -5”作为输入而是作为参数,因此它们进入了main方法的args参数。 To pass them as input wait till the app starts and enter them or use input stream redirection 要将它们作为输入传递,请等到应用程序启动并输入它们或使用输入流重定向

Update (code for arguments processing) 更新 (用于参数处理的代码)

How should I write it in java to take input as arguments then? 我应该如何用Java编写它以将输入作为参数呢? Is there a specific easy way? 有没有特定的简便方法?

I'd say that using arguments for non-fixed number of input params is not so good idea. 我想说,对于非固定数量的输入参数使用参数不是一个好主意。 I'd still say that using input stream is the way to go - this is what it was designed for! 我仍然要说使用输入流是要走的路-这就是它的设计目的! Also your parsing requirements are a bit umbigious. 此外,您的解析要求也有些含糊。 Still here is my attempt 仍然是我的尝试

public class Main
{
    static OptionalInt parseOnlyInt(String s)
    {
        String digitsOnly = s.replaceAll("[^0-9]", "");
        if (digitsOnly.length() == 0)
            return OptionalInt.empty();
        else
            return OptionalInt.of(Integer.parseInt(digitsOnly));
    }

    public static void main(String[] args)
    {
        int sum = Arrays.stream(args)
                .map(Main::parseOnlyInt)
                // probably in Java 9 OptionalInt::stream would be better than next 2 lines
                // see https://bugs.openjdk.java.net/browse/JDK-8050820
                .filter(OptionalInt::isPresent)
                .mapToInt(OptionalInt::getAsInt)
                .sum(); 

        System.out.println(Arrays.toString(args));
        System.out.println(sum);    
    }
}

Or if you prefer the old (non-Java-8) way here it is 或者,如果您更喜欢旧的(非Java-8)方式,那就是

public static void main(String[] args)
{
    int sum = 0;
    for (int i = 0; i < args.length; i++)
    {
        String digitsOnly = args[i].replaceAll("[^0-9]", "");
        if (digitsOnly.length() != 0)
            sum += Integer.parseInt(digitsOnly);
    }
    System.out.println(Arrays.toString(args));
    System.out.println(sum);
}

System.in is the input stream. System.in是输入流。 It only gets data after your program starts. 它仅在程序启动后获取数据。 Try looking at the args parameter to main. 尝试查看main的args参数。 That is where data is put when it is passed in at invocation time. 这就是在调用时传递数据的地方。

A simple oneliner solution to take arguments and print sum 一个简单的oneliner解决方案,用于接受参数并打印总和

public static void main(String[] args) {
    int sum = Arrays.stream(args) // Create a stream from the array
            .mapToInt(Integer::parseInt) // Parse the strings as integers
            .sum(); // Sum
    System.out.println(sum);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM