2014-12-02 38 views
3
import javax.swing.JOptionPane; 
public class MyJavaProgramTask4Exercise3 { 

    public static void main(String[] args) { 

     String Namestudent, studentID; 

     Namestudent = JOptionPane.showInputDialog("Type in a student name: "); 
     studentID = JOptionPane.showInputDialog(null, "Type in the correspondng ID number: "); 
     int the_index; 

     System.out.println(Namestudent + " " +studentID); 
     System.out.println(Namestudent.charAt(studentID)); 

    } 

} 

香港專業教育學院被告知要編寫一個程序,允許用戶在鍵入一個學生ID號碼,然後全名,我已經做到了這一點,即時停留在此位,創建一個新的字符串,其中包含ID號中每個數字的索引名稱中的字符...初學Java中使用的charAt並使用用戶輸入來顯示字符

我試圖讓charAt使用學生ID將用戶輸入作爲索引引用顯示Namestudent的字符,但這不是工作,我需要做什麼,而不是感謝

+0

您studentID變量的類型爲字符串,而不是整數的。 – 2014-12-02 16:18:41

+0

假設用戶輸入學號爲一個隨機數,例如3647352,我想創建一個字符串,其中包含他們輸入的名稱中的字符,稱爲「john smith」,並使用ID號作爲「john smith 「 如果你明白的話?說約翰史密斯顯示的輸出將是hsnmh o使用用戶輸入的數字3647352作爲idex .. – paulc01 2014-12-02 16:23:05

+1

@ paulc01你可以很容易地做到這一點,只要確保沒有一個數字會引發indexoutofbounds異常。 – brso05 2014-12-02 16:24:26

回答

3

使用Character.digit(char,int)將ascii字符數字轉換爲一個int數字。我們可以使用String.toCharArray(),並讓我們使用for-each loop。另外,Java命名約定首先是小寫駝峯式。最後,我建議在初始化變量時定義變量。喜歡的東西,

String nameStudent = JOptionPane.showInputDialog(null, 
     "Type in a student name: "); 
String studentId = JOptionPane.showInputDialog(null, 
     "Type in the correspondng ID number: "); 
for (char ch : studentId.toCharArray()) { 
    int pos = nameStudent.length() % Character.digit(ch, 10); 
    System.out.printf("%c @ %d = %c%n", ch, pos, nameStudent.charAt(pos)); 
} 
+0

謝謝,這些是什麼意思對不起(「%c @%d =%c%n」... – paulc01 2014-12-02 16:50:34

+0

['Formatter' syntax](https://docs.oracle.com/javase/ 7/docs/api/java/util/Formatter.html#語法),'%c'是一個字符''%d' *將參數格式化爲十進制整數*和'%n'是換行符 – 2014-12-02 16:57:28

1
public static void main(String[] args) { 

    String Namestudent, studentID; 
    String newString = ""; 

    Namestudent = JOptionPane.showInputDialog("Type in a student name: "); 
    studentID = JOptionPane.showInputDialog(null, "Type in the correspondng ID number: "); 
    int the_index; 
    System.out.println(Namestudent + " " + studentID); 
    for(int i = 0; i < studentID.length(); i++) 
    { 
     newString += Namestudent.charAt(Integer.parseInt("" + studentID.charAt(i))); 
     System.out.println(Namestudent.charAt(Integer.parseInt("" + studentID.charAt(i)))); 
    } 
    System.out.println(newString); 

} 

通過studentID每個數字只是環並轉換爲Integer然後得到charAtNamestudent

+0

非常感謝因爲它真的非常有用,我最好在哪裏可以找到所有這些如何協同工作,或者你可以通過它來說服我?for(int i = 0; i paulc01 2014-12-02 16:48:07

+0

基本上你循環整個'studentID'字符串,並獲得每個索引「12345」字符charAt(i)將返回1然後2然後3等......它將它返回爲一個char,但是你想將該char轉換爲int,所以你可以使用它來獲取charAt Namestudent。所以你把Namestudent.charAt()作爲你剛剛解析過的int,因爲charAt()接受int而不是char。然後你得到該字符並將其添加到你的newString。我希望這是有道理讓我知道,如果你有具體問題... – brso05 2014-12-02 16:55:58

+0

@ paulc01也可以標記這是正確的,如果這是什麼幫助你?謝謝! – brso05 2014-12-02 16:56:52

相關問題