有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用null参数生成if语句?

如何使if语句检查某个内容是否为null,并且如果if语句为true将返回null

public String getMiddle(String word)
   {
      // I don't know if 'is null' or 'return null' are actually things
      if (is null){
         return null;
      }
   }

另外,输入的一个例子会使其为空吗


共 (1) 个答案

  1. # 1 楼答案

    正如Aominè和litelite所说(同时以相同的方式),您可以这样做:

    if(word == null) return null;
    

    第二个问题:

    Also, what would be an example of an input that would make it null?

    如果调用类似getMiddle(null)的方法,那么这是可能的

    以下是一系列检查单词是否为空的方法:

    1:

    private static void getWord(String str){
        try {
            if(!str.equals("")) {
                System.out.println(str);
            }
        } catch (NullPointerException e) {
            System.out.println("Your word was null.");
        }
    }
    

    2:

    private static void getWord(String str){
        try {
            if(!str.equals(null)) {
                System.out.println(str);
            }
        } catch (NullPointerException e) {
            System.out.println("Your word was null.");
        }
    }
    

    3:

    private static void getWord(String str){
        try {
            if(str != null) {
                System.out.println(str);
            }
        } catch (NullPointerException e) {
            System.out.println("Your word was null.");
        }
    }