Return语句打印back字符串和默认的整数值5。我只想打印出字符串。

huangapple go评论70阅读模式
英文:

back. Any sugReturn statement printing back String and default int of 5. I only want the String to printgestions?

问题

以下是翻译好的部分:

我们正在编程课程中学习面向对象编程(OOP),这是我们的第一个作业。我遇到的问题是,它只应该返回“good”,但我却得到了“good 5”。我对所有这些仍然非常陌生,非常希望得到一些建议或修复此问题的提示。

public class Main{
 public static void main(String[] args){
  Dog dog = new Dog();
  System.out.println(dog.checkWeight());
 }
}

// 两个独立的文件 main.java 和 Dog.java

public class Dog{
 String name = "unknown";
 String breed = "mutt";
 int weight = 5;
 
 public int checkWeight(){
  if (weight < 2){
   System.out.println("under-weight");
  }else if (weight > 10){
   System.out.println("over-weight");
  }else{
   System.out.println("good");
  }return weight;
 }
}
英文:

We are learning oop in my programming class and this was our first assignment for it, the problem I'm having is that it is only supposed to return "good" but i'm getting back "good 5". I'm still very new with all of this and would love some suggestions or tips on how to fix this.

public class Main{
 public static void main(String[] args){
  Dog dog = new Dog();
  System.out.println(dog.checkWeight());
 }
}

//Two seperate files main.java and Dog.java

public class Dog{
 String name = &quot;unknown&quot;;
 String breed = &quot;mutt&quot;;
 int weight = 5;
 
 public int checkWeight(){
  if (weight &lt;2){
   System.out.println(&quot;under-weight&quot;);
  }else if (weight &gt; 10){
   System.out.println(&quot;over-weight&quot;);
  }else{
   System.out.println(&quot;good&quot;);
  }return weight;
 }
}

答案1

得分: 1

System.out.println(dog.checkWeight());

改为

dog.checkWeight();

目前,该方法会返回 5 并将其打印出来。

英文:

Change

System.out.println(dog.checkWeight());

to

dog.checkWeight();

Currently, the method returns 5 and you print it.

答案2

得分: 1

更改checkWeight的定义如下:

public String checkWeight() {
    String health = "";
    if (weight < 2) {
        health = "体重过轻";
    } else if (weight > 10) {
        health = "体重过重";
    } else {
        health = "体重正常";
    }
    return health;
}
英文:

Change the definition of checkWeight as follows:

public String checkWeight() {
	String health = &quot;&quot;;
	if (weight &lt; 2) {
		health = &quot;under-weight&quot;;
	} else if (weight &gt; 10) {
		health = &quot;over-weight&quot;;
	} else {
		health = &quot;good&quot;;
	}
	return health;
}

huangapple
  • 本文由 发表于 2020年10月4日 21:39:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/64195336.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定