为什么我的代码存储器会进入我的temps数组?

时间:2018-03-01 23:41:15

标签: arraylist

System.out.print("What would you like to decode? ");
        String fileName1 = console.next();
        System.out.print("Save the results as: ");
        resultFileName = console.next();
        int token1;
        Scanner inFile1 = new Scanner(new 
File(fileName1)).useDelimiter("[" + "," + " ]");
        List<Integer> temps = new ArrayList<Integer>();
        while (inFile1.hasNext()) {
            token1 = inFile1.nextInt();
            temps.add(token1);
            }
        for(int i = 0; i <= temps.size() - 1; i++) {
            int x = temps.get(i);
            System.out.print((char) x); 
        }

当我运行它时,它说&#34; token1 = inFile1.nextInt();&#34;

这是文件中的内容:[89,111,117,39,114,101,32,97,108,109,111,115,116,32,116,104,101,114,101, 46,32,75,101,101,112,32,117,112,32,116,104,101,32,103,111,111,100,32,119,111,114,107,33]

2 个答案:

答案 0 :(得分:0)

使用与inFile1.hasNextInt()相对的inFile1.hasNext()。这样,您可以确保将下一个值解释为int

我认为inFile1.hasNext()正在解析为true,因为您仍然在文件中留下了字符]

答案 1 :(得分:0)

useDelimiter仅用于分隔您的ints。因此,您必须手动解析[]并致电Scanner inFile1 = new Scanner(new File(fileName1)).useDelimiter(",");以解析ints

编辑:用于解析&#39; [&#39;例如,您可以使用: Pattern p = Pattern.compile("["); scanner.next(p);