gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:22:56 25 4
gpt4 key购买 nike

我正在编写一个程序,它继承了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com