簡體   English   中英

java-如何將對象(存儲字符)類型轉換為整數

[英]java-how to convert an object (store char)type to integer

java-how to convert an object (store char)type to integer 以下是我在方法 print 中的代碼的一部分,其中有 ❤❤❤❤❤ 符號,我需要 testSample.pop() 的值才能完成我的方法。 但是由於它返回的變量是一個對象類型,我無法對其進行強制轉換,那么我如何將其轉換為整數。 感謝您的幫助。

public class Stack {
public static int capacity = 100;
private Object S[];
private int top = -1;
public Stack(){
    this(capacity);
}
public Stack(int cap){
    capacity = cap;
    S = new String[capacity];
}
public boolean isEmpty(){
    return(top<0);
}
public int size(){
    return(top+1);
}
public void push(Object x){
    if(size() == capacity) throw new StackException("Stack overflow");
    S[++top] = x;
}
public Object pop(){
    Object x;
    if(isEmpty()) throw new StackException("Stack is empty");
    x=S[top];
    S[top--] = null;
    return x;
}
public void print(String sign){
    Stack testSample = new Stack();
    int num1 = 0; int num2 = 0;
    for(int i = 0; i < sign.length(); i++){
        char c = sign.charAt(i);
        if(c == '('){
            testSample.push(c); 
        }
        else if (c == ')'){
            num1 = ❤❤❤❤❤❤
            num2 = c;
            for(int j = num1+1; j < num2; j++){
                char a = sign.charAt(i);
                if(!(c == '('||c == ')'))
                System.out.print(a);
            }
            System.out.println();
        }
}

當它返回一個對象時,將其轉換為 String,然后使用 Integer.parse 將其轉換為 Integer:

Integer.parseInt(testSample.pop().toString());

由於您將 Character 值壓入堆棧,即使它作為 Object 彈出,您也應該能夠簡單地將其強制轉換為 Character,然后獲取與 Character 相關的 int 值。

Integer.valueOf((Character) obj); //obj is the value popped up

暫無
暫無

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

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