Reading from the command line in java

时间:2016-02-12 20:14:07

标签: java input command arguments

I am trying to read in values from the command line into variables, using the code below.

Node

When I use the input "" 159 13 "Hello"

I get the following error:

public static void main (String [] args) throws Exception
{

    // Read in all of the passed arguments                     
    String address = args[0];
    int port =
        Integer.parseInt(args[1]);
    int code =
        Integer.parseInt(args[2]);
    String msg = args[3];

}

Which relates to the line Exception in thread "main" java.lang.NumberFormatException: For input string: "Hello" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at client.main(client.java:15)

Does anyone know what needs to be changed here?

3 个答案:

答案 0 :(得分:0)

You'll need to find a way to parse your String ("Hello"); the first thing that comes to my mind would be that you need to catch your Exception (see Alvin Alexander's page on doing just that in converting a String to an int).

The <!DOCTYPE html> <html> <head> <style> div{border: 1px solid black} html, body{height: 100%; width: 100%;} #container1{ width: 100%; height: 100%; display: flex; flex-flow: row wrap; } #subContainer3, #subContainer2{ flex: 1 49%; } #subContainer1{ flex: 1 100%; } .content{ background-color: lightgray; height: 90%; } </style> </head> <body> <div id="container1"> <div id="subContainer1"> <div class="content"></div> </div> <div id="subContainer2"> <div class="content"></div> </div> <div id="subContainer3"> <div class="content"></div> </div> </div> </body> </html> would in this case encapsulate the try{} and int port declarations. int code would belong underneath the try, of course.

However, in your example, it appears that you're possibly parsing the 159 as a String (catch{} would map to the first argument of the input), then "13" is being parsed correctly as an Integer to the args[0] variable, and lastly your code is getting hung up on trying to parse port as an integer (using "Hello") where you expect it to be mapped to args[2] in the args[3] declaration.

Don't forget that Java uses zero indexing! Your code is looking for the following types:

msg, String, int, int

So if you want to handle situations where a user inputs something other than those types, use a String try{}.

Here's a few links to some relevant documentation on the catch{} try{}:

try{}, catch{}, and a simple guide to exception handling.

Hope this helps!

答案 1 :(得分:0)

As the other answer states, you need exception handling. Think about what you want to happen when invalid input is entered and handle it accordingly. Any particular reason in your example the method throws instead of using try-catch like below?

step

答案 2 :(得分:0)

您不能将“ Hello”转换为错误的整数

第三个输入是整数,然后第四个输入是字符串