字符串java上的空指针异常
代码是缩短名称 当我在Hackerrank中执行时,temp.length()、temp.toUpperCase()、temp.substring()上存在NullPointerException。 第一行包含一个整数N,表示测试用例的数量 样本输入 三, 莫汉达斯·卡拉姆坎德·甘地 默文R桑德哈拉姆酒店 穆图 样本输出 甘地 M R Sundharam 穆图字符串java上的空指针异常,java,string,nullpointerexception,Java,String,Nullpointerexception,代码是缩短名称 当我在Hackerrank中执行时,temp.length()、temp.toUpperCase()、temp.substring()上存在NullPointerException。 第一行包含一个整数N,表示测试用例的数量 样本输入 三, 莫汉达斯·卡拉姆坎德·甘地 默文R桑德哈拉姆酒店 穆图 样本输出 甘地 M R Sundharam 穆图 import java.io.*; 导入java.util.*; 公共类解决方案{ 公共静态void main(字符串[]args)引
import java.io.*;
导入java.util.*;
公共类解决方案{
公共静态void main(字符串[]args)引发IOException{
扫描仪sc=新的扫描仪(System.in);
int size=sc.nextInt();
BufferedReader br=新的BufferedReader(新的InputStreamReader(System.in));
字符串ar[]=新字符串[大小];
对于(int i=0;i for(int i=0;i在第一个for循环中从ar[i]=br.readLine();
更改为ar[i]=sc.nextLine();
。BufferedReader
的readLine()
方法在流发送EOF
信号时返回null
。这可能是导致NullPointerException
的原因。您的程序甚至没有编译。它如何生成NPE?您没有包含堆栈跟踪,但是如果NPE发生在for(int j=0;j
,这将是因为文件没有您认为的那么长,所以temp
为空。当遇到Scanner.nextLine()
中的false
时,您应该中断循环,如果ar[i],则在第二个循环中==null
。并抱怨输入文件的格式不正确。您应该将BufferedReader
全部删除。BufferedReader
按构造不是null,并且没有像Scanner.readLine()
这样的方法。对不起,我的错误。方法是nextLine()该方法返回一个布尔值
,因此代码不会编译。这里没有任何东西可以解决NullPointerException
。
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException {
Scanner sc= new Scanner(System.in);
int size= sc.nextInt();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String ar[] =new String[size];
for (int i= 0; i < size; i++) {
ar[i]=br.readLine();
}
for(int i= 0;i<size;i++){
String temp=" ";
temp=ar[i];
int pos=0;
for (int j= 0; j < temp.length(); j++)
if(temp.charAt(j)==' '){
System.out.print(temp.toUpperCase().charAt(pos)+ " ");
pos=j+1;
}
}
System.out.println(temp.toUpperCase().charAt(pos)+temp.substring(pos+1));
}
}
}