-1

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
  • 2
    `System.out.println(n.equals(s2) ? "ITS A PALINDROME" : "ITS NOT A PALINDROME");` – shmosel Nov 16 '17 at 20:07
  • @shmosel ternaries are basically just syntactic sugar for an if statement. But maybe that's what OP wants anyway. – Alex von Brandenfels Nov 16 '17 at 20:09
  • @shmosel A ternary is basically an `if-statement` but its a cool thought - not sure what the OP wants though.. – Joe Iddon Nov 16 '17 at 20:09
  • `String out = "ITS NOT A PALINDROME"; while (n.equals(s2)) { out = "ITS A PALINDROME"; break; } System.out.println(out);` – shmosel Nov 16 '17 at 20:11
  • `try { assert n.equals(s2); System.out.println("ITS A PALINDROME"); } catch (AssertionError e) { System.out.println("ITS NOT A PALINDROME"); }` – shmosel Nov 16 '17 at 20:14
  • 3
    I'm voting to close this question as off-topic because it belongs on [codegolf.se]. – shmosel Nov 16 '17 at 20:15
  • Could put the answers in an array `string[] results = new string[]{"ITS A PALINDROME", "ITS NOT A PALINDROME"}`. Then map to a result `System.out.println(results[0])`; – Felix Castor Nov 16 '17 at 20:18
  • You could use a loop with `charAt`, but that's little more than disguising `if` statements really. – AntonH Nov 16 '17 at 20:19

4 Answers4

2

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.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • I was thinking it was `Map ...`. Put the original String in first as key with a value of `false`, then put in the reverse String with a value of `true`. Then display the value with the key being the original string, where the value would have changed if the reverse is equal to the original string. – AntonH Nov 16 '17 at 20:18
  • You cannot do it in this way as to get the `String`, you need to test the `n.equals(s2)` with a conditional statement. To not evaluate the `boolean` expression in your code, the `Map` needs to have as key what you don't want to test : the boolean value. So `Map` makes more sense. – davidxxx Nov 16 '17 at 20:25
  • I realise I wasn't very clear in my explanation. This is what I meant: https://www.ideone.com/ob8p8z So using the String to test as a key, and having the value be if it's a palindrome or not. – AntonH Nov 16 '17 at 20:30
  • It doesn' t display the expected message and it cannot handle all cases. Why use a not adapted structure ? – davidxxx Nov 16 '17 at 20:41
  • It displayed the expected value for me. And it was an exercise of possibility that anything else. The question, as I saw it, was "Is this possible?". And I found my example to work as expected. I would not use it, though, as it's neither readable nor efficient. – AntonH Nov 16 '17 at 20:45
  • Also, what cases can it not handle? I can't think of any that it wouldn't take into account. – AntonH Nov 16 '17 at 20:52
0

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
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0

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.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

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));
}
11thdimension
  • 10,333
  • 4
  • 33
  • 71