如何解决java.lang.numberformatexception:空字符串

yqkkidmi  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(392)

下面的代码不断给出java.lang.numberformatexception:空字符串,但我不明白原因。

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Problem_S1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int n;
        Double c=0.0, e=0.0;
        String number = null;
        Scanner s = new Scanner(System.in);
        List<Double> T = new ArrayList<Double>();
        List<Double> R = new ArrayList<Double>();
        String[] Q = new String[2] ;

        System.out.println("Enter the number of entries");
        n = s.nextInt();
        if(n<= 1) {
            System.out.println("The number of observations should be greater than one, Try again!");
            return;
        }
        else {
            System.out.println("Make sure that there is only one whitespace between each number on a line");
        }

        for(int i=0;i<=n;i++) {
            number = s.nextLine();
            Q = number.split("\\s");

            T.add(Double.parseDouble(Q[0]));
            R.add(Double.parseDouble(Q[1]));    
        }
        for(int i=0;i<=T.size();i++ ) {
            for(int j=0;j<=R.size();j++) {
                if(i==j) {
                    c= R.get(i)/T.get(i);
                    if(c>e){
                        e=c;
                    }
                }

            }
        }

        System.out.println(e);

    }

}

在输入第一个输入之后,我得到println,但是随后,错误直接弹出。我甚至不能为字符串数组q输入所需的输入。这就是控制台上发生的事情。

Enter the number of entries
3
Make sure that there is only one whitespace between each number on a line
Exception in thread "main" java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
    at java.lang.Double.parseDouble(Unknown Source)
    at ccc2020.Problem_S1.main(Problem_S1.java:35)
3qpi33ja

3qpi33ja1#

这是因为scanner.nextint方法不读取输入中的换行符,因此对scanner.nextline的调用在读取该换行符后返回。
解决方法是将s.nextline()放在s.nextint()之后。
它在给定的链接上得到了很好的解释https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/

相关问题