public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
boolean format = false;
int grades = 0;
do {
System.out.println("Enter course mark (0-100): ");
try {
String input = br.readLine();
grades = Integer.parseInt(input);
} catch (NumberFormatException | IOException e) {
System.out.println("Error number format!");
}
} while (!format);
if (grades > 100 || grades < 100) {
System.out.println("Please enter within the range (0-100)");
}
System.out.println("Your grades is " + grades);
}
What have i done wrong here i am trying to achieve this
Enter course mark (0-100): qwerty
Bad input data type.
Enter course mark (0-100): -12
Input out of [0, 100] range!
Enter course mark (0-100): 24
Your grades is 24
Change
do {
try {
String input = br.readLine();
grades = Integer.parseInt(input);
}
catch(...) { ... }
} while (!format);
to
do {
try {
String input = br.readLine();
grades = Integer.parseInt(input);
format = true; // Add this line
}
catch(...) { ... }
if (grades > 100 || grades < 100) {
System.out.println("Please enter within the range (0-100)");
format = false;
}
} while (!format);
If the execution flow reaches format = true;, then that means that the user's input was correct & will make sure that you break the input loop.
You no need to use the do..while block.the output is possible with While block itself. You can also change your program block like this
public static void main(String[] args) throws IOException
{
int grades = 0;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr)
while((input=br.readLine())!=null)
{
try
{
grades = Integer.parseInt(input);
}
catch (NumberFormatException | IOException e)
{
System.out.println("Error number format!");
}
}
if (grades > 100 || grades < 100)
{
System.out.println("Please enter within the range (0-100)");
}
System.out.println("Your grades is " + grades);
}
Related
I'm confused while using an Java program I created.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
System.out.println("Your first input is " + input1);
}
Initially, when a user Ctrl+D during the input, it will promptly end the program and display an error in the form of this,
Your first input integer? ^D
Class transformation time: 0.0073103s for 244 classes or 2.9960245901639343E-5s per class
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651);
at Playground.Test1.main(Test1.java:13)
Doing a bit of research I note that Ctrl+D terminates the input of sort. Therefore, I tried add few more lines to my codes to prevent the error from appearing again and instead printing a simple "Console has been terminated successfully!" and as far as my skills can go.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
catch (NoSuchElementException e) {
System.out.println("Console has been terminated successfully!");
}
}
System.out.println("Your first input is " + input1);
}
In the end, I still got the same error.
Got it!, the code hasNext() will ensure that the error will not appear. This method is to check whether there is another line in the input of the scanner and to check if its filled or empty. I am also using null to check my statement after passing the loop so the program stops if the input value is still null while keeping the function of Ctrl+D.
public static void main(String[] args) {
Integer input1 = null;
System.out.println("Your first input integer? ");
Scanner scanner1 = new Scanner(System.in);
while(scanner1.hasNextLine()) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
break;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.println("Your first input integer? ");
}
}
if (input1 == null) {
System.out.println("Console has been terminated successfully!");
System.exit(0);
}
System.out.println(input1);
}
This solution is not prefect of course but I would appreciate if there were much simpler options.
import java.util.Scanner;
public class CurrencyTester
{
public static void main(String[]args)
{
i want to loop from the beginning, but not to ask the user to type in for same converter, how do i do it?
CurrencyConverter one= new CurrencyConverter();
System.out.println("Convert dollar to euro/gbp/cad");
i want to ask for the input euro gbp or cad after the first loop
System.out.println("enter euro/gbp/cad");
System.out.println("");
Scanner input = new Scanner(System.in);
String a = input.next();
if("euro".equalsIgnoreCase(a))
{
euro
do {
System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
break;
} else {
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
System.out.println("Euro:");
System.out.println("€"+one.getCurrencyE());
} catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
}
} while (true);
}
if("gbp".equalsIgnoreCase(a))
{
GDP
do { System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
break;
} else {
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
System.out.println("GDP:");
System.out.println("£"+one.getCurrencyG());
} catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
}
} while (true);
}
if("cad".equalsIgnoreCase(a))
{
CAd
do { System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
break;
} else {
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
System.out.println("Canadian Dollar:");
System.out.println("$"+one.getCurrencyC());
} catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
}
} while (true);
}
}
}
}
I tried to use while loop in the beginning ,but it doesn't work.
The main problem with your existing code is that you have duplicated the same logic in three different places. What you instead want to do is group any code that is common for all your different cases into methods or otherwise structuring your logic so you don't have to duplicate it.
Here is one way to structure your code in a more readable and maintainable way:
public static void main(String[] args) {
CurrencyConverter one = new CurrencyConverter();
do{
System.out.println("Convert dollar to euro/gbp/cad");
System.out.println("enter euro/gbp/cad");
System.out.println("");
Scanner input = new Scanner(System.in);
String a = input.next();
String d = enterDollars();
if( d == null )
break;
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
if( "euro".equalsIgnoreCase(a) )
System.out.println("Euro:\n€" + one.getCurrencyE());
else if( "gbp".equalsIgnoreCase(a) )
System.out.println("GBP:\n£" + one.getCurrencyG());
else if( "cad".equalsIgnoreCase(a) )
System.out.println("Canadian Dollar:\n$" + one.getCurrencyC());
}
catch (NumberFormatException e) {
System.out.println("Not double,wrong input");
}
} while (true);
}
private static String enterDollars(){
System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
return null;
}
return d;
}
I have put the code for getting user input in dollars into its own separate method, which makes the code easier to read. Similarly, you could further divide your code into smaller methods (like enterCurrency(), presentResult(), etc) to make your main method more readable.
You are copying and pasting similar pieces of logic. This is not good practice and typically means you should start creating functions for similar behavior. I am not sure how far into programming you are so I am going to show you a simple way to get input from the user using a single do/while and another do while for grabbing a valid dollar amount.
Put this in your main
CurrencyConverter one= new CurrencyConverter();
Scanner input = new Scanner(System.in);
System.out.println("Convert dollar to euro/gbp/cad");
HashSet<String> conversions = new HashSet<>();
conversions.add("euro");
conversions.add("gdp");
conversions.add("cad");
System.out.println("");
String userInput = "";
do {
System.out.println("enter euro/gbp/cad");
userInput = input.nextLine();
double amount = 0;
//check to see if we need to get a dollar amount
if(conversions.contains(userInput))
{
do {
System.out.println("Enter Dollars:");
String sAmount = input.nextLine();
amount = Double.MAX_VALUE;
//check it's a number before parsing
if(sAmount.matches("\\d+"))
{
amount = Double.parseDouble(sAmount);
//then set it for the object once
one.setDollar(amount);
}
else
{
System.out.println("Error when parsing dollar amount: " + sAmount);
System.out.println("Please Try again!");
}
} while (amount != Double.MAX_VALUE);
}
//check for euro
if(userInput.equals("euro"))
{
System.out.println("Euro: ");
System.out.println("€"+one.getCurrencyE());
}
else if(userInput.equals("gdp"))
{
System.out.println("GDP: ");
System.out.println("£"+one.getCurrencyG());
}
else if(userInput.equals("cad"))
{
System.out.println("Canadian Dollar: ");
System.out.println("$"+one.getCurrencyC());
}
else if (!userInput.equals("quit"))
{
System.out.println("Error with input : " + userInput);
}
} while (!userInput.equals("quit"));
Is it possible to repeat more than one try-catch statements in one block without creating another (nested) while loop or having to repeat the whole loop again?
For example:
while(true) {
//try-catch 1: if the user input is correct continue, or ask him to repeat this input
//try-catch 2: if the user input is correct continue, or ask him to repeat this input
break; //after it's done
}
Another Ex:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
while (true) {
Scanner scan1 = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
scan1.next();
} catch (InputMismatchException e) {
//do something to repeat this task
}
try {
System.out.println("Enter another number: ");
scan2.next();
} catch (InputMismatchException e) {
//do something to repeat this task
}
break;
}
}
}
The flow you are describing doesn't require nested loops, but it does require two separate loops.
I think you want something like this:
Scanner scan1 = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter a number: ");
scan1.next();
break;
} catch (InputMismatchException e) {
System.out.println("Error! That wasn't a number!");
// didn't reach a break statement, will repeat.
}
}
while (true) {
try {
System.out.print("Enter another number: ");
scan2.next();
break;
} catch (InputMismatchException e) {
System.out.println("Error! That wasn't a number!");
// didn't reach a break statement, will repeat.
}
}
Notice that this is a lot of repeated code, so you could improve it by extracting a method to call - something like:
private static int getNumber(String prompt, Scanner scan) {
while (true) {
try {
System.out.print(prompt);
return scan.nextInt();
} catch (InputMismatchException e) {
System.out.println("Error! Try again.");
}
}
}
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
int num1 = getNumber("Enter a number: ", scan1);
int num1 = getNumber("Enter another number: ", scan2);
}
Disclaimer: my Java is rusty, so the above code may not be exactly right, but I hope you get the idea.
Here is a simple example where the application will not continue unless there is a valid number supplied.
public class TestInput
{
public static boolean validInput(Scanner scan)
{
System.out.print("Enter a number: ");
try
{
String stringNumber = scan.next();
try
{
int myInt = Integer.parseInt(stringNumber);
}
catch (NumberFormatException e)
{
System.out.println("No I meant a Number; " + stringNumber + " is not a number");
return false;
}
}
catch (InputMismatchException e)
{
return false;
}
return true;
}
public void doTheWork()
{
Scanner scan = new Scanner(System.in);
if (!validInput(scan))
{
doTheWork();
}
System.out.println("All Good");
}
public static void main(String[] args)
{
TestInput testInput = new TestInput();
testInput.doTheWork();
}
}
Here is a simple example to reuse a method to get multiple inputs
public class TestInput
{
public static int getNumberInput(String message)
{
Scanner scan = new Scanner(System.in);
try
{
System.out.print(message);
String stringNumber = scan.next();
try
{
return Integer.parseInt(stringNumber);
}
catch (NumberFormatException e)
{
return getNumberInput("No I meant a Number; " + stringNumber + " is not a number");
}
}
catch (InputMismatchException e)
{
//do something to repeat this task
}
return getNumberInput(message);
}
public void doTheWork()
{
int oneParam = getNumberInput("Enter a number: ");
int twoParam = getNumberInput("Enter another number: ");
System.out.println("Your first input is " + oneParam);
System.out.println("Your second input is " + twoParam);
}
public static void main(String[] args)
{
TestInput testInput = new TestInput();
testInput.doTheWork();
}
}
How do i return an error and ask the question Do you want to try again (Y/N)? again when the user entered neither Y/N as an answer?
import java.io.*;
public class Num10 {
public static void main(String[] args){
String in="";
int start=0, end=0, step=0;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
do{
try{
System.out.print("Input START value = ");
in=input.readLine();
start=Integer.parseInt(in);
System.out.print("Input END value = ");
in=input.readLine();
end=Integer.parseInt(in);
System.out.print("Input STEP value = ");
in=input.readLine();
step=Integer.parseInt(in);
}catch(IOException e){
System.out.println("Error!");
}
if(start>=end){
System.out.println("The starting number should be lesser than the ending number");
System.exit(0);
}else
if(step<=0){
System.out.println("The step number should always be greater than zero.");
System.exit(0);
}
for(start=start;start<=end;start=start+step){
System.out.println(start);
}
try{
System.out.print("\nDo you want to try again (Y/N)?");
in=input.readLine();
}catch(IOException e){
System.out.println("Error!");
}
}while(in.equalsIgnoreCase("Y"));
}
}
Should i be using if-else?
First +1 for supplying a fully compilable program. That's more than 90% of question askers do.
In your final try/catch block, check that the user entered 'y' or 'n' like this
try{
while (!in.equalsIgnoreCase("y") && !in.equalsIgnoreCase("n")) {
System.out.print("\nDo you want to try again (Y/N)?");
in=input.readLine();
}
}catch(IOException e){
System.out.println("Error!");
}
}while(in.equalsIgnoreCase("Y"));
Do something like this:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
boolean w4f = true;
do {
String in = input.readLine();
if ("Y".equalsIgnoreCase(in)) {
w4f = false;
// do something
} else if ("N".equalsIgnoreCase(in)) {
w4f = false;
// do something
} else {
// Your error message here
System.out.println("blahblah");
}
} while(w4f);
This is what I have written so far but when exception is raised it does not again ask the user for input.
do {
System.out.println("Enter the number of stones to play with: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp = br.readLine();
key = Integer.parseInt(temp);
} while (key < 0 && key > 9);
if (key < 0 || key > 10)
throw new InvalidStartingStonesException(key);
player1 = new KeyBoardPlayer();
player2 = new KeyBoardPlayer();
this.player1 = player1;
this.player2 = player2;
state = new KalaGameState(key);
} catch (NumberFormatException nFE) {
System.out.println("Not an Integer");
} catch (IOException e) {
System.out.println(e);
}
As soon as that NumberFormatException is thrown, you jump out of the loop and down to the catch. If your try-catch block is inside your while loop, it'll have the effect you're looking for. You may need to adjust the condition on the loop.
An alternative way is to check if the string input matches a regular expression for an integer. If it doesn't match, you ask for the input again.
See Teleteype.readInt() from the Java Project Template. The basics of it is that you read input as a String, and then you convert it to an integer using Integer.parseInt(), which will throw NumberFormatException if the contents of the String is not an integer, which you can handle by catching the NumberFormatException.
What I would recommend is instead of using all these exceptions is to make separate methods that read specific data types. (Ex.)
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args){
int n = getInteger("Enter integer: ");
System.out.println(n);
}
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
return Integer.parseInt(in);
}
}
while (true) {
System.out.println("Enter the number of stones to play with: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
key = Integer.parseInt(br.readLine());
if (key > -1 && key < 10)
break;
else
System.out.println("Invalid number of stones. Choose from 0 - 9");
}