I was wondering how to get a Scanner to set its value to an integer.
The reason I want to do this is because I have my program:
- reading a line of input that is only numbers,
- then takes the input, puts it into an
int, - and then uses the
Integer.toBinaryString(<name of int>);to show the number in binary
The only problem is that the name of in HAS to be an int; it can’t be a String.
Here’s my code if you need it:
package base.pkg10.to.binary.txt.converter;
import java.util.Scanner;
import static java.lang.System.out;
public class Base10ToBinaryTXTConverter {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int output;
out.println("This converts base 10 numbers to binary numbers.");
out.println("Please enter your Base 10 Number:");
out.println("Please wait...");
out.println("Your numeber in Binary is:");
out.println(Integer.toBinaryString(input));
}
}
So, you need to convert the input from the scanner to an integer?
Try:
Then you could write:
Edit: When using
Integer.parseInt, it is a good idea to catch anyNumberFormatExceptions that may arise from invalid input, e.g.Integer.parseInt("foo");will throw such an exception.