如何在Java中将null输入从用户替换为Zero

时间:2014-12-29 09:24:54

标签: java

我试图通过使用替换用户输入为空或零  ---如果( “”。等于(br3.readLine()))。  我无法做到这一点。请帮助我。

import java.io.*;
import java.util.*;

public class abc{
    public static void main(String[] args) throws IOException
    {
        System.out.println("enter the no of test cases");
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int a=Integer.parseInt(br.readLine());
        System.out.println("no of test cases:"+a);

        for (int j =0;j<a;j++)
        {
            System.out.println("enter for the"+(j+1)+" case");
            System.out.println("enter the no of tress");
            BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
            int b=Integer.parseInt(br.readLine());
            System.out.println("no of tress:"+b);
            int[] ar=new int[b];
            for (int i =0;i<b;i++)
            {
                System.out.println("enter the plucks for tree:"+i);
                BufferedReader br3=new BufferedReader(new InputStreamReader(System.in));
                if("".equals(br3.readLine()))
                {
                    ar[i]=0;
                }
                else
                {
                    ar[i]=Integer.parseInt(br3.readLine());
                }
            }
            System.out.println("hello");
            for (int i =b-1;i>=0;i--)
            {
                System.out.println(ar[i]+"\t");
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

if("".equals(br3.readLine()))是不够的,因为readLine可能会返回null。

尝试:

String line = br3.readLine();
if(line == null || line.equals(""))

String line = br3.readLine();
if(line == null || line.isEmpty())

答案 1 :(得分:0)

您的代码运行正常。你在第16行做了一个错字。

BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
            int b=Integer.parseInt(br1.readLine());