我的Vector类的代码有问题。
固定即可。添加了对文件的读写,但这个try / catch对我来说看起来太麻烦了。也许有更好的文件I / O方式?
FIXED-2 哦,我刚发现“抛出”,现在我的代码看起来非常好。谢谢大家的帮助!这是Stack.java的最终版本:
import java.util.Scanner;
import java.io.*;
class Vector {
private int[] vec;
private int length, pointer;
public Vector(int n) {
pointer = 0;
length = n;
vec = new int[length];
}
public int get(int i) {
return vec[i];
}
public void set(int i, int n) {
vec[i] = n;
}
public void push(int n) {
if (pointer == length) {
int[] nvec = new int[length*2];
for (int i = 0; i < length; i++)
nvec[i] = vec[i];
length *= 2;
vec = null;
vec = nvec;
}
vec[pointer++] = n;
}
public void delete() {
pointer--;
if (pointer == length / 4) {
int[] nvec = new int[length/2];
for (int i = 0; i <= pointer; i++)
nvec[i] = vec[i];
length /= 2;
vec = null;
vec = nvec;
}
}
public int size() {
return pointer;
}
public int actualSize() {
return length;
}
}
public class Stack {
public static void main(String[] args) throws IOException {
File ifile = new File("stack1.in");
BufferedReader reader = new BufferedReader(new FileReader(ifile));
File ofile = new File("stack1.out");
BufferedWriter writer = new BufferedWriter(new FileWriter(ofile));
int n = Integer.parseInt(reader.readLine());
Vector stack = new Vector(10);
for (int i = 0; i < n; i++) {
String s = reader.readLine();
if (s.charAt(0) == '-') {
writer.write(Integer.toString(stack.get(stack.size()-1)));
writer.write("\n");
stack.delete();
} else {
s = s.substring(2);
stack.push(Integer.parseInt(s));
}
}
writer.close();
reader.close();
}
}
答案 0 :(得分:4)
你的语法错了。也许你的意思是这样的:
Vector stack = new Vector(10);
另外,您确定要在Stack类中使用Vector类吗?另外,将类命名为与现有Java类相同的内容通常是个坏主意。
答案 1 :(得分:0)
初始化Vector类,如下所示
Vector stack = new Vector(10);
答案 2 :(得分:0)
Vector stack = new Vector(10);