想问下这个代码哪里错了,为什么一直出现NullPointerException异常呢?

发布时间:2019-07-31 10:12:03

package MyThread;

import java.util.Scanner;

public class Checkmajuscule extends Thread {

    public  String s;

    public Checkmajuscule(){}

    public Checkmajuscule(String name){

        super(name);

    }

    public  void run(){

        while(true){

            for(int i = 0;i<s.length();i++){

                char c = s.charAt(i);

                if(c>=65&&c<=90){

                    System.out.println(c+"------>");

                    c+=32;

                    System.out.println(c);

                }

            }

            s="";

            try{

                Thread.sleep(1);

            }catch(Exception e){}

        }

    }

    public static void main(String[]args){

        Checkmajuscule chk = new Checkmajuscule();

        Thread t = new Thread(chk);

        t.start();

        Scanner in = new Scanner(System.in);

        while(true){

            chk.s=in.nextLine();

        }

    }

}


推荐回答

不知你程序的目的,你程序运行时,新建的线程中,s没有赋值,它为null,你的

for(int i = 0;i<s.length();i++){

中的s.length就会报NULL错,且你的两个死循环看去都没有意义

若你要不报错,在 第一个while(true)前加

       if (s==null)             return;

但你程序不会有任何输出结果的

以上问题属网友观点,不代表本站立场,仅供参考!