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
Related
I am currently working on an assignment to parse strings and I am running into an issue.
It appears, that if nothing is entered, it is generating my error message I have created when a comma is not inputted.
According to the assignment in zybooks, it should not be outputting anything. Below is my code.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
//local variables
String lineString;
String firstWord;
String secondWord;
int commaLocation;
boolean inputDone;
//checks to end the program
inputDone = false;
//keeps the loop running until q is entered
while (!inputDone) {
System.out.println("Enter input string: ");
lineString = scnr.nextLine();
//checks comma
commaLocation = lineString.indexOf(',');
if (commaLocation == -1) {
System.out.println("Error: No comma in string");
}
else {
firstWord = lineString.substring(0, commaLocation);
firstWord = firstWord.replace(" ", "");
secondWord = lineString.substring(commaLocation + 1, lineString.length());
secondWord = secondWord.replace(" ", "");
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
System.out.println();
}
if (lineString.equals("q")) {
inputDone = true;
}
}
return;
}
}
It happens because when nothing is entered, comma cannot be found, therefore indexOf returns -1.
I would add something like
if (lineString.isEmpty()) {
continue;
}
right after lineString = scnr.nextLine();
EDIT:
I just noticed, that your error message will be printed in case, when your input equals 'q'. I assume this is not an expected behaviour, so I recommend to place
if (lineString.equals("q")) {
inputDone = true;
}
right after assignment of lineString or the if block I suggested above.
I'm trying to make a simple program that uses a scanner for input and has a while loop that continues taking input until an end character is entered. I want the scanner to take input and add a string to the stack list. I'm trying to figure out why this code doesn't terminate the while loop when a space is typed.
import java.util.Scanner;
public class ReverseString<E> {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Stack<String> stack = new Stack();
//while(scan.hasNext() && !stack.equals(" ")){
// while(!scan.nextLine().equals("")){
while (scan.hasNext()) {
stack.push(scan.next());
if (scan.equals(" ")) {
break;
}
}
System.out.print(stack.pop() + " ");
}
}
You should use nextLine instead
while (scan.hasNextLine()) {
String nextInput = scan.nextLine();
stack.push(nextInput );
if (nextInput.equals(" ")) {
break;
}
}
while (scan.hasNext()) {
stack.push(scan.next());
if (scan.equals(" ")) {
break;
}
}
change to
while (scan.hasNextLine()) {
String value = scan.nextLine();
if (" ".equals(value)) {
break;
}
stack.push(value);
}
scan is a Scanner, it's not a String, scan.equals(" ") would always return false.
You're doing,
if (scan.equals(" ")) {
break;
}
which means you're comparing the Scanner object scan to a space. Try doing the following instead(you have to compare the scan.next() with a space):
import java.util.Scanner;
public class ReverseString<E> {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Stack<String> stack = new Stack();
//while(scan.hasNext() && !stack.equals(" ")){
// while(!scan.nextLine().equals("")){
while (scan.hasNext()) {
String nextInput = scan.next();
stack.push(nextInput );
if (nextInput.equals(" ")) {
break;
}
}
System.out.print(stack.pop() + " ");
}
}
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"));
String [] V = {"a","e","i","o","u"};
Scanner input = new Scanner(System.in);
String A;
System.out.println("Enter any letters");
A=input.next();
if(A.contains(V)) {
System.out.println("success");
}
bottom line. if any of the letters in "V" string are in "A" i want it to continue to "success"
Try to use a foreach loop like this:
for (String string : V) {
if(A.contains(string)) {
System.out.println("success");
}
}
Because the method contains(CharSequence) in the type String is not applicable for the arguments (String[]).
It Works Making some changes to your code
String [] V = {"a","e","i","o","u"};
boolean flag = false;
Scanner input = new Scanner(System.in);
String A;
System.out.println("Enter any letters");
A=input.next();
for(String temp:V)
{
if (A.contains(temp)) {
flag = true;
break;
}
}
if(flag)
System.out.println("Success");
else
System.out.println("Not Success");
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