2015-12-12 93 views
0

我有一個任務要做。我需要將字母轉換爲電話號碼。在第3個數字後面以及後面的4個數字後添加連字符。然後我需要讓用戶繼續輸入。 我已經完成了3/4的代碼。它不工作。我只是停留在提示用戶輸入的部分。 這是我迄今爲止的Java代碼。請幫助我,告訴我我的代碼有什麼問題。我是Java新手,請保持良好態度。謝謝!保持提示輸入來自用戶

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

    System.out.println("Enter letters: "); 
    String phonenumber = input.next(); 
    String phone = phonenumber.replaceAll("\\s", " "); 

    int count = 0; 
    int prevCount = 0; 

    while (!phone.equals("#")){ 
    for (int i = 0; i < phone.length(); i++) 
     { 
      char letter = Character.toLowerCase(phone.charAt(i)); 
      if (letter == 'a' || letter == 'b' || letter == 'c') 
      {  
       System.out.print(2); 
       count++; 
      } 

      if (letter == 'd' || letter == 'e' || letter == 'f') 
      { 
       System.out.print(3); 
       count++; 
      } 

      if (letter == 'g' || letter == 'h' || letter == 'i') 
      { 
       System.out.print(4); 
       count++; 
      } 

      if (letter == 'j' || letter == 'k' || letter == 'l') 
      { 
       System.out.print(5); 
       count++; 
      } 

      if (letter == 'm' || letter == 'n' || letter == 'o') 
      { 
       System.out.print(6); 
       count++; 
      } 

      if (letter == 'p' || letter == 'q' || letter == 'r' || letter == 's') 
      { 
       System.out.print(7); 
       count++; 
      } 

      if (letter == 't' || letter == 'u' || letter == 'v') 
      { 
       System.out.print(8); 
       count++; 
      } 

      if (letter == 'w' || letter == 'x' || letter == 'y' || letter == 'z') 
      { 
       System.out.print(9); 
       count++; 
      } 

      if (count == 3 || count - prevCount == 4) 
      { 
       System.out.print('-'); 
       prevCount = count; 
      } 
     } 
     System.out.println(); 
     System.out.println("Enter letters: "); 
     input.nextLine(); 
    } 
} 

回答

0

使用一個循環:

while (true) 
{ 
System.out.println("Enter letters: "); 
String phonenumber = input.next(); 

if something break; 

while ((String phonenumber = input.next())!=null) 
{ 
// ... 
    System.out.println("Enter letters: "); 
} 
+0

謝謝。我終於解決了! –

0

你的問題是在這裏:

System.out.println(); 
    System.out.println("Enter letters: "); 
    input.nextLine(); // you forgot to assign the String returned by nextLine 
         // into your phone variable 

除此之外,你應該在每次迭代重置計數器while循環。

while (!phone.equals("#")) { 
    int count = 0; 
    int prevCount = 0; 
    ... your for loop ... 
    System.out.println(); 
    System.out.println("Enter letters: "); 
    phone = input.nextLine(); 
} 
+0

謝謝!我終於明白了。 –