2014-02-08 31 views
0

所以我在我的Java intro類中遇到了這個問題。我是一個完全新手在這個東西,所以任何幫助表示讚賞。我必須設計和創建一個程序,它接受用戶輸入的字母(應該是a-z或A-Z)並確定它在字母表中的位置。 (所以a將等於0)我一直有問題的字符串char和char到int轉換。任何提示或如何設計這個程序的線索將不勝感激。我一整天都在從事這個項目,並沒有取得任何明顯的進展。如何將用戶輸入的字符轉換爲Java中的數字位置?

+0

好吧很酷,但我將如何去獲取用戶輸入的字符?對不起,男士,但我真的很新。 –

回答

0

從輸入字符中減去char常量'a'。 嘗試以下代碼:

char c = 'b'; 
System.out.println(c - 'a' + 1); 

的輸出將是2

+0

字母b的輸出應該是2。 – BitNinja

+0

a - > 0,b - > 2? @codeNinja –

+0

a是字母表中的第一個字母,因此a - > 1,b - > 2. @Weibo Li – BitNinja

0

爲了讓使用者輸入什麼使用掃描儀。在這種情況下,以下代碼將提示用戶輸入一個字符,然後將其分配給名爲'c'的變量。

import java.util.*; 

// assuming that the rest of this code is inside of the main method or wherever 
// you want to put it. 
System.out.print("Enter the letter: "); 

Scanner input = new Scanner(System.in); 

char c = Character.valueOf(input.next()); 

然後使用此代碼使用您喜歡的任何方法轉換爲字母位置。希望有所幫助!

0

我認爲這已經回答了,但把他們放在一起:

/** 
    * Gets the numerical position of the given character. 
    */ 
    private static final int convertToPosition(final char c) { 
     return c - 'A' + 1; 
    } 

    public static void main(String[] args) throws Exception { 
     System.out.print("Enter the letter: "); 
     Scanner input = new Scanner(System.in); 
     if (input.hasNext()) { // if there is an input 
      String inStr = input.next().toUpperCase(); 
      if (inStr.length() != 1) { 
       System.out.println("Unknown letter"); 
       return; 
      } 
      char c = inStr.charAt(0); 
      int pos = convertToPosition(c); 
      System.out.println("Position: " + pos); 
     } else { 
      System.out.println("no input"); 
     } 
    } 
相關問題