3

我想我把它分解成最基本的形式。如果没有,那么我很抱歉,并会尝试对其进行编辑。如果我已经将变量设置为字符串,为什么在我的 while 循环中需要为 FirstName 转换字符串?难道我做错了什么?我尝试将 FirstName 变量设置为等于第一个标记,该标记应该是文本文件的第一个单词等。

  try
            {
                BufferedReader infileCust =
                        new BufferedReader(new FileReader("C:\\custDat.txt"));
    }
      catch(FileNotFoundException fnfe)
            {
                System.out.println(fnfe.toString());
            }
            catch(IOException ioe)
            {
                System.out.println(ioe.toString());
            }
        }

        public static void createCustomerList(BufferedReader infileCust,
                CustomerList custList) throws IOException
    {    
        String  FirstName;
        String  LastName;
        int  CustId;


        //take first line of strings before breaking them up to first last and cust ID
        String StringToBreak = infileCust.readLine();
        //split up the string with string tokenizer
        StringTokenizer st = new StringTokenizer(StringToBreak);

        while(st.hasMoreElements()){
        FirstName = (String) st.nextElement();
        LastName = (String) st.nextElement();
        CustId = Integer.parseInt((String) st.nextElement());

        }

编辑:显然我可以使用 nextToken() 代替。但是为什么我的变量显示为未使用?它们不在while循环的范围内吗?

4

3 回答 3

6

这是因为nextElement返回 Object。如果您调用nextToken,则不需要强制转换。

从文档中:

公共对象 nextElement()

返回与 nextToken 方法相同的值,只是它声明的返回值是 Object 而不是 String。它的存在是为了让这个类可以实现 Enumeration 接口。

编辑关于未使用的变量:您收到警告的原因是变量已分配,但未以某种方式打印、保存或分析。如果你添加一个电话,比如说,writeln名字和姓氏,警告就会消失。

于 2012-02-13T00:06:11.493 回答
3

因为StringTokenizer.nextElement返回一个java.lang.Object. 请参阅此处的文档:http: //docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.htmlnextToken() : String如果您愿意,可以使用。

于 2012-02-13T00:06:32.817 回答
2

因为StringTokenizer.nextElement()返回

与nextToken方法的值相同,只是它声明的返回值是Object而不是String。它的存在是为了这个类可以实现Enumeration接口。

于 2012-02-13T00:06:41.683 回答