java - 类型转换并获取数组以查看通用结果

标签 java arrays types casting

我正在编写一个程序,它继承了 MyStackGeneric 的一些特征,称为 MyStackInteger。我几乎完成了作业,但遇到了一个问题。一旦我在方法binaryOperator中得到两个变量,它就会尝试对字符串进行加法、减法或乘法运算,但会返回错误。我尝试过类型转换和移动东西,但我无法让它工作。我工作的限制之一是当前 MyStackGeneric 中的所有方法都必须保留在那里。我不能将它们放在 MyStackInteger 中,因为我们将来将使用它来处理复数。

class `MyStackInteger`:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Iterator;

public class MyStackInteger extends MyStackGeneric<java.lang.Integer>{

//Creates a new ArrayList and runs readInput as long as there is input
public static void main(String[] args){
  MyStackInteger my = new MyStackInteger(){};
  my.readInput(new Scanner(System.in));
}

//Subtracts two variables
@Override
protected java.lang.Integer minus(java.lang.Integer o1, java.lang.Integer o2){
    o2 = o2-o1;
    return o2;
}

//Multiplies two variables
@Override
protected java.lang.Integer multiply(java.lang.Integer o1, java.lang.Integer o2){
    o2 = o2*o1;
    return o2;
}

//Creates a new element in the Array
@Override
protected java.lang.Integer newElement(java.lang.String w){
    return new Integer(w);
}

//Adds two variables
@Override
protected java.lang.Integer plus(java.lang.Integer o1, java.lang.Integer o2){
    o2 = o2+o1;
    return o2;
}

//Adds a zero to the array
@Override
protected java.lang.Integer zero(){
    Integer blank = 0;
    return blank;
}
}

class MyStackGeneric<E>:

abstract class MyStackGeneric<E> extends ArrayList<E>{

//Generics being implemented by MyStackInteger
protected abstract E multiply(E o1, E o2);

protected abstract E minus(E o1, E o2);

protected abstract E plus(E o1, E o2);

protected abstract E zero();

protected abstract E newElement(java.lang.String w);

//Grabs the top element of the ArrayList
public E peek(){
   return this.get(getSize()-1);
}  

//Removes the top element of the ArrayList
public E pop(){
    E o = this.get(getSize()-1);
    this.remove(getSize()-1);
    return o;
} 

//Pushes an element onto the ArrayList
public void push(E o) {
    this.add(o);
}

//Makes the ListArray A string
@Override
public String toString() {
    return "stack: " + this.toString();
}   

//Iterates while there is input
public void readInput(Scanner s) {
    while (s.hasNext()) {
        String s2 = s.next();
            //Pushes any numerical input to the stack
            if (s2.matches("[+-]?\\d+")) {
                push((E) s2);
            //Goes to binaryOperator if +, - or * is implemented
            } else if (("+".equals(s2)) || 
                      ("-".equals(s2)) || 
                      ("*".equals(s2))) {
                binaryOperator(s2);
            //Prints the stack
            } else if (s2.matches("p")) {
                print();
            //Runs an error if the input is too long
            } else if (s2.length() > 1) {
                System.out.println("Exception: too long: " + s2);
            //Runs an error if there is one unknown char
            } else if (s2.length() == 1) {
                System.out.println("Exception: Unknown Command " + s2);
            }

    }
}

//Prints the stack
public void print(){
   System.out.println("Print Stack: ");
   Iterator<E> s = this.iterator();

   while(s.hasNext()){
       System.out.print(s.next() + (s.hasNext() ? ", " : "\n" ));
   System.out.println("");
   }
}

//Checks if the ArrayList is empty
public boolean empty(){
    return this.isEmpty();
}

//Gets the total size of the ArrayList
public int getSize(){
    return this.size();
}

//Tries to grab the top two elements of the ArrayList, then execute a 
//arithmetic operation on them.
public void binaryOperator(java.lang.String op){
    E var1; 
    E var2;
    boolean exist = true;
    try {
        var1 = peek();
        }catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Exception: Need two operands");
        var1 = null;
        exist = false;
    }
    if (exist)
       pop();
    try {
        var2 = peek();
        }catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Exception: Need two operands");
        var2 = null;
        exist = false;
    }
    if (exist)
        pop();
    //This is where the program breaks. At this point, both var1
    //and var2 are Strings so when it tries to run plus or minus
    //or multiply, it returns the error of not being able to turn
    //a string into an int.
    if ("+".equals(op)){
       push(plus(var1, var2));
    }
    if ("-".equals(op)){
       push(minus(var1, var2));
    }
    if ("*".equals(op)){
       push(multiply(var1, var2));
    }  
}
}

最佳答案

        if (s2.matches("[+-]?\\d+")) {
            push((E) s2);

你不能这样做。您不能获取 String 并对其执行任意转换。如果您注意编译器,您会看到警告消息

Type safety: Unchecked cast from String to E

主要问题在于您的设计。 readInput 方法与 MyStackGeneric 类无关。该类应该只做一件事,即作为实现具体堆栈的基础。输入和输出应该由类的用户处理,他们可以对输入数据进行正确的解析/转换。

或者,换句话说,转换输入数据以匹配泛型类型需要的信息(具体参数类型)由于类型删除而无法供 MyStackGeneric 类使用。您可以将具体版本的readInput()放入您的具体类中。对于 MyStackInteger 这些行将变为

        if (s2.matches("[+-]?\\d+")) {
            push(Integer.valueOf(s2));

但这仍然违反了单一职责原则。

关于java - 类型转换并获取数组以查看通用结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39383272/

相关文章:

java - 如何创建依赖类的单例实例?

java - Blowfish 示例,其中自动填充和取消填充键以调整大小

python - 使用 NumPy argsort 并接收二维数组

Javascript:for循环返回 bool 数组而不是值数组

c - 使用链表与大数组进行搜索

java - 如何检查 java.lang.reflect.Type 是否为枚举

javascript - 服务器发送事件,spring mvc 始终关闭

c++ - 新表达式会返回一个指向数组的指针吗?

c - 我们可以找到另一个小于float的数据类型吗?

java - 在类里面取消设置 session android