I'm trying to figure out how I can write this method to avoid the stack buildup from recursively calling the method in the exception?
Here is the wording of my instructions:
Read a number, use an exception handler to make sure it is an int number and then add to the ArrayList object, aryList.
Here is my attempt:
public void createOriginalAryList() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number: ");
try {
int number = keyboard.nextInt();
aryList.add(number);
while(keyboard.hasNextInt()) {
System.out.println("Enter a number: ");
number = keyboard.nextInt();
aryList.add(number);
}
} catch(InputMismatchException ime) {
System.out.println("Invalid number submitted! Try again.");
createOriginalAryList();
}
System.out.println(aryList);
}
Any suggestions are greatly appreciated!
Simply use a do-while loop:
Scanner keyboard = new Scanner(System.in);
boolean redo = false;
do {
System.out.println("Enter a number: ");
redo = false;
try {
int number = keyboard.nextInt();
aryList.add(number);
while(keyboard.hasNextInt()) {
System.out.println("Enter a number: ");
number = keyboard.nextInt();
aryList.add(number);
}
} catch(InputMismatchException ime) {
redo = true;
System.out.println("Invalid number submitted! Try again.");
}
}
while(redo);
System.out.println(aryList);
Since initializing the Scanner keyboard each time is useless, it is put before the loop.
Related
So basically I've been trying to get this small simple code to work but I'm running into the problem of making a loop. What I want to happen is basically this: User enters an Integer, if its not an integer it will display an error and ask for an Integer until and Integer is given. I'm having a difficult time setting up a loop cause I don't quite know what to do. Im pretty new and dumb so this is probably really easy but I'm kind of an idiot and suck at this but I'm learning.
Here's what I have.
import java.util.Scanner;
public class Loop{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
}
else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
}
else {
System.out.println("Error: Index is not Integer.");
}
}
}
You can use while loop for that.
while (true) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
break;
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
}
You need to use a loop (for or while) to your code. You can do it like this.
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
scan.nextLine();
System.out.println("Index = " + Index);
} else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
} else {
System.out.println("Error: Index is not Integer.");
}
// add same condition to break the loop
}
// close the scanner
scan.close()
}
}
How do I change this while(true) into a do while so when the user enters a number they will be given back details but if they enter * the system will close.
while (true){
System.out.print("Enter number: ");
int option = keyboard.nextInt();
out.writeInt(option);
char option;
do {
System.out.print("Enter number: ");
option = keyboard.nextChar();
out.writeChar(option);
} while (option != '*')
You may want to use nextLine() or next() to receive the input and parse them accordingly:
do{
System.out.print("Enter number: ");
String str = keyboard.nextLine();
int option = 0;
if(str.matches"[0-9]+"){
option = Integer.parseInt(str);
System.out.println(option);
}
else if(str.equals("*"))
System.exit(0); //or use break; if you want to exit the loop
}while(whatever); //whatever == true
If you change it to allow the user to input a String and then convert to int if possible, you can catch any errors and break out if the user enters a '*' character:
import java.util.*;
class MainInput{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int option;
String input;
do{
System.out.print("Enter number: ");
input = keyboard.nextLine();
try{
option = Integer.parseInt(input);
System.out.println("You entered the value: " + option);
}
catch(Exception ex) {
if (!input.equals("*")){
System.err.println("Invalid input, please enter numbers only.");
}
}
}while(!input.equals("*"));
}
}
If you use an exit value like (-1), you can continue to process input with nextInt() and becomes even easier. You can do this with a simple do/while:
import java.util.*;
class MainInput{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int option = 0;
do{
System.out.print("Enter number: ");
option = keyboard.nextInt();
System.out.println("You entered the value: " + option);
}while(option != -1);
}
}
do{
System.out.print("Enter number: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
}while(!str.equals("*"))
edit: if you want to play with numbers as integer or double. Just let me know and I'll add casted version as your needs.
int number;
do{
System.out.print("Enter number: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
number = Integer.parseInt(str);
}while(!str.equals("*"))
now you have a integer number.
package exercises;
import java.util.*;
public class Try_and_catch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x=1;
do
{
System.out.println("Enter first number");
int n1 = input.nextInt();
System.out.println("Enter second number");
int n2 = input.nextInt();
int sum= n1/n2;
System.out.println(sum);
} while(x==1);
}
}
The code above requires input only integers, my question is how to handle the error whenever the user input a character?
Use a try block:
boolean again = true;
int n1;
while (again) {
try {
System.out.println("Enter first number");
input.nextInt();
again=false;
}
catch(InputMismatchException ime)
{
// do nothing!
}
}
What happens here is pretty simple: if we get an exception, then "again" is not set to true and we go back around in the loop. If we get out of the try block without an exception, then again is toggled and we go merrily on our way.
I want the user to enter a number which is scanned by the following code:
scanner.nextInt();
If a user enters a string instead, the program throws InputMismatchException, which is obvious. I want to catch the exception in such a way that the program prompts the user to enter an input until the user enters an integer value.
Scanner scanner = new Scanner(System.in);
while(true) {
try {
System.out.println("Please enter a number: ");
int input = scanner.nextInt();
System.out.println(input);
//statements
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
continue;
}
}
This code creates an infinite loop if a string is entered.
The answer to my problem is as follows:
Scanner scanner = new Scanner(System.in);
while(true) {
try {
System.out.println("Please enter a number: ");
int input = scanner.nextInt();
System.out.println(input);
//statements
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
scanner.next();//new piece of code which parses the wrong input and clears the //scanner for new input
continue;
}
}
Put Scanner scanner = new Scanner(System.in); within your while loop.
Scanner scanner;
while(true) {
try {
System.out.println("Please enter a number: ");
scanner = new Scanner(System.in);
int input = scanner.nextInt();
System.out.println(input);
//statements
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
System.out.println("I said a number...");
}
}
How about this?
while(true) {
try {
System.out.println("Please enter a number: ");
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
System.out.println("\n\nEntered number is : " + input);
break;
} catch(InputMismatchException | NumberFormatException ex ) {
System.out.println("\n\nInput was not a number. Please enter number again : ");
} catch(Exception e ) {
System.out.println("\n\nException caught :: " + e);
}
}
I have also removed continue syntax as those are not needed.
I am trying to make a simple text based operating system and I cant figure out why my code doesn't let me enter a command after the calculator class is done. It is supposed to continue executing the code until I type "off" but this is not the case. Eclipse says it is running but I cant do anything. can someone please help me?
here is my two classes:
public class Calculator extends Start{
public static void calStrt() {
System.out.print("\nEnter operator you wish to use: ");
StringInput = scan.nextLine();
if (StringInput.equals("+")) {
add();
} else if (StringInput.equals("-")) {
sub();
} else if (StringInput.equals("*")) {
mul();
} else if (StringInput.equals("/")) {
div();
} else {
System.out.println("\nSyntax error: Operator not recognized");
System.out.println("Please try again");
calStrt();
}
}
public static void add() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 + intVar2));
}
public static void sub() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 - intVar2));
}
public static void mul() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 * intVar2));
}
public static void div() {
System.out.print("\nEnter first number: ");
intInput = scan.nextInt();
int intVar1 = intInput;
System.out.print("\nEnter second number: ");
intInput = scan.nextInt();
int intVar2 = intInput;
System.out.println("\nAnswer: " + (intVar1 / intVar2));
}
}
import java.util.Scanner;
class Start {
static Scanner scan = new Scanner(System.in);
static String StringInput;
static int intInput;
public static void main(String[] args) {
System.out.println("\nWelcome to RobOS");
passLoop: while (true) {
System.out.print("\nPlease enter password: ");
StringInput = scan.nextLine();
if (StringInput.equals("banana")) {
System.out.print("Logging in, please wait");
System.out.print(".");
System.out.print(".");
System.out.println(".");
System.out.println("\nWelcome User");
outerLoop: while (true) {
System.out.println("\nType \"help\" to see a list of programs");
StringInput = scan.nextLine();
innerLoop: while (true) {
if (StringInput.equalsIgnoreCase("cal")) {
Calculator.calStrt();
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("guess")) {
GuessGame.guess();
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("help")) {
System.out.println("\n\"cal\" uses the calculator");
System.out.println("\"guess\" plays guessing game");
System.out.println("\"help\" shows list of programs");
System.out.println("\"off\" turns RobOS off");
continue outerLoop;
} else if (StringInput.equalsIgnoreCase("off")){
break passLoop;
}
}
}
} else {
System.out.println("\nWrong password. Please try again");
continue passLoop;
}
}
}
}
Brent Nash is correct. To fix the error though, try using instead of scan.nextInt(): Integer.parseInt(scan.nextLine());
Hope this works
Your code is getting into an infinite loop. When you call StringInput = scan.nextLine(), the first time it works fine. I entered cal and I can run the calculator once. The problem is that the second time scan.nextLine() gets called, it's automatically returning an empty string "" as the value of StringInput. Your set of if/else statements in the while(true) have no way to handle this, so it just loops forever.
The deeper rationale is that you call scan.nextInt() to read in the numbers, but the problem is when you read in the second number for the calculator operation, there's still a "\n" sitting on System.in. As a result, when you loop around and call scan.nextLine() again, it doesn't prompt you for anything because it just reads that "\n" that's still sitting on System.in and then that sends you into an infinite loop.