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 中没有业务类(class)。该类应该只做一件事,即作为实现具体堆栈的基础。输入和输出应该由类的用户处理,他们可以对输入数据进行正确的解析/转换。

或者,换一种说法,将输入数据转换为与泛型类型匹配需要MyStackGeneric 不可用的信息(具体参数类型)。类因为类型删除。你可以把 readInput() 的具体版本在你的具体类(class)中。对于 MyStackInteger那些行会变成
        if (s2.matches("[+-]?\\d+")) {
            push(Integer.valueOf(s2));

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

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

相关文章:

java - 您知道免费或开源的网站拼写检查器吗?

java - 如何避免用户将重复的int值添加到数组?

c++ - 使用 vector 用C++解决Eratosthenes筛子并收到异常错误消息

json - 无法将类型 'AnyObject?' 的值转换为预期的参数类型 '[AnyObject]!

java - 使用 TextAction 实现带有 actionPerformed 的 JMenu

java - 读取文本文件中的字符串

c++ - 从文件中将对象读入数组,反之亦然

Javascript:如何检查每个输入值是否重复到另一个输入值

scala - Scala-没有TypeTag可用当使用案例类尝试获取TypeTag时发生异常吗?

python - numpy矩阵和numpy.matrixlib.defmatrix.matrix有什么区别?