I am building a java program that tracks bowel function for users. I have a segment of code inside a loop that queries the user via Scanner to answer if they have cramps. I have the following code working:
String cramps = userInput.nextLine();
String replacecramps = cramps.replace("Y","true");
boolean mycramps = Boolean.parseBoolean(replacecramps);
This effectively takes a "Y" answer and replaces it with "true" and then takes the String "true" and changes it to a boolean true (I think - it seems to be working that way, anyway). However, I'd like to change other possible common inputs, such as "y", "yes", "Yes", "yeah", "Yeah", "yep", "Yep", etc as well.
Is there any way to do this? I am very new to Java, so it is proving to be difficult. I have read every single post about it here, and I'm still lost as to how to best go about this.
Here are some code snippets that may be useful:
The branch of the loop this resides in is (I can paste in the full code if necessary, but it is very long):
} else if (myBristol == 7) {
System.out.println("You appear to have severe diarrhea. ");
//Integrate Diarrhea.java class
System.out.println("\nDid you experience cramps or bloating? (Y/N)");
String cramps = userInput.nextLine();
String replacecramps = cramps.replace("Y","true");
boolean mycramps = Boolean.parseBoolean(replacecramps);
System.out.println("Did you experience flatulence? (Y/N)");
String gas = userInput.nextLine();
String replacegas = gas.replace("Y","true");
boolean mygas = Boolean.parseBoolean(replacegas);
Diarrhea b = new Diarrhea(poopColor, poopSize, mycramps, mygas);
//Print data to log file
pw.println(b.toString());
The subclasses it is using:
public class Poop{
protected String color;
protected String size;
public Poop(String poopColor, String poopSize)
{
color=poopColor;
size=poopSize;
}
public void setcolor(String c)
{
color = c;
}
public String getcolor(){
return color;
}
public void setsize(String s)
{
size = s;
}
public String getsize(){
return size;
}
#Override
public String toString() {
String tmp = "This poop's color was: " + this.getcolor() + ". Poop was: " + this.getsize() + ".";
return tmp;
}
}
public class Diarrhea extends Poop{
protected boolean cramps;
protected boolean gas;
public Diarrhea(String poopColor, String poopSize, boolean cramps, boolean gas) {
super(poopColor,poopSize);
this.cramps=cramps;
this.gas=gas;
}
public void setcramps(boolean mycramps) {
cramps=mycramps;
}
public boolean getcramps(){
return cramps;
}
public void setgas(boolean gas) {
gas=this.gas;
}
public boolean getgas(){
return gas;
}
#Override
public String toString() {
String tmp = "This diarrhea's color was: " + this.getcolor() + ". Was this a little or a lot of diarrhea: " + this.getsize() + ". Did you experience cramps or bloating? (true/false) " + this.cramps + ". Did you experience flatulence? (true/false) " + this.gas + ".";
return tmp;
}
}
This is how I have been managing my y/n questions up until this point, which has been working nicely as it only looks for a y or n as the first character, doesn't care what case, and doesn't care about anything else (like typos). It was a little difficult figuring out how to get it to work for a boolean, but I think I'm on the right path - but maybe I'm going about this all wrong.
char answer1 = userInput.next().charAt(0);
answerString = Character.toString(answer1);
userInput.nextLine();
if (answerString.equalsIgnoreCase("Y")) {
//Integrate Poop.java class
System.out.println("Was this a large, medium, small, or average sized bowel movement (describe size): ");
String poopSize = userInput.nextLine();
System.out.println("How would you describe the color of this poop (brown, greenish, light, dark, etc): ");
String poopColor = userInput.nextLine();
Poop a = new Poop(poopColor, poopSize);
//Print data to log file
pw.println(a.toString());
You can use replaceALL with some regex like this :
String input = "you are saying : y yes Yes yeah Yeah yep Yep";
input = input.replaceAll("\\b(?i)y(es|eah|ep)?\\b", "true");
System.out.println(input); //you are saying : true true true true true true true
details about regex :
\b for Word Boundaries
(?i) for case insensitive
y(es|eah|ep)? y followed by one of (es or eah or ep) which are optional ?
Try a case insensitive replace all using the list of positive words you want to target:
String target = "Dogs Yes yes Yeah yeah Yep yep false";
target = target.replaceAll("(?i)\\b(y|yes|yeah|yep)\\b", "true");
System.out.println(target);
Dogs true true true true true true false
Demo
Related
So basically I have to take these words as an input or hard coded(doesn't really matter). And I have to print what color the word has for example. "Red Dogs"-->Red. And I have two colors red and blue. When its neither I get an extra empty string.
Scanner input=new Scanner(System.in);
String h=System.out.println("Enter a word");
String i=input.next();
public static String color(str r, str b){
for(int i=0;i<=h.length;i++){
if(i="red"){
System.out.println("Red");
}else if(i="blue"){
System.out.println("Blue");
}else{
return("");
}
}
}
practice more.
public static void main(String[] args) {
String colorStr = "RED DOG BLUE BIRD";
System.out.println(color(colorStr));
}
public static String color(String colorStr) {
Set<String> set = new HashSet<>(Arrays.asList("RED", "BLUE"));
StringBuilder presentColorStr = new StringBuilder();
String[] words = colorStr.split(" ");
for (String word : words) {
if(set.contains(word)) {
presentColorStr.append(word).append(" ");
}
}
return presentColorStr.toString();
}
Looks like you are entirely new to Java code. I will explain few things about your code.
Conditinal construct if..else accept a boolean literal only.
if(a = b) // this is error as = is assignment operator and will not return boolean unless you assign a boolean
if(a == b) // this is right approach to compare two values.
Comparison of two reference is different than values. Ex. String holds reference so you cannot compare two string with == . You must compare two Strings with equals method that returns boolean if both string are same.
String str1 = "hello";
String str2 = "hello";
if(str1.equals(str2)) {
System.out.println("both are same.");
}
Further, your requirement to check if input string contains a string can be done using String.contains() function
String str1 = "Red Ball";
String str2 = "ball";
if(str1.contains(str2)) {
System.out.println("String conatins str2");
}
You can also use methods toLowerCase() and toUpperCase() to make it case independent.
I have to code a program, that's working with boolean operators. The first thing this program should do is to ask the user for an operator by "command:". The user can only enter "&&", "||", "!" and "quit". Quit just shuts down the program. The next thing it does is to ask the user for a boolean variable, but here is my problem: The program works perfectly fine with entering "true" or "false", but the task I've got says, the user can only use "t" for "f" as input. So here is my question: How can I make the program to understand "t" as "true" and "f" as "false"?(by the way if the user enters"!" the program just outputs the negation of the first parameter)
public static void main(String[] args) {
Scanner eingabe = new Scanner(System.in);
System.out.println("Command: ");
String command = eingabe.nextLine();
if(command.equals("quit")) {
System.exit(0);
}
System.out.println("Parameter 1:");
boolean parameter1=eingabe.nextBoolean();
if(command.equals("!")) {
System.out.println(!parameter1);
System.exit(0);
}
System.out.println("Parameter 2:");
boolean parameter2=eingabe.nextBoolean();
if(command.equals("&&")) {
System.out.println(parameter1&¶meter2);
}else if(command.equals("||")) {
System.out.println(parameter1||parameter2);
}
eingabe.close();
}
}
The easiest way would be to write a little method, something like:
boolean customParseBoolean(String input) {
if ("t".equals(input)) {
return true;
} else if ("f".equals(input)) {
return false;
}
// You don't have to throw an exception on invalid input; just an example.
throw new IllegalArgumentException("Invalid input: " + input);
}
and then invoke this something like:
boolean parameter1 = customParseBoolean(eingabe.nextLin());
It doesn't matter which way you do it, but below should work for your example. It just doesn't cover the case when the input is malformed
String parameterString1 = eingabe.next();
boolean parameter1 = !command.equals("f");
String parameterString2 = eingabe.next();
boolean parameter2 = command.equals("t");
you can always cross verify the user input in if() condition. create a boolean value with false by default, if the user types t make that boolean as true and vice versa.
or else u can use switch statements
I was trying to prepare a flow chart of program for my practice where i encounter that following situation is required for me where a user would enter a string value as input either "Yes"or "Y" and "No" or "N" and based on its input the application would either terminate or restart from a certain point till now i have this as an example in my mind
public class ApplicationName {
public static void main(String args[]) {
String restartOperation;
do {
restartOperation = Confirm_Before_Exit();
} while (!restartOperation.equals("No"));
//Rest of code
}
public static void Some_Operation() {
//Executed when called before closing application
}
public static String Confirm_Before_Exit() {
Scanner inputData = new Scanner(System.in);
String answer;
System.out.println("Do you want to perform another operation ?" + " " + "Y" + " " + "N");
answer = inputData.nextLine();
switch (answer) {
case "Y":
case "Yes":
Some_Operation();
break;
default:
System.out.println("Good Bye !");
}
return answer;
}
}
This works till the user has not given input as "No" but obviously it wont work if entered "N" or perhaps small "n" or even "no" but for timing i am only trying for "No" and "N" as input value.
change your do while to the following :
do {
restartOperation = Confirm_Before_Exit();
} while (!restartOperation.equalsIgnoreCase("No") && !restartOperation.equalsIgnoreCase("n"));
I would do something like this. You make your answer lowercase to take into account cases like YEs, NO, etc. You then specify the n and no.The default should be a catch all.
answer = inputData.nextLine().toLowerCase();
switch (answer) {
case "y":
case "yes":
Some_Operation();
break;
case "n":
case "no":
System.out.println("Good Bye !");
break;
default:
System.out.println("Not a valid reponse");
}
You may want to use Regex for text matching (it is contained in the default Java-JDK, not an external library). It is extremely powerful.
You define a needle to search for in Regex-syntax, for example this:
^no?$
It matches text that starts (^) with n and then eventually (?) followed by o (but it does not need to be there), after that the text ends ($). There's also a flag for case insensitive matching /i. You can try Regex at regex101.com. Try this: regex101.com/r/edrehj
Okay, how to use this stuff in Java? Fairly easy:
String input = ...
Pattern pattern = Pattern.compile("^no?$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
// User want's to cancel
...
} else {
// User want's to continue
...
}
More info at Wikipedia#Regex, Java-API#Pattern and Java-API#Matcher.
You can also put this inside an own method, makes the usage more easy and user friendly to read:
private boolean doesUserWantToCancel(final String textInput) {
Pattern pattern = Pattern.compile("^no?$", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(textInput);
return matcher.find();
}
You then just call the method for your input:
...
} while (!doesUserWantToCancel(restartOperation));
...
If I am understanding your question correctly you want to run Confirm_Before_Exit() when you are restarting an operation?
Here is what I would do. Instead of having string restartOperation you should have boolean restartOperation. This way you either deal with true or false.
In the Confirm_Before_Exit() function I would still add the .toLowerCase() to your inputData to take into account weird cases. I added two booleans answer and inValidAnswer.
You want your answer to be true if you want to perform another operation. If it is false it will exit.
If the user mistypes, inValideAnswer will be set to true and they will get an error saying invalid answer and will get reprompted.
public class ApplicationName {
public static void main(String args[]) {
boolean restartOperation;
do {
restartOperation = Confirm_Before_Exit();
} while (restartOperation);
//Rest of code
}
public static void Some_Operation() {
//Executed when called before closing application
}
public static boolean Confirm_Before_Exit() {
Scanner inputData = new Scanner(System.in);
boolean answer;
boolean validAnswer;
while(inValideAnswer){
System.out.println("Do you want to perform another operation ?" + " " + "Y" + " " + "N");
string userInput = inputData.nextLine().toLowerCase();
switch (userInput) {
case "y":
case "yes":
Some_Operation();
answer = true;
inValideAnswer = false;
break;
case "n":
case "no":
answer = false;
inValideAnswer = false;
System.out.println("Good Bye !");
break;
default:
System.out.println("Not a valid reponse");
inValideAnswer = true;
}
}
return answer;
}
}
In the program I am trying to look for pattern in content. If any of the pattern H Q 9 is found in string taken by user it should print YES else NO. So I used three bool flag1 flag2 flag3. My code gives wrong output if input is codeforces. Desired output is NO instead of YES.
public static void main(String[] args) {
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
Scanner in = new Scanner(System.in);
String s = in.nextLine();
String text = s;
String pat1 = ".*H*.";
String pat2 = ".*Q*.";
String pat3 = ".*9*.";
//boolean isMatch = Pattern.matches(pattern, content);
flag1 = Pattern.matches(pat1, text);
flag2 = Pattern.matches(pat2, text);
flag3 = Pattern.matches(pat3,text);
if (flag1 == true || flag2 == true || flag3 == true)
System.out.println("YES");
else
System.out.println("NO");
}
Your regexps are wrong - H* means "any number of Hs, including zero", and likewise for both other regexps.
Thus, .*H*. means that your text should contain an arbitrary number of "something", then an arbitrary number of Hs (or none, as "zero Hs" is also allowed), and then an arbitrary letter.
codeforces fulfils these criteria, as it contains of an arbitrary number of letters, no H and ends with an arbitrary letter.
Your regexps will match any input which has at least once character.
Using three regular expressions is redundant. I recommend just using one.
I also refactored and reformatted your code.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
boolean matches = Pattern.matches(".*[HQ9].*", s);
if (matches)
{
System.out.println("YES");
} else
{
System.out.println("NO");
}
}
You could compress the method even further:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
boolean matches = Pattern.matches("[HQ9]", s);
System.out.println(matches ? "YES" : "NO");
}
The regular expression .*[HQ9].* does the following: It searches for any characters equal to the ones found inside of the square brackets:
Although someone has already explained the problem (I do not want to take credit from others), here are a few suggestions to reduce and more importantly test your code
import java.util.regex.Pattern;
class Test75B {
public static final String[] TESTS = {
"codeforces",
"Back to Headquarters",
"A cat has nine lives",
"A cat has 9 lives",
"Is it a Query or a Quarry?",
"How Can You Quote 4+5=9!"
};
public static void main(String[] args) {
for (String text: TESTS) {
boolean flag1=false;
String pat1= ".*[HQ9].*";
System.out.println(text);
flag1=Pattern.matches(pat1, text);
System.out.println( flag1 ? "YES" : "NO");
}
}
}
Here is the output I get
codeforces
NO
Back to Headquarters
YES
A cat has nine lives
NO
A cat has 9 lives
YES
Is it a Query or a Quarry?
YES
How Can You Quote 4+5=9!
YES
As an easy test, remove the .* in the regex, recompile and look at the output. You will see they are required.
Hey guys so heres my question. I've got a class that manipulates a stack of Fractions and it is an RPN Evaluator. I'm newer to Java and only know basic data structures. This is a project for a class but I'm kinda bummed. I need to print out the expression that I used OR print out the expression until the RPN expression isn't valid denoted by valid = false/true I have a specific way I have to print it out and ill give an example but I cannot figure out how to do it... I have a queue available to me to use but I must use both a stack and a queue. I realize the code is yuck but its because I haven't begun my cleanup of that class yet. Here is an example of the output I need if the inputs are as follows.... Note that the input is in quotes minus the quotes
Input************************************Output
"(2/5)(1/2) * * #" *********** Expression 3 is: (2/5)(1/2)**
"(3/1)T ^ (3/2) #" *********** Expression 4 is: (3/1)T
Here is my class(I know it's sloppy...and the rules are very restrictive on what I can and can't use. No linked lists etc....)
import java.util.Scanner;
public class RpnEvaluator
{
private final int MAX_TOKEN = 20;
private Scanner stdin;
private int count = 0;
public void run() throws java.io.IOException
{
runOnce();
}
public boolean isOperator(String input)
{
String[] oprtr = {"+", "-", "*"};
for(String choice: oprtr)
if(choice.equals(input))
return true;
return false;
}
public boolean isOperation(String input)
{
if(input.startsWith("(", 0))
return true;
return false;
}
public Fraction runOperation(String choice, Fraction op2, Fraction op1)
{
Fraction newFract = new Fraction();
if(choice.equals("*"))
newFract = new Fraction(op1.times(op2));
else if(choice.equals("+"))
newFract = new Fraction(op1.plus(op2));
else if(choice.equals("-"))
newFract = new Fraction(op1.minus(op2));
return newFract;
}
public void runOnce()
{
String readIn = "";
boolean valid = true;
Fraction op1 = null, op2 = null, answer = null, myFract;
Queue myQueue = new Queue(MAX_TOKEN);
Stack myStack= new Stack(MAX_TOKEN);
stdin = new Scanner(System.in);
while(stdin.hasNext() && valid == true)
{
readIn = stdin.next();
if(readIn.equals("#"))
{
break;
}
else if(!isOperator(readIn) && isOperation(readIn))
{
myFract = new Fraction(readIn);
myStack.push(myFract);
}
else if(isOperator(readIn))
{
if(myStack.isEmpty())
valid = false;
else
op2 = (Fraction)myStack.pop();
if(myStack.isEmpty())
valid = false;
else
op1 = (Fraction)myStack.pop();
myStack.push(runOperation(readIn, op2, op1));
}
else
valid = false;
}
if(myStack.isEmpty())
valid = false;
else
answer = (Fraction)myStack.pop();
if(!myStack.isEmpty())
valid = false;
if(valid == false)
{
System.out.print("Expression " + ++count + ": ");
System.out.println("Invalid Expression");
}
else
{
System.out.println("Expression " + ++count + ": ");
System.out.println("The value is: " + answer.toString());
}
clear(myStack, myQueue);
}
public void clear(Stack myStack, Queue myQueue)
{
myStack.clear();
myQueue.clear();
}
}
I've got a class that manipulates a stack of Fractions and it is an RPN Evaluator.
No it isn't. It's an attempt, but it doesn't handle parentheses at all, or operator precedence. You need to look up the Dijsktra shunting-yard algorithm. If this is an assignment I have no doubt that this algorithm was mentioned in class, probably at great length.
I realize the code is yuck but its because I haven't begun my cleanup of that class yet.
The best way to cleanup a class is not to fill it with dirt in the first place. Writing code that has to be subsequently removed is a double waste of time.
Ok it is very unclear what you are asking and your code doesn't make too much sense and the fraction variable fraction is unknown.
and just a note here always clean up your code as write it since later you will never know where it is and will always be confusing.
try http://www.planet-source-code.com/vb/scripts/search.asp?lngWId=2.
for some examples, they always have what i need.
and if you are new to java and want to know more i would suggest the book Java Programming: From Problem Analysis to Program Design, it explains everything from main method to GUI design.
and in future please explain your problem in more detail, we have no idea what you are asking.
Thanks.