gpt4 book ai didi

Java,在其他地方使用数组中的字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 14:26:10 27 4
gpt4 key购买 nike

我是编码新手。我正在做一个项目,但我被困住了。我的代码从文本文件中读取句子。它分隔句子并获取第二个单词并将其记录在数组中。我需要在其他地方使用这个词,但我做不到。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Classroom {
private String classname;

public String getClassname() {
return classname;
}

public void setClassname(String classname) {
this.classname = classname;
}

public void classroomreader(String filename) {
// This method gets the name for Classroom
File text = new File("C:/classlists/" + filename + ".txt");
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
String classroomarray[] = line.split("\t");
// ** right now classroomarray[1] has the word which I want.**

} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}

这是我的主要类(class):

public class ProjectMain {
public static void main(String[] args) {
// I created an array with 3 Classroom object inside it.
Classroom[] classarray = new Classroom[3];

//I hope I did this correct.

// I used classroomreader method on my first object.
classarray[0].classroomreader("class1");

// Now I need to use the word in classroomarray[1].
classarray[0].setClassname(????)
}
}

我尝试过:classarray[0].setClassname(classroomarray[1]);但它给出了一个错误。如何为我的第一个对象设置名称?

最佳答案

我只对你的代码做了一些更改..试试这个....这肯定会起作用

    class Classroom {
private String classname;
String classroomarray[]=null;//declare classroomarray[] here

public String getClassname() {
return classname;
}

public void setClassname(String classname) {
this.classname = classname;
}

public void classroomreader(String filename) {

File text = new File("C:/classlists/" + filename + ".txt");
Scanner scan;
try {
scan = new Scanner(text);
String line = scan.nextLine();
classroomarray = line.split("\t");


} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}

}

类项目主{ 公共(public)静态无效主(字符串[]参数){

        Classroom[] classarray = new Classroom[3];


//here you need to initialize all elements of the array
classarray[0]=new Classroom();
classarray[1]=new Classroom();
classarray[2]=new Classroom();

classarray[0].classroomreader("class1");


classarray[0].setClassname(classarray[0].classroomarray[1]);

System.out.println(classarray[0].getClassname());// here you'll surely get the the desired results
}
}

关于Java,在其他地方使用数组中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26638989/

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