0

I haven't found answer to my question from anywhere else so now i need to ask it here. My small java program asks user to input a number. What is the good practice to do it? Should it read string and convert it to int or should it read int? I need to do exception handling anyway to check the value. So does it matter and what is the proper way to do it?

  • It very much depends. Are you using Scanner, or are you more properly using BufferedReader? Scanner can do the conversion for you, but a Reader allows you to do the conversion on your own. – NomadMaker Dec 16 '20 at 19:42
  • I'm using scanner to get the input. I was just curious about good coding style and practice. But i guess it doesn't matter so much. – Raine M. Dec 16 '20 at 20:01
  • @RaineM. - It's better to use `Integer.parseInt(Scanner#nextLine)`. Check [this discussion](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) to learn more about it. – Arvind Kumar Avinash Dec 16 '20 at 21:14

2 Answers2

0

in my case, this works for me. I read the string and convert it to int. Next is an example

public class Test{
  public static void main(String arg[]){
   try{
     int number = Integer.parseInt(arg[0]);
     System.out.println("Your number is " + number);
    }catch(NumberFormatException e){
     System.out.println("Enter a number");
    }catch(ArrayIndexOutOfBoundsException e){
     System.out.println("Enter a number");
   }
  }
 }
Jordy
  • 109
  • 5
0

Every thing your program reads from standard input stream or file, is by default buffer of characters, and we can see them as String. So if you need other type, you should parse that string and convert to your desired type. but some functions do that conversion and you can use from them.

like :

Scanner myInput = new Scanner( System.in );
System.out.print( "Enter first integer: " );
int a = myInput.nextInt();

for more information you can see content of this page: https://www.tutorialspoint.com/read-integers-from-console-in-java

Mohsen Bahaloo
  • 237
  • 2
  • 2