2016-12-06 109 views
-2
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace switchStatementExercise 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      String response; 

      Console.WriteLine("Please Vote for your president out of the 7 following, Joseph Mason, James Long, Ben Harding, Georgia Mason, Keith Webb, Mark Grimley, Max Gridley"); 
      response = Console.ReadLine(); 

      string fullNameJoe = response; 
      var names = fullNameJoe.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); 
      string firstName = names[0]; 
      string lastName = names[1]; 
      Console.WriteLine(lastName); 
      if (response.Equals(fullNameJoe) || response.Equals(firstName) || response.Equals(lastName)) 
      { 
       Console.WriteLine("You have voted for " + fullNameJoe); 
       Console.WriteLine(fullNameJoe); 

      } 
      else if (fullNameJoe.Length > 1 && lastName == null) 
      { 

       Console.WriteLine("You need a last name"); 
      } 
      else 
      { 
       Console.WriteLine("Please enter a first name and last name"); 
      } 

     } 
    } 
} 

所以我想要做的是檢查是否姓氏是空的這是所有用戶輸入姓氏,但我得到這個錯誤。檢查分割方法是否爲空

未處理的異常:System.IndexOutOfRangeException:索引超出了數組的範圍。 在switchStatementExercise.Program.Main(字串[] args)在C:\用戶\喬\桌面\ cSharpWeek1 \ switchStatementExercise \ switchStatementExercise \的Program.cs:行21

任何幫助或重定向到的答案是大!

+0

爲什麼'fullNameJoe.Split(新[] { ''}'和'不fullNameJoe.Split(新[] {」「}'誰寫的'最大; Gridley' –

+0

我試過這個,但仍然不起作用): –

+0

它只能根據你輸入的內容來工作,你可以用任何字符來分割'fullNameJoe.Split(「,; - /」。ToCharArray )' –

回答

0

指數數組的邊界

手段,不管你在那裏輸入外,你Split後沒有得到names[1](最有可能)。所以,如果你輸入「alex;」 - 把...忘了吧。

您可以檢查

if (names.Length < 2) 
{ 
    Console.WriteLine("You need first and last name"); 
    return; 
} 

在另一方面,爲什麼 「;」?它會期望輸入「alex; morgan」。我們通常輸入「alex morgan」並按「」分割。您可以通過任何字符的

fullNameJoe.Split(" ,;-/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); 

使用分在第二部分

if (response.Equals(fullNameJoe) || response.Equals(firstName) || response.Equals(lastName 

這並沒有太大的意義。第一個條件永遠是真的。第二和第三個條件將是真或假。你可能需要做的是創建一個列表

var presidents = "Joseph Mason, James Long, Ben Harding, Georgia Mason, Keith Webb, Mark Grimley, Max Gridley". 
    Split(",".ToCharArray()).Select(p => p.Trim()).ToArray() 

,然後再檢查條件的頭號(可選)[if (names.Length < 2)]。或者,你可以直接去名檢查

if (names.Contains(response.Trim(), StringComparer.OrdinalIgnoreCase)) 
{ 
    Console.WriteLine("yes"); 
} 
+0

仍然給我同樣的錯誤): –

+0

我已經改變了我的代碼回到「」 –

+0

@ J.mason之間的空白空間我不同意,我只是擺弄它'var fullNameJoe =「alex morgan」; var names = fullNameJoe.Split(new [] {'',StringSplitOptions.RemoveEmptyEntries) ; Console.WriteLine(names [0]); \t Console.WriteLine(names [1]);'**就像一個魅力** –