簡體   English   中英

for循環(記住最后看的位置)和Character.isDigit()

[英]for loop (remember where last to look) & Character.isDigit()

我必須做一個關於元素周期表的項目。 我的困境如下。 用戶向您發送一個分子方程式。 它可以是任何長度。 在此數組中,有大寫字母,小寫字母和數字。

我也有一系列對象。 每個對象代表元素周期表上的一個元素。 現在,我需要打破此字符串,用戶將其細分為一些較小的部分,這些部分可以被對象數組識別。 我還必須將答案乘以一個或乘以元素最后一個字母旁邊的數字。

我已經嘗試了以下方法。 將字符串設為char數組。 從后向遍歷數組-測試數字( Character.isDigit(a[i]); ),測試大寫和小寫...我總是Character.isDigit(a[i]);相同的問題。 我不知道字符串會持續多久。 可以說我找到一個數字。 然后,如果前一個字符是小寫字母,我需要向后檢查另一個大寫字母。 然后說我有分子方程式和乘以它的數量-如何讓計算機知道從最后一個大寫字母開始查找。

希望有人能理解!

確實需要一些幫助。

另一個問題:為什么這段代碼行不通:

String moleq = "HeKiLH2B6";

char[] a = moleq.toCharArray();
int g = moleq.length()-1;
int x = 1; //if not more than one of element - multiply getWeight by 1

int[][] indexofdigit = new int[moleq.length()][2];
int[] indexoflower = new int[moleq.length()];

for (int i = g; i <= 0; i--){

    if (Character.isDigit(a[i])) {
    String z = Character.toString(a[i]);
    x = Integer.parseInt(z);
    System.out.println("YES");

    }
}

此代碼永遠不會打印出我的意思?

尋找i <= 0條件時,循環永遠不會執行。 起初是不正確的,因為g> 0,如果將其更改為i> = 0,它將起作用

對於化學式,正則表達式(regexp)可能會很有趣。 像([AZ] [az]?[0-9] )+之類的東西。 如果我沒記錯( ),則會隔離一個元素及其基數(例如Fe2O3->第1組(Fe2)+第2組(O3))。 查看模式和匹配器。

  • 如果我錯了,我敢肯定Google某處有一個正則表達式。 它通常不依賴於語言(如果它適用於Perl,則適用於Java)。

請注意,在Java 5+中,可以使用for每個循環來簡化該循環:

for (char c : a){
  if (Character.isDigit(c)) {
    String z = Character.toString(c);
    x = Integer.parseInt(z);
    System.out.println("YES");
  }
}

擴展SJuan的建議:

String input = "HeKiLH2B6";
Pattern p = Pattern.compile("([A-Z][a-z]*)(\\d*)");    
Matcher m = p.matcher( input );

while(m.find()){
  String element = m.group( 1 );
  String cardinalityStr = m.group( 2 );
  int cardinality= 1;
  if( cardinalityStr != null && cardinalityStr .length() > 0)
  {
    cardinality= Integer.parseInt( cardinalityStr );
  }

  System.out.println( element + cardinality);
}

產量:

He1
Ki1
L1
H2
B6

編輯:如果用戶輸入了He-Ki-L-H2-B6He Ki L H2 B6類的內容,這也將起作用。

代碼中SJuan76的答案(添加了勉強的組限定符):

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {
        // the compiled pattern can be re-used, are thread-safe 
        // and thus can be static final
        Pattern p = Pattern.compile("([A-Z][a-z]?[0-9]*)+?");

        // Per molecule (well, string) a matcher must be obtained.
        Matcher m = p.matcher("HeKiLH2B6");
        while(m.find()) {
            System.out.println(m.group());
        }
    }
}

打印:

He
Ki
L
H2
B6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM