String空指针问题
package com.javasm.while_;
import javax.sound.midi.Soundbank;
import java.util.Scanner;
/**
* @author: JAVASM
* @classNAME: WhileDemo01
* @description:
* @date: 2021/3/26 21:16
* @version:0.1
* @since:1.8
*/
public class WhileDemo01 {
public static String str;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("韩梅梅,怎么样,可以了吗?y/n");
String anwser= input.nextLine();
//已确定的值与变量进行比较 避免出现空指针的问题(NullPointerException)
System.out.println("y".equals(str));
System.out.println(str.equals("y"));
}
}
程序输出的结果为:
韩梅梅,怎么样,可以了吗?y/n
y
false
Exception in thread "main" java.lang.NullPointerException
at com.javasm.while_.WhileDemo01.main(WhileDemo01.java:23)
Process finished with exit code 1
出现了NullPointerException空指针问题,在前面定义的str并没有赋值,默认值为null,与之后的字符y进行比较时,出现报错。
一般如果出现NullPointerException,可能就是某些变量没有赋初值。
通过while询问韩梅梅不断练琴走向成功
package com.javasm.while_;
import javax.sound.midi.Soundbank;
import java.util.Scanner;
/**
* @author: JAVASM
* @classNAME: WhileDemo01
* @description:
* @date: 2021/3/26 21:16
* @version:0.1
* @since:1.8
*/
public class WhileDemo01 {
public static String str;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("韩梅梅,怎么样,可以了吗?y/n");
String answer= input.nextLine();
//已确定的值与变量进行比较 避免出现空指针的问题(NullPointerException)
//System.out.println("y".equals(str));//结果为Flase
//System.out.println(str.equals("y"));//str为null,结果会报错。
while ("n".equals(answer)){
System.out.println("早上5点练琴,上午练钢琴,晚上练舞蹈");
System.out.println("韩梅梅,怎么样,可以了吗?y/n");
answer=input.nextLine();
}
System.out.println("韩梅梅,你成功了");
}
}
程序输出的结果为:
韩梅梅,怎么样,可以了吗?y/n
n
false
早上5点练琴,上午练钢琴,晚上练舞蹈
韩梅梅,怎么样,可以了吗?y/n
n
早上5点练琴,上午练钢琴,晚上练舞蹈
韩梅梅,怎么样,可以了吗?y/n
n
早上5点练琴,上午练钢琴,晚上练舞蹈
韩梅梅,怎么样,可以了吗?y/n
.........
y
韩梅梅,你成功了
Process finished with exit code 0