繁体   English   中英

java中带有多个语句的三元运算符

[英]Ternary Operator in java with multiple statements

我想在三元运算符中写多个语句..但不知道如何写。 我想要这样的

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);
        }
}

我想使用三元运算符在java中编写上述代码。请帮忙

不完全确定您想在这里做什么,或者为什么要这样做。 此外,我将关注您的具体问题,而不是您对Scanner的使用。

您不喜欢示例代码的if语句吗?

为什么要使用三元运算符?

底线:我认为三元运算符不适合您可能尝试做的事情。

Java 三元运算符是一种编写简化if...else...赋值的单行方式。 在您的示例代码中,您有一个if但没有else - 并且没有明显的分配 - 除非您打算分配这一行的结果......

input.replace(replaceString, newString);

...到一个字符串变量。 我可能完全错了你的意图。

只要方法返回预期类型,三元运算符的值(在 ? 问号之后并由 : 冒号分隔)可以由方法分配。

以下使用三元运算符:

//
// 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);
}

在我看来,你最好使用if

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM