• Post Reply Bookmark Topic Watch Topic
  • New Topic

String to Int  RSS feed

 
Oleg Korsakov
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello.
It's I know simple but how to make a number from a command line:

int int1 = (int)args[0];

required: int
int int1 = (int)args[0];
^
1 error
I guess data casting has another method here
Thank you
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

Casting, in general, only tells the compiler to interpret a variable in a certain way, without actually changing the bits themselves. You can't cast a String to an int because a String is an object containing characters that represent some text, whereas an int is a binary representation of a number. The compiler can't just "pretend" that the String is an int and have it magically become one. You need to call a function to do the conversion. Java includes several in the standard API; I generally use the static method parseInt() in the Integer class:

int i = Integer.parseInt(argv[0]);

Note that if argv[0] isn't a text representation of a number, you'll get a NumberFormatException.
 
Oleg Korsakov
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, also for welcome!
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!