gpt4 book ai didi

java - If/Else/提取字符串的一部分

转载 作者:行者123 更新时间:2023-12-02 06:46:42 26 4
gpt4 key购买 nike

我现在正在做一个项目,并且对它的一个方面感到困惑,

项目标签是:

Create a class encapsulating the concept of a file. Include a constructor, getter/setter, toString method, equals method. The added bit is to one I have trouble with

Also write a method returning the extension of the File, i.e. the letters after the last dot(.) in thefilenameIf the filename is hello1.doc, then the method should return docIf there is no dot(.) in the filename, then the method should return “unknown extension”

这是迄今为止我的 File 类代码

public class File {

private String fileName;

public File()
{

}

public File(String fn)
{
this.fileName = fn;
}


public String getName()
{
return this.fileName;
}


public void setName(String name)
{
this.fileName = name;
}


public String toString()
{
return fileName;

}


public boolean equals(File f1)
{


if (f1.getName().equals(fileName))
{
return true;
}
else
{
return false;
}

}


public void String(File f1){
if (f1.toString().contains(".")){
String h=f1.toString();
String[] parts = h.split(".");
String i= parts[0];
String j= parts[1];
System.out.println("File is of type"+" "+parts[1]);

}
else{
System.out.println("Unkown file extension.");}

}

}

我完全不知道如何完成这个。我认为问题是,当我实例化一个新的"file"对象时,该字符串没有通过我的最终 if/else 传递。如果能朝正确的方向插入,我们将不胜感激:)

干杯

Ps 这是我的测试类(我知道 if/else 应该在上面的主文件中:))

public class Filemain {
public static void main(String[] args) {



File f1 = new File();

File f2 = new File ("test.pdf");
File f3= new File ("results.doc");

System.out.println(f2);
System.out.println(f3);



if (f2.equals(f3))
{
System.out.println("You have not got complete documentation");
}
else
{
System.out.println("You have the complete documentation");



}

最佳答案

我认为问题出在构造函数中

f1.toString()

当你需要做的时候

f1.getName()

加上你的类名已经存在于java中,尝试使用MyFile代替

最后你想使用

public void toString(File f1)

public void extString(File f1)

而不是

public  void String(File f1)

它还能编译吗?

关于java - If/Else/提取字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18558191/

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