簡體   English   中英

我如何從字符串中提取整數,然后在Java中將它們加在一起而沒有split方法/數組?

[英]How would I extract integers from a string and add them together in Java without the split method/arrays?

假設我得到的字符串是(1 5 23 100 90)。

我將如何提取它們,將它們轉換為整數,然后將它們加在一起?

我相信Integer.parseInt(String)會將它們轉換為整數,但是我遇到的麻煩是提取它們。

這是我的偽代碼:

1)存儲整數。

2)有空間時停下來。

3)重復步驟1-2(這樣可能會循環嗎?)

4)然后將它們轉換為整數,因為它們仍被視為字符串。

5)將它們全部加在一起。

使用java Scanner類。 它可以幫助您使用定界符(在您的情況下為空格以及“(”和“)”字符)。

Scanner s = new Scanner(input).useDelimiter(WHATEVER_DELIMITERS_YOU_NEED);
sum = 0;
while(true) {
    sum += s.nextInt();
    if(!s.haNext())
        break;
}

這應該可以解決問題...假設您被允許使用模式

public int printSum(String str) {
    Scanner scan = new Scanner(str);
    int sum = 0;

    // tell the scanner to use "(", " ", or ")" as a delimeter 
    scan.useDelimiter("(\\(|\\s|\\))");

    while ( scan.hasNext() ) {
        try {
            sum += scan.nextInt();
        }
        catch (Exception ex) {
            // if input is unable to be parsed.
            ex.printStackTrace();
        }
    }

    return sum;
}

有一個Scanner的構造函數,該構造函數將String作為參數,並允許您使用Scanner讀取String

您可能希望先讀取開頭的(字符。)之后,可以重復調用hasNextIntnextInt ,直到hasNextInt返回false為止。在運行時添加nextInt返回的int值。

暫無
暫無

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

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