java.util.InputMismatchException从文件加载时

时间:2016-10-14 00:03:01

标签: java file java.util.scanner inputmismatchexception

您好我正在尝试使用此代码从文本文件中读取,文本文件应该通过检查下一行的字符串是以停止,播放还是持续时间开始,然后传递它来定义音高合成所以它可以发挥。

有没有人知道为什么它会导致错误并且无法正常工作?

代码和示例文本文件如下:

      public class MyTuneRunnable implements Runnable {
      //method start
        public void run(){
           Thread thread = Thread.currentThread();
           thread.getName();
              try {
                    Synthesizer synth = MidiSystem.getSynthesizer();
                    synth.open();
                    MidiChannel[] channels = synth.getChannels();
            File file = new File(Loader.instance().getConfigDir().getParentFile().getAbsolutePath()+"/"+"LoadTunes"+"/"+Config.tuneName+".txt");
            try {
                Scanner intLoader = new Scanner(file);
                Scanner stringLoader = new Scanner(file);
                while (intLoader.hasNextLine()&stringLoader.hasNextLine()) {
                    int i = intLoader.nextInt();
                    String s = stringLoader.next();
                    if (s.startsWith("play")){
                        channels[channel].noteOn( i, volume);
                    }
                    if (s.startsWith("stop")){
                        channels[channel].noteOff( i, volume);
                    }
                    if (s.startsWith("duration")){
                        Thread.sleep(i);
                    }
                }
                intLoader.close();
                stringLoader.close();
            } 
            catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            synth.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        }
      }

关于文本文件的外观......这是一个例子:

0 This is a comment
0
play 60         This is a C note and it is set to play because of 'play <note number>'
0
duration 200    This is saying the currently playing notes will make sound
0
stop 60         This stops playing the C note because of the 'stop <note number>'

1 个答案:

答案 0 :(得分:1)

您的问题源于在同一文件中使用两个扫描程序。你假设当一个扫描仪读取一个令牌时,它们都会推进它们的指针,而这不会发生 - 只有读取令牌的扫描仪才会前进,因此,你试图读取一个令牌。当扫描仪指向文本时为int。不要这样做,只使用一台扫描仪。

话虽如此,您可以使用多个扫描程序,但只有其中一个读取文件,这是我经常做的事情:一个扫描程序读取文件,通过nextLine()获取每一行字符串,为每行文本创建另一个扫描程序,以提取行中找到的标记。当我这样做时,我会小心地关闭每一行扫描仪,当然完成它后关闭文件扫描仪。

相关问题