0

I am writing a program in Java that makes use of the command line.

The program that I'm making is used by another program, the problem is that my 4th parameter has to be an int, for example 60(this is an int, it's used for calculations) for my program to work, and the program that uses it then has fixedwidth:60(this is a string) as the 4th parameter.

My question now is how is it possible to still use the 60 in calculations while not giving errors due to the program using it having a string as a 4th parameter and not an int. I have triend Integer.parseInt and Integer.ToString, but I still get the same error

Thanks in advance.

3
  • 2
    post relevant code, Integer.parseInt should be what you're looking for Commented Mar 19, 2014 at 14:48
  • 1
    Please add relevant code, the command line you are invoking it with and the error you are getting. Commented Mar 19, 2014 at 14:49
  • Is there a reason why you don't input the number alone instead of fixedwidth:60? @MichaelIT +1 for code, command line, and error. Commented Mar 19, 2014 at 14:52

2 Answers 2

1

Split the string on : and then parse the second part, like so -

String str = "fixedwidth:60";
String[] arr = str.split(":");
int val = Integer.parseInt(arr[1]);
// OR -
// int val = Integer.valueOf(arr[1]);
System.out.println(val);

Output is

60
Sign up to request clarification or add additional context in comments.

1 Comment

you can also use Integer.parseInt(arr[1]);
0

Integer.parseInt(String) and Integer.valueOf(String) both expect the input String to be just the number you want to parse. That's why you probably get a NumberFormatException when trying to parse "fixedwidth:60".

If you really need to input the whole string "fixedwidth:60", you must first extract the number from that string. You can do that with Elliott Frisch's code using String.split(":"):

String str = "fixedwidth:60";
String[] arr = str.split(":"); // arr = { "fixedwidth", "60"}
int val = Integer.parseInt(arr[1]); // arr[1] = "60", which can be parsed

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.