【问题标题】:Scanner isn't reading the last int on each line because of my delimiter由于我的分隔符,扫描仪没有读取每一行的最后一个 int
【发布时间】:2011-10-30 12:08:04
【问题描述】:

我正在尝试使用 Scanner 类读取下面显示的简单文本文件,并将分隔符设置为 scanner.useDelimiter(","); 但是您可以看到每行末尾没有逗号,因此扫描仪不会读取每行的最后一个数字。有人可以建议如何解决这个问题吗?

提前感谢您的帮助。

文本文件:

0,4,4,0,-4,2,2,8,16,20,20,12,8
1,6,7,1,-6,4,2,6,12,19,22,12,8
2,6,8,2,-7,5,2,4,11,19,23,14,8
3,4,8,4,-6,6,0,3,11,20,24,15,8
4,4,7,3,-5,5,0,0,12,20,24,16,10

这也是我的代码: public class ECGFilereader { // 从 SD 卡读取心电图文件

public final static int numChannels = 12;   // the data is stored in 12 channels, one for each lead
public final static int numSamples = 6; //500 = fs so *6 for 6 seconds of data
public File file;
private Scanner scanner;
short [] [] ecg = new short [numChannels] [numSamples];

 public ECGFilereader (String fname) throws FileNotFoundException 
 {
    File file = new File(Environment.getExternalStorageDirectory() +"/1009856.txt");        //accesses the ecg file from the SD card

    scanner = new Scanner(file);

    scanner.useDelimiter(",");  
}
public boolean ReadFile(Waveform[] waves) // sorts data into and array of an array (12 channels each containing 5000 samples)
{
    for (int m=0; m<numSamples && scanner.hasNextInt(); m++)        //
    {
        scanner.nextInt();

        for (int chan = 0; chan<numChannels && scanner.hasNextInt(); chan++)    //&& scanner.hasNextInt()
        {
            ecg [chan] [m] = (short) scanner.nextInt();     

            if (!scanner.hasNextInt())
            {
                if (scanner.hasNextLine())
                {
                    scanner.nextLine();
                    //scanner.nextInt();
                }
            }
        }
        if (!scanner.hasNextInt())
        {
            if (scanner.hasNextLine())
            {
                scanner.nextLine();
                //scanner.nextInt();
            }
        }
    }

【问题讨论】:

  • 您尝试过类似scanner.useDelimiter(",|\n"); 的方法吗?
  • 我试过了,由于某种原因没有效果

标签: android java.util.scanner delimiter text-files number-with-delimiter


【解决方案1】:

应该是scanner.useDelimiter(",|\\n"); 因为您希望编译器在字符串中放入“\n”而不是“\n”,编译器会将\视为转义字符。

【讨论】:

  • 我试过这个,它让我的文件读取每隔一个 int 并将它放在正确的位置但是它仍然不会从该行读取最后一个 int 所以最后一行的 arrya 仍然存在作为 0,0,0,0,0...
【解决方案2】:

当设置为 scanner.useDelimiter(",|\\n"); 时,分隔符仍然没有拾取行尾

我无法准确解释原因,但事实证明我也需要在其中添加 \r :

scanner.useDelimiter(",|\\r\\n");

【讨论】:

    【解决方案3】:

    试试这样:

    public boolean ReadFile(Waveform[] waves) {
        while(scanner.hasNextInt()){
            if(scanner.hasNextInt()){
                ecg [chan] [m] = (short) scanner.nextInt();
            }
            if(scanner.hasNextLine()){
                scanner.nextLine(); 
            }       
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多