gpt4 book ai didi

java - Java 中的文件 I/O

转载 作者:行者123 更新时间:2023-12-01 18:35:34 25 4
gpt4 key购买 nike

我自己的 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();
}
}

最佳答案

你的语法错误。也许你的意思是这样的:

Vector stack = new Vector(10);

另外,您确定要将 Vector 类放在 Stack 类中吗?另外,将类命名为与现有 Java 类相同的名称通常是个坏主意。

关于java - Java 中的文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22175998/

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