Making a main method repeat after catching an exception - java

This program takes in an integer and returns the number of digits within that integer. I noticed that I was unable to take very big numbers, so I decided to use the BigInteger class. All was good until I realized I needed the user to input a valid integer if they use incompatible input (like a string). How do I make the main method repeat after the catch statement, so no matter how many times you use bad input it request another input? I know that I shouldn't exit the program.
//This class test the recursive method to see how many digits are in a number
public class TestDigits {
public static void main(String[] args) {// main method to test the nmbDigits method
Scanner intInput = new Scanner(System.in);
try{
System.out.println("Input an integer number:");
BigInteger number = intInput.nextBigInteger() ;
System.out.println(nmbDigits(number));}
catch (InputMismatchException ex){
System.out.println("incorrect input, integer values only.");
System.exit(1);}}
static BigInteger nmbDigits(BigInteger c) {//nmbDigits method takes input from user and returns the number of digits
long digits = 0;
if (c.divide(BigInteger.valueOf(10l)) == BigInteger.valueOf(0l)){
digits++;
}
else if (c.divide(BigInteger.valueOf(10l)) != BigInteger.valueOf(0l)){
digits++;
BigInteger remainingValue = c.divide(BigInteger.valueOf(10l));
BigInteger g = nmbDigits(remainingValue);
digits += g.longValue();}
return BigInteger.valueOf(digits);}}

You can loop :
public static void main(String[] args) {// main method to test the nmbDigits method
boolean exit=false;
Scanner intInput = new Scanner(System.in);
while (!exit) {
try{
System.out.println("Input an integer number:");
BigInteger number = intInput.nextBigInteger() ;
System.out.println(nmbDigits(number));
exit=true;
}
catch (InputMismatchException ex){
System.out.println("incorrect input, integer values only.");
}
}
}

Somewhat like this pseudocode would do:
main(args) {
input = null;
do {
input = getInput();
} while(!valid(input);
solveAlgorithm(input);
}

Related

Binary to Decimal calculator InputMismatchException

My goal is to create a simple binary to decimal calculator. I try to go about this by first having the user input a string of the binary value they are trying to calculate and later use the length of this string to run a for loop (as seen in the code below). The calculator appears to work fine but fails when the user enters a binary number (of all 1's) longer than 20 digits. I receive a java.util.InputMismatchException error and I don't know how to fix it.
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a binary number to convert to decimal: ");
long binaryNum = scan.nextLong();
System.out.println(binaryConverter(binaryNum));
scan.close();
}
public static long binaryConverter(long binaryNum) {
String binaryString = Long.toString(binaryNum);
long decimalValue = 0;
for(int i = 0; i < binaryString.length(); i++) {
if((binaryNum%10) == 0) {
binaryNum = binaryNum/10;
} else if((binaryNum%10) == 1) {
decimalValue += Math.pow(2, i);
binaryNum = binaryNum/10;
} else {
System.out.println("This isn't a binary number. Please try again.");
break;
}
}
return decimalValue;
}
}
The way you want to do this to use scanner.nextLong(2) where 2 is the radix. Then you will be reading in an actual binary number.
long number = scanner.nextLong(2);
System.out.println(number);
produces
144115188075855871
for input of
111111111111111111111111111111111111111111111111111111111
If I understood you correctly you always want to convert the binary input to a decimal value. A very simple solution would look like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a binary number to convert to decimal: ");
final String input = scan.next();
System.out.println(Integer.parseInt(input, 2));
scan.close();
}
If you are interested how it works under the hood, take a look at the java source for Integer.parseInt.

How would i do input validation?

Tells the user if the number entered is even or even. I need help with the input validation. The validation i need do is that the user cannot entered anything but a number. Trying to do the validation without the try and catch method.
import java.util.Scanner;
public class oddoreven {
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
//declaractions
int num;
//while loop
do{
System.out.println("PLease enter a number to see whether it is even or odd. To end tyype in -99.");
num = input.nextInt();
// input valid
}while(num != -99); // loop ends
// begins the method
public static void is_odd_or_even_number(int number){
int rem = number%2;
\
You can call Scanner.hasNextInt() to determine if the next input is an int (and consume anything else). Also, you might make an infinite loop and break when the input is -99 (or 99, your code tests for 99 but your prompt says -99). Finally, you should call your method. Something like,
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
do {
System.out.println("Please enter a number to see whether it is "
+ "even or odd. To end type in -99.");
if (input.hasNextInt()) {
num = input.nextInt();
if (num != -99) { // <-- directions say -99.
is_odd_or_even_number(num);
} else {
break;
}
} else {
System.out.printf("%s is not a valid int.%n", input.nextLine());
}
} while (true);
}
You can use Scanner.nextLine() to get a string input. Then loop through the characters to make sure they are all digits. (assuming non-negative integers only)
string rawInput = input.nextLine();
boolean validInput = true;
for (char c : rawInput) {
if (!Character.isDigit(c)) {
validInput = false;
break;
}
}
if (validInput) {
int num == Integer.parseInt(rawInput);
// proceed as normal
}
else {
// invalid input, print out error message
}
You can use regex to check whether all the characters of string entered by user are digits or not,
num.matches("[0-9]+") // return true if all characters are digits
or
num.matches("^[0-9]*$") // return true if all characters are digits
but before that change your num = input.nextint() to num = nextLine() and make num as String. if you dont do this there is no need of validating user input as you are requiring.

Why wont this program allow me to divide

I noticed I could not find the digits in really large numbers. I decided to use biginteger to solve this problem however it will not let me divide them. I also turned one of the divisions into the big int dividion method but still it gives me a red flag. can anyone help me figure out why this is happening? the divide method is not working also. I changed one division to the divide method and left the rest as regular divisions.
//This class test the recursive method to see how many digits are in a number
public class TestDigits {
public static void main(String[] args) {// main method to test the nmbDigits method
Scanner c = new Scanner(System.in);
try{
System.out.println("Input an integer number:");
BigInteger number = c.nextBigInteger() ;
System.out.println(nmbDigits(number));}
catch (InputMismatchException ex){
System.out.println("incorrect input, integer values only.");
System.exit(1);}}
static BigInteger nmbDigits(BigInteger c) {//nmbDigits method takes input from user and returns the number of digits
int digits = 0;
if (c.divide(10) == 0){
digits++;}
else if (c / 10 != 0){
digits++;
BigInteger count = c/10;
do {
count = count/10;
digits++;}
while (count != 0);}
return digits;}
}
You can't use the division operator / on instances of BigInteger. This operator only works for primitive numerical types. That's why the BigInteger class has a divide method.
BigInteger result = c.divide(new BigInteger("10")); would work.
public class TestDigits {
public static void main(String[] args) {// main method to test the nmbDigits method
Scanner c = new Scanner(System.in);
try{
System.out.println("Input an integer number:");
BigInteger number = c.nextBigInteger() ;
System.out.println(nmbDigits(number));}
catch (InputMismatchException ex){
System.out.println("incorrect input, integer values only.");
System.exit(1);}}
static BigInteger nmbDigits(BigInteger c) {//nmbDigits method takes input from user and returns the number of digits
long digits = 0;
if (c.divide(BigInteger.valueOf(10L)) == BigInteger.valueOf(0L)){
digits++;}
else if (c.divide(BigInteger.valueOf(10L)) != BigInteger.valueOf(0L)){
digits++;
long count = (c.divide(BigInteger.valueOf(10L))).longValue();
do {
count = count/10;
digits++;}
while (count != 0);}
return BigInteger.valueOf(digits);}
}

Using nextLine() and nextInt() together in my context always gets an error

I'm writing some Java code that'll make a guessing game, where a random number is generated based on your maximum value and you have to guess the correct number. You can also set the amount of attempts you can get. This is where the problem occurs.You see, you can set a number of attempts in number form or write out "unlimited". I have an example of the code that does this here with comments to help you out:
import java.util.Scanner;
public class Game{
public static int processMaxAttempts;
public static Scanner maxAttempts;
public static String processMaxAttempts2;
public static void main(String args[]){
//Prints out text
System.out.println("Fill in your maximum attempts OR write \"unlimited\".");
//Creates a scanner
maxAttempts = new Scanner(System.in);
//Looks at the scanner "maxAttempts" and reads its integer value
processMaxAttempts = maxAttempts.nextInt();
//Looks at the scanner "maxAttempts" and reads its string value
processMaxAttempts2 = maxAttempts.nextLine();
//Prints out "unlimited" if "maxAttempts" has a string value and "set" if it has an integer value
if(processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}//Close else
}//Close main method
}//Close class
What happens is a get an error that says this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:857)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at com.pixelparkour.windows.MainGameWindow.main(MainGameWindow.java:34)
That error targets this line of code:
processMaxAttempts = maxAttempts.nextInt();
So... yeah. I have no idea. I'm very new to Java (I've been learning it for only 3 days) and I'm a bit helpless. I'd love to know what my problem is so I can apply to it the future and program some cool games!
You need to put a check on content type before reading the content.
What you need is :
if(maxAttempts.hasNextInt()){ // this will check if there is an integer to read from scanner
processMaxAttempts = maxAttempts.nextInt();
} else {
processMaxAttempts2 = maxAttempts.nextLine();
}
if(processMaxAttempts2!=null && processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}
I think this is what you are looking for
public class Test
{
private int guessableNumber;
private Integer maxAttempts;
public Test()
{
maxAttempts = 0;
}
public void doYourStuff(){
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("Please enter your amount of guesses or type unlimited for unlimited guesses");
String s = scan.next();
if(s.toUpperCase().equals("UNLIMITED")){
guessableNumber = random.nextInt(100);
}
else {
try{
maxAttempts = Integer.parseInt(s);
guessableNumber = random.nextInt(100) + Integer.parseInt(s);
}catch(Exception e){
System.out.println("You did not enter a valid number for max attempts");
}
}
int counter = 0;
System.out.println("Type in a guess");
while(scan.nextInt() != guessableNumber && counter <=maxAttempts){
System.out.println("You did not guess correctly try again");
++counter;
}
if(counter > maxAttempts){
System.out.println("You have exceeded your max attempts");
}
else {
System.out.println("Correct you guessed the correct number: "+ guessableNumber);
}
}
public static void main(String[] args)
{
Test test = new Test();
test.doYourStuff();
}
}
One little trick that always works for me is just going ahead and making a second scanner, i.e. num and text, that way you can always have one looking for int values and the other dealing with the Strings.

How do I check to see if the input is an integer?

Very Frustrated at my professor, because she did not teach try and catch concepts, neither did she teach us about throw exceptions either, so it is very difficult for me to do this program. The objective is to make a program where the user is asked to input an integer that prints "Hello World" that many times of the integer. The problem is I cannot check to make sure the user input is an integer. For instance, if the user chose to type a character or a double, how do I implement that into my code? And I cannot use throw exceptions or try and catch because we did not learn them yet.Thanks guys!!!
import java.util.Scanner;
public class PrintHelloWorld
{
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
int number;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
number = scan.nextInt();
System.out.print("Your integer is " + number);
int remainder = number%1;
int counts = 0;
if( number>0 && remainder == 0)
{
while(counts <= number)
{
System.out.println("Hello World!");
counts++;
}
}
else
System.out.print("Wrong, choose an integer!");
}
}
scan.hasNextInt()
will check to see if the next value in the input stream is an integer.
as such:
int number = -1;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
if (scan.hasNextInt()) number = scan.nextInt();
if (number != -1) System.out.print("Your integer is " + number);
You can use a loop and validate the input with a regex, like this:
Scanner scan = new Scanner(System.in);
String input = null;
while (true) {
input = scan.nextLine();
if (input.matches("\\d+")) {
break;
}
System.out.println("Invalid input, please enter an integer!");
}
int number = Integer.parseInt(input);
This will keep asking for input until a valid integer is entered.
And I cannot use throw exceptions or try and catch because we did not
learn them yet.
For a first attempt, you could create a method that accepts a String as parameter. You will loop through all the chars of this String and check if each char is a digit. While this method returns false, re-ask the user for a new input.
Then use Integer.valueOf to get the int value..
public static boolean isNumber(String input)
You will have to use sc.nextLine() to get the input
The method Character.isDigit and toCharArray() will be useful

Categories

Resources