I'm trying to create a programme like this previous one I've made;
It simply gives a boolean true/false on if a string backwards is still spelt the same way.
I've created this using if statements, but would like too know if it is possible too create using only methods and loops, and if so how? I have looked for duplicates, and there are similar posts that achieve what I have below, but everything I find uses if else statements
Any help appreciated as always; thanks.
import java.util.*;
public class testingthingsv24 {
private static Scanner in;
public static void main(String args[])
{
in = new Scanner(System.in);
System.out.println("Please Enter Your String: ");
String n=in.nextLine();
System.out.println("Your String Was: "+n);
StringBuffer str=new StringBuffer(n);
StringBuffer str2=new StringBuffer(str.reverse());
String s2=new String(str2);
System.out.println("Reversed Is: "+str2);
if(n.equals(s2))
System.out.println("ITS A PALINDROME");
else
System.out.println("ITS NOT A PALINDROME");
}
}
Output:
Please Enter Your String:
dad
Your String Was: dad
Reversed Is: dad
ITS A PALINDROME
To test a result, generally a conditional statement (if, ternary or switch) appears useful.
You have to avoid using conditional statements as these conditions are annoying by making your code not readable, brittle, error prone, etc..
To do that, you have to favor abstraction over sequential logic.
In your simple case, you could for example introduce a structure (key-value) that associate each boolean value to the String message.
Map<Boolean, String> messageByBoolean = new HashMap<>();
messageByBoolean.put(true, "ITS A PALINDROME");
messageByBoolean.put(false, "ITS NOT A PALINDROME");
...
System.out.println(messageByBoolean.get(n.equals(s2));
But does it make really sense ? It looks like an overhead as you have just two possibilities.
With 5 or 10 of them, it would make much sense.
would like too know if it is possible too create using only methods and loops, and if so how?
Sure. The if statement is redundant in Java. There are plenty of other conditionals in the language, and there are multiple ways that you could implement the semantics of an if statement (including an else clause, if desired) without actually using an if statement.
For example, you can always replace
if (condition) {
// statements when true ...
} else {
// statements when false ...
}
with
if_replacement: do {
while (condition) {
// statements when true ...
break if_replacement;
}
// statements when false ...
} while (false);
Note that that has no association whatever with any particular problem, and that it uses only looping constructs. A somewhat simpler form is possible if you don't need the analog of an else block. In principle you could replace every if in any program with a construct of this form.
This can't really be achieved any more efficiently (as in using a method or function). The reason is that the if-statement:
if (n.equals(s2))
System.out.println("ITS A PALINDROME");
else
System.out.println("ITS NOT A PALINDROME");
at the processor level would simply evaluate the statement: n.equals(s2) and then switch to the first println if true else go to the second println. If you think about this, there isn't really any optimisation that you can do as this condition will always have to be evaluated and always have to carry out the necessary task (printing).
However, having said that this is the most optimised solution for this part of your code, you can make the code slightly shorted and less bulky without a big if-else.
And to do that, the best solution IMO would be #shmosel's with a ternary expression. This would replace this if-else block with a simple line:
System.out.println(n.equals(s2) ? "ITS A PALINDROME" : "ITS NOT A PALINDROME");
This works due to the general format of a ternary statement:
condition ? task if true : task if false
Can be done with recursion too
boolean isPalindrome (String s) {
return s.length() < 2 ? true : s.charAt(0) == s.charAt(s.length() - 1) && isPalindrome(s.substring(1,s.length() - 1));
}
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
m trying to write a super simple piece of code which asks "are we nearly there yet" if the user inputs yeah they get the answer "finally" if the user says anything other than yeah the computer keeps asking are we nearly there yet?
for some reason when I run the code below even if I type "yeah" after the first prompt the computer just keeps printing are we nearly there yet? and can't get through the loop.
import java.util.Scanner;
class FirstAttempt {
public static void main(String args[]) {
Scanner s= new Scanner(System.in);
String a =" ";
System.out.println("are we nearly there yet?");
a = s.next();
while ( a != "yeah" & a != "Yeah")
{System.out.println("are we nearly there yet?");
s = new Scanner(System.in);
a = s.nextLine(); }
System.out.println("finally");
} }
The issue is just in the way you wrote the condition in the while.
The application doesn't go in the loop, because your condition is always false. Basically, that's because you are not comparing the values of the String objects, but the values of their instances.
In Java, you must compare one String object with another by using equals and not with operators != or ==
Plus, I suggest that you use &&, instead of &. The first one is short-circuiting, which means that the first condition is evaluated, and only in case it's true the second one is also evaluated.
However, there is a more efficient way to do that. Look at this:
while ( !a.equalsIgnoreCase("yeah")) )
To test if strings are equal you need to use equals:
while ( !(a.equals("yeah") || a.equals("Yeah")) )
& is a bitwise operation -- you probable want the logical operations && and ||.
Also, no need to create a new Scanner inside the loop. Just keep using the one from the top of the main method.
The & operator, otherwise known as 'bitwise and' will evaluate all conditions regardless of whether the first condition is true or false. So while the input "yeah" makes the first condition false and thus loop-breaking, the second condition is still evaluated to true and keeps the loop going. You should use &&
You have to change
while ( a != "yeah" & a != "Yeah")
to
while ( a != "yeah" || a != "Yeah")
as it can't be both at the same time
Dear Stackoverflow community I am Struggling with one task on repl.it (018) Conditional Statements 4
So they want me to do that :
Instructions from your teacher:
For you to do:
Given a string variable "word", do the following tests
If the word ends in "y", print "-ies"
If the word ends in "ey", print "-eys"
If the word ends in "ife", print "-ives"
If none of the above is true, print "-s"
No more than one should be printed.
and my code looks like this :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String word = inp.nextLine();
//DO NOT CHANGE ABOVE CODE! Write your code below
if(word.endsWith("y"){
System.out.println("-ies");
}
else if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else{
System.out.println("-s");
}
}
}
When I run it for example my input is :Hey
and of course my code will go through the code and see if the first statement is correct and yes it is equal because y = y at the end and that is WRONG!
My question is how can i let my code compare the last 2 or 3 characters so it will print out the right value when I input Hey.
If I input Hey it should print out :
-eys and not -ies
Ty
Since ending with "ey" is a subset of ending with "y", your 2nd if will never be true.
Change the order of your tests to the most specific first:
if(word.endsWith("ey"){
System.out.println("-eys");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
reorder the conditions as such:
if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else{
System.out.println("-s");
}
This means we hoist the condition that is most specific and put the less specific ones below.
I've put the else if(word.endsWith("y")) as the last of the else ifs but it really doesn't matter where within the else if chaining you put it as long as it's before the condition if(word.endsWith("ey")) things should be fine.
I'm trying to learn java but I'm stuck trying to do a single program which concerns Do While Statement with two conditions. Specifically, I want a method to run until the user write "yes" or "no". Well, down there is my thing, what is wrong with it?
String answerString;
Scanner user_input = new Scanner(System.in);
System.out.println("Do you want a cookie? ");
do{
answerString = user_input.next();
if(answerString.equalsIgnoreCase("yes")){
System.out.println("You want a cookie.");
}else if(answerString.equalsIgnoreCase("no")){
System.out.println("You don't want a cookie.");
}else{
System.out.println("Answer by saying 'yes' or 'no'");
}while(user_input == 'yes' || user_input == 'no');
}
}}
I'd do something similar to Tim's answer. But to do things the way you were trying to do them, you have a lot of problems that need to be fixed:
(1) String literals in Java are surrounded by double quote marks, not single quote marks.
(2) user_input is a Scanner. You can't compare a scanner to a string. You can only compare a String to another String. So you should be using answerString in your comparison, not user_input.
(3) Never use == to compare strings. StackOverflow has 953,235 Java questions, and approximately 826,102 of those involve someone trying to use == to compare strings. (OK, that's a slight exaggeration.) Use the equals method: string1.equals(string2).
(4) When you write a do-while loop, the syntax is do, followed by {, followed by the code in the loop, followed by }, followed by while(condition);. It looks like you put the last } in the wrong place. The } just before the while belongs to the else, so that doesn't count; you need another } before while, not after it.
(5) I think you were trying to write a loop that keeps going if the input isn't yes or no. Instead, you did the opposite: you wrote a loop that keeps going as long as the input is yes or no. Your while condition should look something like
while (!(answerString.equals("yes") || answerString.equals("no")));
[Actually, it should be equalsIgnoreCase to be consistent with the rest of the code.] ! means "not" here, and note that I had to put the whole expression in parentheses after the !, otherwise the ! would have applied only to the first part of the expression. If you're trying to write a loop that does "Loop until blah-blah-blah", you have to write it as "Loop while ! (blah-blah-blah)".
I might opt for a do loop which will continue to take in command line user input until he enters a "yes" or "no" answer, at which point the loop breaks.
do {
answerString = user_input.next();
if ("yes".equalsIgnoreCase(answerString)) {
System.out.println("You want a cookie.");
break;
} else if ("no".equalsIgnoreCase(answerString)) {
System.out.println("You don't want a cookie.");
break;
} else {
System.out.println("Answer by saying 'yes' or 'no'");
}
} while(true);
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
So, for some reason I'm having problems just USING a string input.
I don't know why. Maybe it's some incredibly stupid thing everyone knows, but I don't.
Here's the non-functioning code:
import javax.swing.*;
public class Thing {
public static void main(String[] args) {
String input;
JOptionPane.showMessageDialog(null,"Welcome to the test...");
input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
String i = input;
if(i == "Yes") {
tutorial();
} else if(input=="'Yes'") {
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
} else {
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}
}
Yes, I actually do have a tutorial method somewhere else, and it works fine.
The main problem is that if I enter 'Yes' or Yes, it still goes to the final else.
I only put in the
String i = input;
and changed it from
if(input == "Yes") {
because it didn't work then, either.
So what am I doing wrong?
Don't use the == operator to compare Strings, use equals() instead, as thoroughly explained here, here, here, here or any of the numerous duplicates.
if ("Yes".equals(input))
Or even
if ("yes".equalsIgnoreCase(input))
Notice that the operation is invoked on the "yes" literal to avoid a possible NullPointerException in the case input was null and the operation was invoked on it (Yoda condition).
From the Java Language Specification, Chapter 15 - Expressions, section 21 - Equality Operators:
15.21.3. Reference Equality Operators == and !=
While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters (ยง3.10.5). The contents of two strings s and t can be tested for equality by the method invocation s.equals(t).
As mentioned, the problem is that you are comparing this String using the == comparator, not the .equals() method.
If you are running on Java 7, my advice, for a cleaner solution, would be also to wrap this in a switch statement:
JOptionPane.showMessageDialog(null,"Welcome to the test...");
String input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
switch (input) {
case "Yes":
tutorial();
break;
case "'Yes'":
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
break;
default:
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}
I'm programming a traditional hangman game in Java. What I'm currently stuck on is to find if the users character input is not a character within the String.
if(getLetters.indexOf(userCharInput)==-1) //getLetters is the StringBuilder, and the userCharInput is a String.
{
playerCounter++;
}
This is the section that I seem to have trouble in, I've looked at different indexOf examples and I've formulated this to work with my program.
The problem is, It doesn't work. I set it so the player has 3 chances to guess the word, since the default word is "apple" I guessed 'a', 'p', and 'l', which leaves 'e' to be guessed. Now I intentionally make 3 incorrect guesses and it doesn't proc the next else if:
else if(playerCounter == 3)
{
System.out.println("All lives are gone! Game Over!");
playerCounter = 1; //resets the playerCounter to one.
System.exit(0);
}
Any help will be greatly appreciated.
It's because when you keep guessing the wrong letter, the first if statement is evaluated to true:
if(getLetters.indexOf(userCharInput)==-1) //getLetters is the StringBuilder, and the userCharInput is a String.
{
playerCounter++;
}
So you keep increasing playerCounter (beyond 3). This means that your next statement is unreachable (once it's greater than 3, it's not going to get any smaller, at least with the code you have posted so far). So else if (playerCounter == 3) may not be reachable.
I guess that your else if is part of another if statement that is getting true, so check that out.
The reason it was not working was because of the indexOf method being used improperly,it was partially because of the ordering of the if statements, but that was very miniscule to the primary issue. What had to be changed was the way I used the indexOf method.
ie. instead of gletter.indexOf(character); it should have been word.indexOf(character);
where word was the word that had to be guessed, and gletter was the StringBuilder used to keep track of user guesses.
Here's the Javadoc for StringBuilder:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html
Based on the code you've posted, I'm guessing:
1) You're saving the letters needed (e.g. the letters in the word "apple") to getLetters.
2) getLetters is type StringBuilder
3) if userCharInput is type "char", then indexOf() probably won't give the expected results
4) Substitute "if" for your "else if"
SUGGESTIONS:
Try changing "getLetters" to a "String", and see if that helps.
while (...) {
...
//getLetters is the StringBuilder, and the userCharInput is a String.
if(getLetters.indexOf(userCharInput)==-1) {
playerCounter++;
}
// Debug: comment this out once it's working
System.out.println ("userCharInput=" + userCharInput + ", playerCounter=" + playerCounter);
if(playerCounter == 3) {
System.out.println("All lives are gone! Game Over!");
playerCounter = 1; //resets the playerCounter to one.
System.exit(0);
}
...
}