2016-04-11 10 views
0

クラス用語の2つのコンポーネントを一緒に結合する方法、および文字列内の(integer.parseIntを使用して)コンポーネントを識別して変換する方法を教えてください。 2つの成分は「元素」および「原子」である。文字列の2つのコンポーネントを結合してコンポーネントを識別する

例をH20からHと20に分け、Hを要素、20を原子の数として識別する必要があります。 "TODO"パートは私のコードが必要な場所で、最初の "TODO"は2つのコンポーネントを結合する必要があり、2番目の "TODO"は文字列のコンポーネントを識別して翻訳する必要があります。

私はこれをBlueJでコーディングしています。私はコーディングの初心者であり、charとintの解析と連結に慣れていません。このコンピュータサイエンスプロジェクトに使用される化学式はすべてCH3CH2CH2CH2CH2CH3です。これらは最初の質問です。

TODOセクションでコードを開始する方法がわからないため、まだ実装がありません。

public class Term 
{ 
private char element; 
private int atoms; 
// creates a Term with the provided values 
public Term(char element, int atoms) 
{ 
this.element = element;   
this.atoms = atoms; 
} 
// creates a Term by parsing s  
// e.g. "H20" would give element = 'H', atoms = 20 

public Term(String s) 
{ 
// TODO 
}   
// turns the Term into a String  
// e.g. element = 'C', atoms = 4 would give "C4" 
public String display() 
{   
// TODO   
return ""; 
}   
// returns the current value of element 
    public char getElement() 
{ 
return element; 
} 
// returns the current value of atoms 
public int getAtoms() 
{   return atoms; 
} 
} 
+0

'String.valueOf(INT)'? –

+0

あなたは何をしたいのかはっきりしていませんが、数式はN回または大きなものになります。これまでのあなたの示唆も示してください。あなたが投稿したコードは、先生が教えてくれたスニペットです。 – dambros

+0

あなたはそれを拡張していただけますか? – thatguy123

答えて

0

public class Term { private char element;

private int atoms; 

// creates a Term with the provided values 
public Term(char element, int atoms) { 
    this.element = element; 
    this.atoms = atoms; 
} 

// creates a Term by parsing s  
// e.g. "H20" would give element = 'H', atoms = 20 

public Term(String s) { 
    // TODO 
    String e=""; 
    String at="";   
    char ch[]=s.toCharArray(); 

    for(int i=0;i<s.length();i++){ 

     if(ch[i]>=(char)65 && ch[i]<=(char)90 || ch[i]>=(char)97 && ch[i]<=(char)122){ 
      e=e+ch[i]; 
     } 
     else{ 
      at=at+ch[i]; 
     } 
    } 
    System.out.println("element = '"+e+"'\t atom = "+at); 
} 

// turns the Term into a String  
// e.g. element = 'C', atoms = 4 would give "C4" 
public String display() { 
    // TODO 
    String trm=""+getElement()+getAtoms(); 
    return trm; 
} 

// returns the current value of element 
public char getElement() { 
    return element; 
} 

// returns the current value of atoms 
public int getAtoms() { 
    return atoms; 
} 

}

+0

答えにあなたの解答を説明してください! – gaRos

+0

あなたのご意見ありがとうございます。しかし、あなたの説明にお答えください。 "for(int i = 0; i =(char)65 && ch [i (char)97 && ch [i] <=(char)122){ e = e + ch [i]; " – thatguy123

+0

アルファベットかどうかを判断するためのものです。 a-z [97〜122]およびA-ZのASCIIコードは[65〜90]です。 – Dev

関連する問題