使用nextDouble()

时间:2016-04-15 18:15:12

标签: java

以下是我正在为应用程序构建的面板的当前代码:

import javax.swing.*;
import java.util.*;
import java.io.*;

public class BookListPanel extends JPanel
{
    private JList<String> bookList;
    private String[] list = new String[20];
    private double[] priceList = new double[7];
    private File priceFile = new File("BookPrices.txt");
    int counter = 0;

    public BookListPanel() throws FileNotFoundException, InputMismatchException
    {
        Scanner fileReader = new Scanner(priceFile).useDelimiter(",\\s|$|\\n");
        while(fileReader.hasNext())
        {
            list[counter] = fileReader.next();
            priceList[counter] = fileReader.nextDouble();
            counter++;
        }

        bookList = new JList<>(list);
        bookList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        add(bookList);
    }
}

我正在尝试阅读包含混合信息的文件,此处仅供参考:

I Did It Your Way, 11.95
The History of Scotland, 14.50
Learn Calculus in One Day, 29.95
Feel the Stress, 18.50
Great Poems, 12.95
Europe on a Shoestring, 10.95
The Life of Mozart, 14.50

当我尝试构建应用程序时,我在nextDouble行收到InputMismatchException:

--------------------Configuration: <Default>--------------------
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at BookListPanel.<init>(BookListPanel.java:26)
    at BookstoreGUI.<init>(BookstoreGUI.java:39)
    at Bookstore.main(Bookstore.java:13)

我一直在努力解决这个问题,并且已经采取了取出nextDouble行并直接读取String数组并使用这样的计数器数字打印出来:

    Scanner fileReader = new Scanner(priceFile).useDelimiter(",\\s|$|\\n");
    while(fileReader.hasNext())
    {
        list[counter] = fileReader.next();
        System.out.println(counter + ": " + list[counter]);
        counter++;
    }

我收到了这个输入:

0: I Did It Your Way
1: 11.95

2: The History of Scotland
3: 14.50

4: Learn Calculus in One Day
5: 29.95

6: Feel the Stress
7: 18.50

8: Great Poems
9: 12.95

10: Europe on a Shoestring
11: 10.95

12: The Life of Mozart
13: 14.50
14: 

这让我相信,即使我在分隔符列表中有换行符表达式,但只要它读取双精度表时它仍然包含它(因为在读取数字后添加了额外的行)。我想知道是否有一些我排除或丢失的东西可以消除该换行符,以便我可以将数字读入双数组,或者这可能是我完全没有的东西?

非常感谢

1 个答案:

答案 0 :(得分:0)

您定义分隔符的方式不起作用。你的字符串中有空格(如<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="layer1"> <pre id="moto1" class="position"> AA </pre> <pre id="moto12" class="position"> BB </pre> </div> <div id="consola"> </div>中所示)。

这有效:

"I Did It Your Way"

说明:

  • 匹配其中一个:useDelimiter("[,$\\v]\\s*") ,或垂直空格(行分隔符)
  • 然后匹配零个或多个空格(因为字符串和双精度由$分隔)