UserAbdur
UserAbdur

Reputation: 29

Ternary Operator in java with multiple statements

I want to write multiple statements in Ternary Operator..But dont know how to write. I want like this,

public static void main(String[] args) {

    String replaceString,newString;
    Scanner user_input=new Scanner(System.in);
    String input=user_input.next();
    boolean choice=true;
    if(choice==true){
        System.out.println("Enter string to replace");
        replaceString=user_input.next();
        System.out.println("Enter new string");
        newString=user_input.next();
        input.replace(replaceString, newString);
        }
}

I want to write the above code in java using ternary operator.Please help

Upvotes: 0

Views: 572

Answers (1)

andrewJames
andrewJames

Reputation: 22052

Not entirely sure what you want to do here, or why you want to do it. Also, I will focus on your specific question, and not on your use of Scanner.

Is there something about your sample code's if statement that you don't like?

Why do you want to use a ternary operator?

Bottom line: I think a ternary operator is a bad fit for what you may be trying to do.

The Java ternary operator is a one-line way of writing a simplified if...else... assignment. In your sample code, you have an if but no else - and no obvious assignment - unless you mean to assign the result of this line...

input.replace(replaceString, newString);

...to a String variable. I may be completely wrong about your intention.

The values of a ternary operator (after the ? question-mark and separated by the : colon) can be assigned by methods, as long as the methods return the expected type.

The following uses a ternary operator:

//
// BAD use of the ternary operator - NOT RECOMMENDED:
//
public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);
    String input = userInput.next();
    boolean choice = true;
    String replaced = (choice == true) ? whenTrue(userInput, input) : null;
}

private static String whenTrue(Scanner userInput, String input) {
    System.out.println("Enter string to replace");
    String replaceString = userInput.next();
    System.out.println("Enter new string");
    String newString = userInput.next();
    return input.replace(replaceString, newString);
}

You would be better off using if, in my opinion.

Upvotes: 2

Related Questions