2014-03-19 54 views
-2

我已經循環了一個數組,所以首先它從輸入的數據全名抓取並將它拆分爲lname和fname,然後用循環內部的循環將所輸入的分數相加。我該如何清除/清空一個循環中的數組

當你結束第二個循環時,第一個循環再次要求String.split(在我的例子中是fullname),但它不允許我輸入新的數據來分割,而是給出錯誤「java.lang。 ArrayIndexOutOfBoundsException異常:1" ,並強調「字符串FNAME =零件[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(); 

    } 

    } 
} 
+0

刪除C++標籤,因爲它與C++無關 – billz

+4

'我只是在爲C++做...'這是java而不是C++! – myusuf

+0

String []部分在while循環中,當循環結束時String []部分被破壞不是嗎? –

回答

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的數組,因此您在此行中獲得ArrayIndexOutOfBoundsExceptionString fname = parts[1];。在等待輸入之前,您只需添加一個nextLine()即可首先使用換行符。

這個答案請看下圖:Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

+0

我想感謝所有回覆了這一切的人,並添加了kb.nextLine();像魅力一樣工作! – SamsinOzo

+0

您可以接受任何答案以顯示問題已解決。 – kai

+0

完成!再次感謝,在使用nextInt()後添加「跳過nextLine()」後,它更清除了我的理解:3 – SamsinOzo

0

首先測試的天氣將拆分結果在那裏,嘗試初始化全名變量

String fullname = "";

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

的原因錯誤是parts不夠長有parts[1]

parts這麼短的原因是fullName.split(",")返回一個元素的數組。

原因split()返回一個元素的數組是fullname不包含逗號。

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

你做什麼來解決這個問題是由你決定的。您可以指定您的程序在無效輸入時可能會失敗。您可以檢測短陣列並跳過該行。您可以檢測短陣列並插入空白/空姓或名。這一切都取決於你的要求(或已發明)。