This is my first time using the site so forgive me if I don't have things formatted correctly. But I'm pretty much a beginner with Java and am trying to create this program for a computer science course online and I need to use doubles in a Try/Catch in Java and I'm not sure how to go about doing it.
I know I need to use Math.pow() somewhere, but the instructor didn't exactly make it clear how to do this and I'm unable to contact them.
Here's the error code I'm getting and maybe that will better explain what I'm trying to do:
CollectInfo.java:22: error: method collectWage in class Validate cannot be applied to given types;
double wage = Validate.collectWage("Please enter your hourly wage");
^
required: double
found: String
reason: actual argument String cannot be converted to double by method invocation conversion
1 error
Here is an example of the code I have that is working so far, but I don't know how to fix to correct the error.
import java.util.*;
import java.util.regex.*;
public class CollectInfo {
public static void main(String[] args) {
int id = Validate.collectInt("Please enter the ID of the Item");
String fname = Validate.collectString(3, "Please enter the first name");
String lname = Validate.collectString(5, "Please enter the last name");
String email = Validate.collectEmail("Please enter your email address");
String phone = Validate.collectPhone("Please enter your phone Number\n"
+ "Like (123) 456-7890 or 1234567890 or 123-456-7890");
String zipcode = Validate.collectZip("Please enter the zipcode");
String ssn = Validate.collectSsn("Please enter your SSN");
double wage = Validate.collectWage("Please enter your hourly wage");
System.out.print(String.format("id: %s\nName: %s %s\nEmail: %s\n"
+ "Phone: %s\nZipCode: %s\n SSN: %s\nWage:%s\n\n",
id,fname,lname,email,phone,zipcode,ssn,wage));
} // end main method
} //end class CollectInfo
class Validate {
public static int collectInt(String messageIn) {
Scanner input = new Scanner(System.in);
int intOut = 0;
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
intOut = input.nextInt();
valid = false;
} catch (InputMismatchException e) {
input.nextLine();
System.out.println("You must enter a whole number!");
} // end catch
} // end while
return intOut;
} // end collectInt
public static String collectString(int strLen, String messageIn) {
Scanner input = new Scanner(System.in);
String outStr = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
outStr = input.nextLine();
if (outStr.length() < strLen) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("You must have more than %s characters\n", strLen);
} // end catch
}// end while
return outStr;
}
public static String collectZip(String messageIn) {
Scanner input = new Scanner(System.in);
String outStr = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
outStr = input.nextLine();
Integer.parseInt(outStr);
if (outStr.length() != 5) {
throw new Exception();
}
valid = false;
} catch (NumberFormatException ne) {
System.out.printf("Please enter a valid zip code\n");
} catch (Exception e) {
System.out.println("A zip code must be 5 characters long");
}
}// end while
return outStr;
}
public static String collectEmail(String messageIn) {
String expression = "^[\\w\\-]([\\.\\w])+[\\w]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Scanner input = new Scanner(System.in);
String outStr = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
outStr = input.nextLine();
CharSequence emailChk = outStr;
Matcher matcher = pattern.matcher(emailChk);
if (!matcher.matches()) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("Please enter a valid email address\n");
} // end catch
}// end while
return outStr;
}
//***************************************************************************
public static Double collectWage(String messageIn) {
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
double out = 0;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
if (strOut.length() != 4) {
throw new Exception();
}
out = Double.parseDouble(strOut);
valid = false;
} catch (NumberFormatException ne) {
System.out.println("Please enter a valid wage");
} catch (Exception e) {
System.out.printf("A wage should be 4 numbers long");
} //end catch
} //end while
return out;
}//end collectWage method
//***************************************************************************
public static String collectPhone(String messageIn) {
String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
CharSequence phoneChk = strOut;
Matcher matcher = pattern.matcher(phoneChk);
if (!matcher.matches()) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("Please try again with a valid phone "
+ "number\n");
} //end catch
} //end while
return strOut;
}//end collectPhone method
//***************************************************************************
public static String collectSsn(String messageIn) {
String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
CharSequence ssnChk = strOut;
Matcher matcher = pattern.matcher(ssnChk);
if (!matcher.matches()) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("Please try again with a valid social security "
+ "number\n");
} //end catch
} //end while
return strOut;
}//end collectSsn method
} // end of class Validate
I know that I don't need the 3 number length or anything like that, but this is just an example of what I did get working.
I'd appreciate any help you guys could provide in helping me figure things out.
try this
public static void main(String[] args) {
double wage = Validate.collectWage("Please enter your hourly wage");
}// end main method
public static Double collectWage(String messageIn) {
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
double out = 0;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
if (strOut.length() != 3) {
throw new Exception();
}
out = Double.parseDouble(strOut);
valid = false;
} catch (NumberFormatException ne) {
System.out.println("Please enter a valid wage");
} catch (Exception e) {
System.out.printf("A wage should be 3 numbers long");
} //end catch
} //end while
return out;
}//end collectWage method
Related
I am having a problem trying to understand how I can loop through a keyboard input line of text the user will give ex:
Anika 14 Dan 16
I want to read each token and assign to String name, Int, age, String name, int age. in that order.
This is easy however, if the user enters
Anika Anika Anika Anika 13 13 13 Dan 16
Then I want the program to:
Anika,
Integer needed got String,
Integer needed got String,
Integer needed got String,
13,
String needed got Integer,
String needed got Integer,
Dan,
16
So first one will always be a string which is a word EDIT: "word", second an int and thrid string which is a "word" and fourth int.
However, I can not simulate this.
Scanner scan = new Scanner(System.in);
String name = null;
int age = 0;
String name2= null;
int age2= 0;
if(scan.hasNext() == true)
name = scan.next();
age = scan.nextInt();
name2= scan.next();
age2= scan.nextInt();
I know if I do the top I get the right order, but it is the extra inputs that I would like to ignore but write a statement expression why it's wrong and then continue to search for the next int, or third string and so on.
boolean isstring = false;
boolean isnumber = false;
do {
if (scan.hasNext())
{
name = scan.next();
isstring = true;
}
else {
System.out.println("Need String got Integer");
isstring = false;
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt())
{
age = scan.nextInt();
isnumber=true;
}
else {
System.out.println("Need Integer got String");
isnumber=false;
scan.nextInt();
}
} while (!isnumber);
do {
if (scan.hasNext())
{
name2 = scan.next();
isstring = true;
}
else {
System.out.println("Need String got Integer");
isstring = false;
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt())
{
age2 = scan.nextInt();
isnumber = true;
}
else {
System.out.println("Need Integer got String");
isnumber=false;
scan.nextInt();
}
} while (!isnumber);
}
I tried to use do while with ifs and It didnt work. My logic is wrong somewhere, and I think it might be the has.next() method.
Any help will be appreciated!!
If the input is a word while waiting for an Integer, it will throw InputMismatchException. nextInt() first read the value as a String an then parse it as a Integer, so if you ignore the value using nextInt, if the value is a word, it will trow the aforementioned Exception.
Using the same logic of your program
The changes should be:
Ignore the input with scan.next()
Check if a String can be or not an Integer (using scan.hasNextInt()), not if is a String, because any Integer can be expressed as a String.
boolean isstring = false;
boolean isnumber = false;
do {
if (!scan.hasNextInt()) {
isstring = true;
name = scan.next();
} else {
isstring = false;
System.out.println("Need String got Integer");
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt()) {
isnumber = true;
age = scan.nextInt();
} else {
isnumber = false;
System.out.println("Need Integer got String");
scan.next();
}
} while (!isnumber);
do {
if (!scan.hasNextInt()) {
isstring = true;
name2 = scan.next();
} else {
isstring = false;
System.out.println("Need String got Integer");
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt()) {
isnumber = true;
age2 = scan.nextInt();
} else {
isnumber = false;
System.out.println("Need Integer got String");
scan.next();
}
} while (!isnumber);
Using try/catch and one loop
A naive solution using try/catch can be the following
public static void main (String[]args)
{
String name = null;
String name2 = null;
Integer age = null;
Integer age2 = null;
Scanner scan = new Scanner(System.in);
while (scan.hasNext())
{
try
{
if (name == null)
{
System.out.println("Please provide name: ");
name = getNameOrFail(scan);
System.out.println("Name set: " + name);
}
if (age == null)
{
System.out.println("Please provide age: ");
age = getAgeOrFail(scan);
System.out.println("Age set: " + age);
}
if (name2 == null)
{
System.out.println("Please provide name2: ");
name2 = getNameOrFail(scan);
System.out.println("Name2 set: " + name2);
}
if (age2 == null)
{
System.out.println ("Please provide age2: ");
age2 = getAgeOrFail (scan);
System.out.println ("Age2 set: " + age2);
}
}
catch (Exception e)
{
System.out.println(e.getMessage ()); // Print the message put int Exception(message) constructor
scan.nextLine(); // Flush the Scanner cache
}
}
}
public static String getNameOrFail(Scanner scan) throws Exception
{
if (scan.hasNextInt())
throw new Exception("Need String got Integer");
return scan.next();
}
public static Integer getAgeOrFail(Scanner scan) throws Exception
{
if (!scan.hasNextInt())
throw new Exception("Need Integer got String");
return scan.nextInt();
}
Pay attention to the scan.newLine() in the catch clause, this is needed because the Scanner use a cache with the last input, so if is not re-read you enter in a infinite loop condition.
Good luck!
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"));
I am trying to write a program that breaks string by '+' sign. For example, if my input is "1+2+3*4". the program will print 1, 2, 3*4. I used \s*\+\s* as my pattern. However, it doesn't print out when it matches the pattern?
private Scanner kbd = new Scanner(System.in);
private String tokenPattern = "\\s*\\+\\s*"; //pattern
public void repl() {
while(true) {
try {
System.out.print("-> ");
String input = kbd.nextLine();
if (input.equals("quit")) break;
Scanner tokens = new Scanner(input);
while(tokens.hasNext(tokenPattern)) { //figure out why its not printing
String token = tokens.next(tokenPattern);
System.out.println(token);
}
tokens.close();
} catch(Exception e) {
System.out.println("Error, " + e.getMessage());
}
}
System.out.println("bye");
}
You should use findWithHorizon
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();
}
}
I have the following method:
public void addStudent(){
String fName, lName;
double mGrade, fGrade;
System.out.print("\nEnter first name: ");
Scanner in = new Scanner(System.in);
fName = in.nextLine();
System.out.print("\nEnter last name: ");
lName = in.nextLine();
System.out.print("\nEnter midterm grade: ");
mGrade = in.nextDouble();
System.out.print("\nEnter final grade: ");
fGrade = in.nextDouble();
Student toAdd = new Student(fName, lName, mGrade, fGrade);
students.add(toAdd);
System.out.println("\nStudent record added.\n");
System.out.println(students.size());
}
How can I check if the user typed in something other than an integer for midterm grade and final grade? And if they entered a non-integer, I want the method to just request the user type in that value again. I'm guessing I'll have to use a do-while loop. But I don't don't know how to check the type...
Thanks!
You can use Scanner.next() and try to parse it to the type you want (ex. to integer by using Integer.parseInt(x) and if it fails (throws and exception) try to do it again.
Yes, a do-while will work best.
int midterm;
System.out.printLn("Enter midterm grade");
do
{
try {
string s = in.nextLine();
midterm = Integer.parseInt(s);
break;
}
catch (Exception e)
{
System.out.printLn("Couldn't parse input, please try again");
}
}
while (true);
You may use the method: nextInt() from Scanner
Alternatively you can check if a string is an integer like this:
if( someString.matches("\\d+") ) {
// it is
} else {
// it isn't
}
Run the input method in a loop, if user enters something other than valid integer or double, repeat asking for the input.
you can try this
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String args[]) throws Exception {
String input;
int ch1;
float ch2;
String ch3;
Scanner one = new Scanner(System.in);
input = one.nextLine();
try {
ch1 = Integer.parseInt(input);
System.out.println("integer");
return;
} catch (NumberFormatException e) {
}
try {
ch2 = Float.parseFloat(input);
System.out.println("float");
return;
} catch (NumberFormatException e) {
}
try {
ch3 = String.valueOf(input);
System.out.println("String");
} catch (NumberFormatException e) {
}
}
}