新手程序员需要建议:“字符串索引超出范围” - 爪哇

发布于 2024-12-08 20:41:03 字数 2313 浏览 0 评论 0原文

我对编程还很陌生,并且遇到了一个错误,我确信对于更有经验的人来说这是一个简单的修复方法。

这是我所得到的:

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

    public class ReadNamesFile
    {
        public static void main(String[] args) throws IOException {
        // make the names.csv comma-separated-values file available for reading
        FileReader f = new FileReader("names.csv");
        BufferedReader r = new BufferedReader(f);
        //
        String lastName="unknown", firstName="unknown", office="unknown";

        // get first line
        String line = r.readLine();

        // process lines until end-of-file occurs
        while ( line != null )
        {
           // get the last name on the line
           //
           // position of first comma
           int positionOfComma = line.indexOf(","); 
           // extract the last name as a substring
           lastName = line.substring(0,positionOfComma); 
           // truncate the line removing the name and comma
           line = line.substring(positionOfComma+1); 

           // extract the first name as a substring
           firstName = line.substring(0,positionOfComma); 
           // truncate the line removing the name and comma
           line = line.substring(positionOfComma+1);

           // extract the office number as a substring
           office = line.substring(0,positionOfComma);
           // truncate the line removing the name and comma
           line = line.substring(positionOfComma+2);
           //
           //        
           //
           // display the information about each person
           System.out.print("\nlast name = "+lastName);
           System.out.print("\t first name = "+firstName);
           System.out.print("\t office = "+office);
           System.out.println();
           //
           // get the next line
           line = r.readLine();
        }
    }
}

基本上,它会在 .csv 文件中查找姓氏、名字和办公室号码并将其打印出来。

当我编译时,我没有收到任何错误,但当我运行它时,我得到:

java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1955)
at ReadNamesFile.main(ReadNamesFile.java:34)

在尝试执行办公室号码部分之前,前两个(姓氏和名字)打印得很好,但办公室号码似乎不起作用。

有什么想法吗?

编辑:感谢所有的帖子,但我仍然无法真正弄清楚。有人可以发布一些真正愚蠢的东西吗?我已经尝试解决这个问题一个小时了,但我无法解决。

I'm pretty new to programming and I'm getting a error which I'm sure is a easy fix for more experienced people.

Here is what I have:

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

    public class ReadNamesFile
    {
        public static void main(String[] args) throws IOException {
        // make the names.csv comma-separated-values file available for reading
        FileReader f = new FileReader("names.csv");
        BufferedReader r = new BufferedReader(f);
        //
        String lastName="unknown", firstName="unknown", office="unknown";

        // get first line
        String line = r.readLine();

        // process lines until end-of-file occurs
        while ( line != null )
        {
           // get the last name on the line
           //
           // position of first comma
           int positionOfComma = line.indexOf(","); 
           // extract the last name as a substring
           lastName = line.substring(0,positionOfComma); 
           // truncate the line removing the name and comma
           line = line.substring(positionOfComma+1); 

           // extract the first name as a substring
           firstName = line.substring(0,positionOfComma); 
           // truncate the line removing the name and comma
           line = line.substring(positionOfComma+1);

           // extract the office number as a substring
           office = line.substring(0,positionOfComma);
           // truncate the line removing the name and comma
           line = line.substring(positionOfComma+2);
           //
           //        
           //
           // display the information about each person
           System.out.print("\nlast name = "+lastName);
           System.out.print("\t first name = "+firstName);
           System.out.print("\t office = "+office);
           System.out.println();
           //
           // get the next line
           line = r.readLine();
        }
    }
}

Basically, it finds the last name, first name and office number in a .csv file and prints them out.

When I compile I don't get any errors but when I run it I get:

java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1955)
at ReadNamesFile.main(ReadNamesFile.java:34)

Before trying to do the office number part, the first two (last and first name) printed out fine but the office number doesn't seem to work.

Any ideas?

Edit: Thanks for all the posts guys, I still can't really figure it out though. Can someone post something really dumbed down? I've been trying to fix this for an hour now and I can't get it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

围归者 2024-12-15 20:41:03

让我们通过示例来了解您的代码存在哪些问题。

例如:行:溢出,堆栈
{ 长度:14 }

逐行获取程序语句 -

int positionOfComma = line.indexOf(",");  // returns 9

lastName = line.substring(0,positionOfComma); // should be actually postionOfComma-1

现在lastName 发生溢出。 positionOfComma 有 9

line = line.substring(positionOfComma+1);

现在linestack

firstName = line.substring(0,positionOfComma); 

询问从 09 的子字符串。但stack的长度仅为5。这将导致字符串索引超出范围异常。希望你明白自己哪里做错了。

Let's work by example, what issues you have with your code.

Eg: line: Overflow,stack
{ length: 14 }

Taking your program statements line by line -

int positionOfComma = line.indexOf(",");  // returns 9

lastName = line.substring(0,positionOfComma); // should be actually postionOfComma-1

Now lastName has Overflow. positionOfComma has 9.

line = line.substring(positionOfComma+1);

Now line has stack.

firstName = line.substring(0,positionOfComma); 

Asking substring from 0 to 9. But stack is only of length 5. This will cause String index out of range exeception. Hope you understood where you are doing wrong.

地狱即天堂 2024-12-15 20:41:03

来自 JavaDoc

(StringIndexOutOfBoundsException) - 由 String 方法抛出
指示索引为负数或大于大小
字符串。

在您的情况下,对 .substring 的调用之一被赋予一个 >= 字符串长度的值。如果第 #34 行是注释,那么它就是 #34 上面的行。

From JavaDoc:

(StringIndexOutOfBoundsException) - Thrown by String methods to
indicate that an index is either negative or greater than the size of
the string.

In your case, one of your calls to .substring is being given a value that is >= the length of the string. If line #34 is a comment, then it's the line above #34.

蓝梦月影 2024-12-15 20:41:03

您需要:

a) 如果您找不到逗号(即,如果您无法找到并提取姓氏和/或名字字符串),请确保处理该情况

b) 确保“positionOfComma + N”的值永远不会超过字符串的长度。

几个“if”块和/或“Continue”语句就可以很好地实现这一目的;-)

You need to:

a) Make sure you handle the case if you DON'T find a comma (i.e. if you cannot find and extract a lastName and/or firstName string)

b) Make sure the value of "positionOfComma + N" never exceeds the length of the string.

A couple of "if" blocks and/or "continue" statements will do the trick nicely ;-)

北城孤痞 2024-12-15 20:41:03

您正确地找到了 positionOfComma,但该逻辑适用于 line 的原始值。当您删除姓氏和逗号时,positionOfComma 不再正确,因为它适用于旧的行值。

You correctly find positionOfComma, but then that logic applies to the original value of line. When you remove the last name and comma, positionOfComma is no longer correct as it applies to the old value of line.

滥情哥ㄟ 2024-12-15 20:41:03
int positionOfComma = line.indexOf(",");

这行代码可能找不到逗号,然后positionOfComma将为-1。接下来,您可以使用 (0,-1) 来对某些内容进行子串 - 难怪它会给出 StringIndexOutOfBoundsException。使用类似的内容:

int positionOfComma = 0;
if(line.indexOf(",")!=-1)
{
   positionOfComma = line.indexOf(",");
}

有时您确实必须进行大量检查,尤其是当数据被破坏时:(

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)

PS我是当然,聪明的人可以让我的编码看起来很破旧,但你明白我希望的意思:)

int positionOfComma = line.indexOf(",");

this line of code might not find a comma and then positionOfComma will be -1. Next you substring something with (0,-1) - eeek no wonder it gives StringIndexOutOfBoundsException. Use something like:

int positionOfComma = 0;
if(line.indexOf(",")!=-1)
{
   positionOfComma = line.indexOf(",");
}

You do have to do lots of checking of things sometimes especially when the data is whacked :(

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String)

PS I'm sure someone clever can make my coding look shabby but you get the point I hope :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文