我如何在循环中清除/清空数组

时间:2014-03-19 10:33:45

标签: java arrays while-loop

我已经循环了一个数组,所以首先它从输入的数据全名中抓取并将其拆分为lname和fname,然后在该循​​环内部循环它将你输入的分数相加。

当您结束第二个循环时,第一个循环再次请求String.split(在我的情况下为fullname),但是它不允许我输入要拆分的新数据而是给出错误“java.lang.ArrayIndexOutOfBoundsException :1“并突出显示”String fname = parts [1];

任何想法,任何可以帮助我走上正确轨道的事情都将不胜感激!

我也试过

string = "";

string = null;

到目前为止,这是我的代码:

import java.util.Scanner;


public class TestScores
{
   public static void main(String[] args) {
       Scanner kb = new Scanner (System.in);

       String fullname;
       int sum = 0;
       int count = 0;
       int score;


       System.out.println("Please enter name here e.g lastname, firstname");
       fullname = kb.nextLine( );
       while (fullname.equals ("Done") !=true){
       String[] parts = fullname.split(",");
       String lname = parts[0];
       String fname = parts[1];

       System.out.println("Enter scores (Type -1 to finish scoring.");
       score = kb.nextInt();

       while(score != -1)
       {
           sum += score;
           score = kb.nextInt();
           count++;
        }
       System.out.println(fname + " " + lname + "'s total Score is: " + sum);
       System.out.println();



       System.out.println("Please enter another name here e.g lastname, firstname to start scoring"); 
       fullname = kb.nextLine( );

    }

    }
}

3 个答案:

答案 0 :(得分:1)

<强>解决方案:

System.out.println("Please enter another name here e.g lastname, firstname to start scoring"); 
kb.nextLine();  //add this line to fix your problem.
fullname = kb.nextLine( );

<强>解释

您正在执行Scanner.nextInt()并且这不会读取最后一个换行符。行fullname = kb.nextLine( );使用此换行符,然后您只在fullname中添加换行符。然后拆分返回一个大小为1的数组,因此您在此行ArrayIndexOutOfBoundsException中获得String fname = parts[1];。在等待输入之前,您只需要先添加一个nextLine()来使用换行符。

看一下这个答案:Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

答案 1 :(得分:0)

首先测试天气你的分割结果是否存在并尝试初始化fullname变量

String fullname = "";

String[] parts = fullname.split(",");
if(parts.length==2){
       String lname = parts[0];
       String fname = parts[1];
}

答案 2 :(得分:0)

错误的原因是parts不足以拥有parts[1]

parts这么短的原因是fullName.split(",")返回了一个单元素数组。

split()返回单元素数组的原因是fullname不包含逗号。

fullname不包含逗号的原因是文件中的一行不包含逗号。

你要做的是解决这个问题取决于你。您可以指定您的程序在无效输入时可能会失败。您可以检测短数组并跳过该行。您可以检测短数组并插入空/姓氏或名字。这一切都取决于你给予(或已经发明)的要求。