【问题标题】:How to return two or more strings in java?如何在java中返回两个或多个字符串?
【发布时间】:2020-09-25 18:39:45
【问题描述】:

如何在java中返回两个或多个字符串?我已经尝试了以下代码,但我不知道正确的语法是什么。

import java.util.Scanner;

class cat{
    public String description() {
        String color;
        Scanner sc= new Scanner(System.in);
        System.out.println("enter breed: ");
        String breed= sc.nextLine();
        System.out.println("enter color");
        color= sc.nextLine();
        System.out.println("color is "+ color);
        return new String[] {breed, color};

            }

}
public static void main(String[] args)
{
    cat cat1= new cat();

                System.out.println("breed is: " + cat1.description());
                System.out.println("color is: "+ cat1.description());

}
}

【问题讨论】:

  • 你会返回一个数组或元组或其他什么,但返回值需要与方法签名匹配。

标签: java string return return-value


【解决方案1】:

我认为你应该为你的“猫”类创建字符串属性。

public class Cat {
    private String breed;
    private String color;

    public Cat(String breed, String color) {
        this.breed = breed;
        this.color = color;
    }

    public String getBreed() {
        return this.breed;
    }

    public String getColor() {
        return this.color;
    }
}

现在您可以在 main 方法中访问 getBreed() 和 getColor() 方法。

看来您刚开始使用 oop。也许你应该阅读一些基础知识。

【讨论】:

  • 谢谢您,先生。是的,我刚开始使用 oop。
猜你喜欢
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 2012-10-15
  • 2020-11-13
  • 2022-11-17
  • 1970-01-01
相关资源
最近更新 更多