IndexOf(),字符串索引超出范围:-1 [英] IndexOf(), String index out of bounds: -1

查看:735
本文介绍了IndexOf(),字符串索引超出范围:-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道发生了什么。我有一个产品列表以及一个用标签分隔的数字。当我使用 indexOf()查找选项卡时,我得到一个 String index of bounds error ,它说索引为-1。这是代码:

I have no idea what is happening. I have a list of products along with a number separated with a tab. When I use indexOf() to find the tab, I get a String index out of bounds error, and it says the index is -1. Here's the code:

package taxes;

import java.util.*;
import java.io.*;

public class Taxes {

    public static void main(String[] args) throws IOException {
        //File aFile = new File("H:\\java\\PrimeNumbers\\build\\classes\\primenumbers\\priceList.txt");
        File aFile = new File("C:\\Users\\Tim\\Documents\\NetBeansProjects\\Taxes\\src\\taxes\\priceList.txt");
        priceChange(aFile);
    }

    static void priceChange(File inFile) throws IOException {
        Scanner scan = new Scanner("priceList.txt");
        char tab = '\t';
        while (scan.hasNextLine()) {
            String line = scan.nextLine();
            int a = line.indexOf(tab);
            String productName = line.substring(0,a);
            String priceTag = line.substring(a);
        }
    }
}

这是输入:

Plyer set   10
Jaw Locking Plyers  10
Cable Cutter    7
16 oz. Hammer   5
64 oz. Dead Blow Hammer 12
Sledge Hammer   20
Cordless Drill  22
Hex Impact Driver 50
Drill Bit Set   30
Miter Saw   200
Circular Saw    40


推荐答案

 Scanner scan = new Scanner("priceList.txt");

这行代码错误。此Scanner实例将扫描字符串priceList.txt。它不包含选项卡,因此 indexOf 返回 -1

This line of code is wrong. This Scanner instance will scan the String "priceList.txt". It doesn't contain a tab, therefore indexOf returns -1.

将其更改为:

 Scanner scan = new Scanner(inFile);

使用方法参数,即 priceList.txt <的所需文件实例/ em>。

to use the method argument, that is the desired file instance of your priceList.txt.

这篇关于IndexOf(),字符串索引超出范围:-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆