Scanner debugging - java

I have some issue using Scanner
That's the problematic code:
public static void main(String[] args) {
System.out.println("Chose 1 or 2 = ");
Scanner scan = new Scanner(System.in);
byte a = scan.nextByte();
scan.close();
if (a==1) HW();
else if (a==2) {
System.out.print("Calculation program ... !\nInput Number 1st number = ");
Scanner Catch = new Scanner(System.in);
int x = Catch.nextInt();
System.out.println("");
System.out.print("Input Operand +,-,*,/ = ");
Scanner Catchc = new Scanner (System.in);
char z = Catchc.next().charAt(0);
System.out.println("");
System.out.print("Input 2nd number = ");
Scanner Catch2 = new Scanner (System.in);
int y = Catch2.nextInt();
Catch.close();
Catchc.close();
Catch2.close();
calc(x,y,z);
}
else System.out.println("Please input number 1 or 2 ");
}
}
Thats a simple calculator and i got no errors and the program didn't terminate but it do debug instead. It shows "no such element exception"
Calc method:
public static void calc(int x, int y, char z) {
int result;
result = 0;
switch (z) {
case '+': result = x + y;
case '-': result = x - y;
case '/': result = x / y;
case '*': result = x * y;
}
System.out.println("Result of " + x + " " + z + " " + y + " is..." + " " + result);
}

When working with Scanners, you should only create 1 and NEVER close them until your program is done. This is because closing a scanner closes the passed in InputStream, and this inputstream is the input of your program, so you program doesn't cant recieve anymore input after that points.
Rewrite your code to only create 1 scanner, and pass that to other functions:
public static void main(String[] args) { // TODO Auto-generated method stub
System.out.println("Chose 1 or 2 = ");
Scanner scan = new Scanner(System.in);
byte a = scan.nextByte();
if (a==1)
HW();
else if (a==2) {
System.out.print("Calculation program ... !\nInput Number 1st number = ");
int x = scan.nextInt();
System.out.println("");
System.out.print("Input Operand +,-,*,/ = ");
char z = scan.next().charAt(0);
System.out.println("");
System.out.print("Input 2nd number = ");
int y = scan.nextInt();
calc(x,y,z);
}
else
System.out.println("Please input number 1 or 2 ");
}

Related

How to use try catch to replace invalid data of user input array instead of restarting code in Java?

Whenever invalid input is entered, such as a letter, the code starts from the beginning. How do I get it so that it keeps rebuilding the code from where invalid input was entered. I want it to kick out the invalid input, and prompt the user to re-enter a valid input, and keep building it.
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
int z = 1;
do {
try {
Scanner scanner = new Scanner(System.in);
double[] myArr1 = new double[10]; //Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x=0; x<myArr1.length; x++) {
myArr1[x] = scanner.nextDouble(); //Gets user input
} //end of for
double sum1 = 0;
for(double x=0; x<myArr1.length; x++) {
sum1 += myArr1[(int) x]; //Defines sum1
} //end of for
double[] myArr2 = new double[10]; //Creates array
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int y=0; y<myArr2.length; y++) {
myArr2[y] = scanner.nextDouble(); //Gets user input
} //end of for
double sum2 = 0;
for (double y=0; y<myArr2.length; y++) {
sum2 += myArr2[(int) y];
} //end of for
System.out.println("Sum of first 10 elements is: " + sum1); //Prints sum of first 10 elements
System.out.println("Sum of second 10 elements is: " + sum2); //Prints sum of last 10 elements
}/*end of try*/catch (Exception e) { //Catches errors in user input
System.out.println("Invalid input. Try again: ");
System.out.println("");
} //end of catch
}//end of do
while(z==1);
return;
}
}
You can craft a helper method for input. It will continually prompt with the messages provided until a correct type is entered. This tends to come in handy when inputs need to be taken from different locations within the program.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double v = nextDouble(input, "Please enter a value: ", "Improper type, try again: ");
System.out.println(v);
}
public static double nextDouble(Scanner input, String prompt, String error) {
System.out.print(prompt);
// loop forever
for(;;) {
try {
double v = input.nextDouble();
return v;
} catch (InputMismatchException ie) {
input.nextLine(); // clear input buffer
System.out.print(error);
}
}
}
Here is an example from your code.
Scanner scanner = new Scanner(System.in);
String prompt = "Please enter a number: ";
String error = "Invalid input, try again";
double[] myArr1 = new double[10]; // Creates array
System.out.println("");
System.out.println("Enter 10 elements: ");
System.out.println("");
for (int x = 0; x < myArr1.length; x++) {
myArr1[x] = nextDouble(scanner, prompt, error);
} // end of for
double sum1 = 0;
for (double x = 0; x < myArr1.length; x++) {
sum1 += myArr1[(int) x]; // Defines sum1
} // end of for
Get rid of your existing try/catch blocks. And I don't know why you have a do/while since you aren't looping more than once.
or you can using while loop and a boolean value to get a number
Scanner scanner = new Scanner(System.in);
boolean bool = true;
double d ;//= scanner.nextDouble();
while(bool){
try{
scanner = new Scanner(System.in);
d = scanner.nextDouble();
bool = false;
}catch(InputMismatchException e){
System.err.println("invalid input");
}
}
I've figured it out. I had to create a boolean, but also decrement the index of the array of where the bad input was being placed (i = i-1). I also made it just one array and set the first 10 values to x and the last 10 to y to make it a little bit simpler.
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
double[] array = new double[20]; //creates array
boolean on = true; //sets value "on"
while (on) { //starts while loop
System.out.println("Enter 20 numbers: ");
System.out.println("");
for (int i = 0; i < array.length; i++) { //creates user input prompt
Scanner input = new Scanner(System.in); //gets user input
try {
array[i] = input.nextDouble(); //assigns user input to array[i]
}/*end of try*/ catch (Exception e) { //catches invalid input
System.err.println("Invalid Input. Try again: ");
i = i - 1; //decrements index of re-entered number
} //end of catch
} //end of for
double x = 0;
for (int z = 0; z < 10; z++) {
x += array[z];
} //end of for
System.out.println("Sum of first 10 numbers = " + x); //adds first 10 numbers in array and assigns them to x
System.out.println("");
double y = 0;
for (int z = 10; z < 20; z++) {
y += array[z];
} //end of for
System.out.println("Sum of last 10 numbers = " + y); //adds last 10 numbers in array and assigns them to y
on = false; //breaks while loop
} //end of while
}
}

try catch in a do while loop

The program asks for the user input for the double num 1 and double num 2
and if there is an exception I want it to ask again for the input of num 1 and num 2
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
double num1, num2;
int error = 0;
int text;
System.out.print("Enter 4 ");
text = sc.nextInt();
do{
try{
if(text == 4){
System.out.print("Enter number 1: ");
num1 = sc.nextDouble();
System.out.print("Enter number 2: ");
num2 = sc.nextDouble();
double quotient = num1/num2;
System.out.println("The Quotient of "+num1 + "/" +num2+ " = "+quotient);
}
}catch(Exception ex){
System.out.println("You've entered wrong input");
error = 1;
}
}while(error == 1);
}
then when I try the code if it will catch the exceptions by inputing string in the num1 or num 2 I'm having this infinite loop :
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
You need to reset the error variable inside the loop
do {
error = 0;
//...
} while(error == 1);
It is not necessary to utilize exception handling. Just use Scanner.hasNextDouble() method to find out if actual user input is double, otherwise continue the cycle.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double num1, num2;
num1 = readDouble(1, sc);
num2 = readDouble(2, sc);
double quotient = num1/num2;
System.out.println("The Quotient of " + num1 + "/" + num2 + " = " + quotient);
}
private static double readDouble(int i, Scanner sc) {
while (true) {
System.out.print("Enter number " + i + ": ");
if (!sc.hasNextDouble()) {
System.out.println("You've entered wrong input");
sc.next();
continue;
}
break;
}
return sc.nextDouble();
}
}
Its in C# but relatively similar :)
public class Program
{
private static double ReadUserInput (string message)
{
// This is a double
// The '?' makes it nullable which is easier to work with
double? input = null;
do
{
// Write message out
Console.Write(message);
// Read answer
var inputString = Console.ReadLine();
// Temp variable for the number
double outputNumber = 0;
// Try parse the number
if (double.TryParse(inputString, out outputNumber))
{
// The number was parsable as a double so lets set the input variable
input = outputNumber;
}
else
{
// Tell the user the number was invalid
Console.WriteLine("Sorry bud, but '" + inputString + "' is not a valid double");
}
}
while (input == null); // Keep running until the input variable is actually set by the above
// Return the output
return (double)input;
}
public static void Main()
{
// Read a number
var num1 = ReadUserInput("Enter number 1:");
// Read another number
var num2 = ReadUserInput("Enter number 2:");
// Show the calculation
Console.WriteLine("Answer: " + (num1*num2));
}
}
Demo
And for the actual code (in JAVA):
public class JavaFiddle
{
public static void main (String[] args)
{
// Read a number
Double num1 = ReadUserInput("Enter number 1:");
// Read another number
Double num2 = ReadUserInput("Enter number 2:");
// Show the calculation
System.out.println("Answer: " + (num1*num2));
}
public static Double ReadUserInput (String message)
{
java.util.Scanner inputScanner = new java.util.Scanner(System.in);
Double input = null;
do
{
// Write message out
System.out.println(message);
// Read answer
String inputString = inputScanner.nextLine();
try
{
// Try parse the number
input = Double.parseDouble(inputString);
}
catch (NumberFormatException e)
{
// Tell the user the number was invalid
System.out.println("Sorry bud, but '" + inputString + "' is not a valid double");
}
}
while (input == null); // Keep running until the input variable is actually set by the above
// Return the output
return input;
}
}
You probably want to test if there is no error:
}while(error != 1);
or
}while(error == 0);
You'll need a method for the input which calls itself, if the input is invalid.
double getInput(Scanner sc) {
try {
double num = sc.nextDouble();
return num;
} catch(Exception ex) {
System.out.println("You've entered wrong input");
return getInput(sc);
}
}
And call this method twice in your other method.
it may look ugly , but here is a way to do it
do
{
if(...)
{
boolean successReading = false;
while(!successReading)
{
try
{
System.out.print("Enter number 1: ");
num1 = sc.nextDouble();
System.out.print("Enter number 2: ");
num2 = sc.nextDouble();
successReading = true;
double product = num1*num2;
}
catch(Exception e)
{
successReading = false;
}
}
}
}while(...)
You need to add sc.next(); inside catch block.
nextDouble method doesn't clear buffer in case of exception. So next time you invoke it you get same error because old input is still in buffer.
Also you need to reset your error flag in the beginning of the loop.
You have to put sc.next(); in the catch so it will clear your scanner variable and it will ask for an input

Generating multiplication questions in Java

The code should output a table for Farenheit and Celsius
public static void main(String[] args) {
System.out.println("Fahrenheit\tCelsius");
System.out.println("=======================");
for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
{
System.out.printf("%5d |", temp);
double sum = (temp + (9.0/5.0)) * 32;
System.out.printf("%5d", (int)sum );
System.out.println();
You need to add a do while() loop to continue with the questions, for example:
static Scanner input;
static Scanner scanner;
static String question;
public static void main(String[] args) {
do {
int number1 = (int) (Math.random() * 10);
int number2 = (int) (Math.random() * 10);
input = new Scanner(System.in);
System.out.print("What is " + number1 + " * " + number2 + "? ");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect. Please try again. What is "
+ number1 + " * " + number2 + "? ");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct. Nice work!");
System.out.println("Want more questions yes or no? ");
scanner = new Scanner(System.in);
question = scanner.next();
}
} while (question.toLowerCase().equals("yes") ||
question.toLowerCase().equals("y"));
}
Simplest way would be do while loop. Example:
do{
// What you want to repeat and make sure to change have way to get out of loop like this:
System.out.print("Want more questions yes or no? ");
question = scanner.next();
}while(question.equals("yes") || question.equals("y"));
There's a few errors in your code but instead of giving you the entire solution to your homework problem I suggest you start with the simple case of reading input until the user enters 'n':
String input = "";
Scanner scanner = new Scanner(System. in);
while (!input.equals("n")) {
System.out.println("continue y/n?");
input = scanner.nextLine();
}
Add the generation of random ints, checking of answers etc inside the while loop body. Make sure to use equals instead of == when comparing two Strings

How does one limit/constrain user input in Java?

I want to have an error message appear if a user types more than three integers into the console. So if the console says "Type three integers" and the user types 123 244 242, no matter the numbers size, it should run without a problem. But if the user types 123 244 242 442 then when they press run I would like an error message to appear instead. But not entirely sure how to go about this.
Here is the simple program:
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Type three integers ");
int firstInt = userInput.nextInt();
int secondInt = userInput.nextInt();
int thirdInt = userInput.nextInt();
System.out.println(firstInt + secondInt + thirdInt);
}
}
Thank you
int firstInt = userInput.nextInt();
int secondInt = userInput.nextInt();
int thirdInt = userInput.nextInt();
char run = userInput.next().charAt(0);
if(userInput.hasNext())
{
System.out.println("Error, you need 3 numbers only, and a char");
userInput.nextLine(); //clears the rest of the line
}
give that a shot and see how it goes. I would suggest having this in a while loop so that it will keep priming for numbers until it gets all of them without error.
public static void main(String[] args)
{
boolean getNumbers = true;
int firstInt, secondInt, thirdInt;
Scanner userInput = new Scanner(System.in);
while(getNumbers)
{
firstInt = userInput.nextInt();
secondInt = userInput.nextInt();
thirdInt = userInput.nextInt();
char run = userInput.next().charAt(0);
if(userInput.hasNext())
{
System.out.println("Error message here");
userInput.nextLine(); //clear the rest of line
firstInt = secondInt = thirdInt = 0;
run = '';
}
else
{
getNumbers = false;
}
}
//do calculations with numbers here
}

Solving error for iterative program

i was trying to create an iterative program with user input, copied from this textbook of mine but on the returns i keep getting an error of: " Multiple markers at this line - The primitive type int of a does not have a field b -
Syntax error on token ",", . expected"
import java.util.Scanner;
public class Code3 {
public static void main (String [] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter A: ");
int a = scanner.nextInt();
System.out.println("Enter B: ");
int b = scanner.nextInt();
if (a==b)
return;
if (a>b)
return (a-b, b);
else
return (a, b-a);
}
}
public static void main (String [] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter A: ");
int a = scanner.nextInt();
System.out.println("Enter B: ");
int b = scanner.nextInt();
if (a>b) {
System.out.println("Results: " + (a-b) + ", " + b);
} else if(a < b) {
System.out.println("Results: " + a + ", " + (b-a));
}
}

Categories

Resources