2016-05-15 2 views
0

При поиске решения этого вопроса я нашел предложение использовать sc.next() вместо sc.nextLine(), но я не могу использовать его, поэтому мне нужна дополнительная помощь.Индекс строки за пределами допустимого диапазона: 0

Я развиваю сетевую многопользовательскую текстовую игру и должен фильтровать имя игрока, но я продолжаю получать ошибку «Индекс строки за пределами диапазона: 0» Я пробовал несколько часов, чтобы исправить это и не смог найти решение , Функция вызывает ошибку заключается в следующем:

public static Player charCreate(Player player) { 

    int points = 60; 
    int i = 0; 
    boolean cont = true; 
    int str = 0; 
    int dex = 0; 
    int end = 0; 
    int INT = 0; 
    int lck = 0; 
    int cha = 0; 

    Output.slowDiscription("You stand there and think about all" 
      + " that has transpired, who are you realy?"); 

    System.out.print("What is your Name? "); 

    boolean bool = false; 
    String temp; 
    String name = null; //name is forced to be declared by while loop 

    do { 

     name = sc.nextLine(); 
     System.out.println(name); 
     if (Utills.profan(name) && (name != null) 
       && ((!name.equals("")) || (!name.equals(" ")))) { 

      bool = true; 
      player.setName(Utills.filter(name)); //Error is here 

     } 
     else { 

      bool = false; 

     } 

    } while (bool == false); 

    player.Height = getUsrHeight(); 

    System.out.print("Please select your stats. "); 

    do { 

     System.out.println("Points Remaining: " + points); 

     switch (i) { 

     case 0: 

      System.out.println(); 
      System.out.println("Please Enter the number of points to alot to " 
        + "Strength.\n Min:1 Max:18"); 

      str = sc.nextInt(); 
      if ((str >= 1) && (str <= 18) && (str <= points) && 
        ((points - str) >= 5)) { 

       points -= str; 
       i++; 

      } 
      break; 

     case 1: 

      System.out.println(); 
      System.out.println("Please Enter the number of points to alot to " 
        + "Dexterity.\n Min:1 Max:18"); 

      dex = sc.nextInt(); 
      if ((dex >= 1) && (dex <= 18) && (dex <= points) && 
        ((points - dex) >= 4)) { 

       points -= dex; 
       i++; 

      } 
      break; 

     case 2: 

      System.out.println(); 
      System.out.println("Please Enter the number of points to alot to " 
        + "Endurance.\n Min:1 Max:18"); 

      end = sc.nextInt(); 
      if ((end >= 1) && (end <= 18) && (end <= points) && 
        ((points - end) >= 3)) { 

       points -= end; 
       i++; 

      } 
      break; 

     case 3: 

      System.out.println(); 
      System.out.println("Please Enter the number of points to alot to " 
        + "Inteligence.\n Min:1 Max:18"); 

      INT = sc.nextInt(); 
      if ((INT >= 1) && (INT <= 18) && (INT <= points) && 
        ((points - INT) >= 2)) { 

       points -= INT; 
       i++; 

      } 
      break; 

     case 4: 

      System.out.println(); 
      System.out.println("Please Enter the number of points to alot to " 
        + "Luck.\n Min:1 Max:18"); 

      lck = sc.nextInt(); 
      if ((lck >= 1) && (lck <= 18) && (lck <= points) && 
        ((points - lck) >= 1)) { 

       points -= lck; 
       i++; 

      } 
      break; 

     case 5: 

      System.out.println(); 
      System.out.println("Please Enter the number of points to alot to " 
        + "Charisma.\n Min:1 Max:18"); 

      cha = sc.nextInt(); 
      if ((cha >= 1) && (cha <= 18) && (cha <= points)) { 

       points -= cha; 
       i++; 

      } 
      break; 

     case 6: 

      int[] stats = {str, dex, end, INT, lck, cha}; 

      player.setStats(stats); 
      cont = false; 
      break; 

     } 

    }while (cont); 


    return player; 

} 

Ошибка здесь происходит от (имя) Utills.filter:

public static String filter(String name) { 

    //Variables 
    String[] Name = name.toLowerCase().split(" "); 

    StringBuilder sb = new StringBuilder(); 
    StringBuilder endStr = new StringBuilder(); 

    char temp; 

    int i = 0; 

    //Sorting 
    for(String w: Name) { 

     sb.append(w); 

     temp = Character.toUpperCase(sb.charAt(0)); //And Error is here 
     sb.setCharAt(0, temp); 

     if(i >= 1) { 

      endStr.append(" " + sb.toString()); 

     } 
     else { 

      endStr.append(sb); 

     } 

     i++; 
     empty(sb); 

    } 


    return endStr.toString(); 

} 

Я бы greatfull за любую помощь

+0

Сообщение об ошибке должно сообщить вам, в какой строке включена ошибка. Пожалуйста, сообщите нам, что это (и _show_ нас, какая строка это, не просто сообщите нам номер строки, потому что мы не сможем выяснить, какая строка. Лучше всего отредактировать ваш вопрос и добавить комментарий к вашему коду, указывающий, к какой строке относится сообщение об ошибке). – ajb

+0

Какова ценность 'name'? Если ошибка в 'filter()', то другой код не имеет никакого значения для вашего вопроса и является просто шумом. Соответствующей частью является значение, вызывающее ошибку и строку, в которой происходит ошибка. – Andreas

+1

Не зная, в какую строку включена ошибка, трудно сказать. Но я предполагаю, что 'w' может быть пустой строкой. – ajb

ответ

1

Я думаю, что ваш проблема заключается в следующем:

if (Utills.profan(name) && (name != null) 
      && ((!name.equals("")) || (!name.equals(" ")))) 

Возможно, это должно быть

if (Utills.profan(name) && (name != null) 
      && !name.equals("") && !name.equals(" ")) 

или даже

if (Utills.profan(name) && (name != null) 
      && !name.trim().isEmpty()) 

Если вы до сих пор не понимаю, что проблема, которую я имею в виду, проверка ((!name.equals("")) || (!name.equals(" "))) всегда будет true, потому что name всегда либо не "" или не " ".

Смежные вопросы