英文:
Check if my code is correct for the following problems given?
问题
以下是翻译好的内容:
我正在学习Java。
我想改进我的代码并回答下面的问题。
- 在Simulator的main()方法内,创建一个"Cat"对象的实例,并调用该对象的run()方法。
我的代码需要额外的信息吗?我想回答上面的问题,以下是我目前的进展:
class Simulator {
public static void main(String[] args) {
Cat c = new Cat();
c.run();
}
}
我是正确的吗?我发现第二个类返回一个随机整数。这样可以用来调用run方法吗?
英文:
I am just learning Java.
And I want to improve my code and answer the question below.
3.Inside the main() method of Simulator , create an instance of a "Cat" object, and invoke that object's run() method.
Does my code require additional information? I want to answer the above question and this is what I have so far:
class Simulator {
public static void main(String[] args) {
Cat c = new Cat();
System.out.println(c);
}
}
Am I correct? I found the second class returns as an random integer. Will that work to invoke the run method.
答案1
得分: 1
有很多问题...
-
“代码片段” 适用于 JavaScript。而你的程序是 Java。Java <> Javascript
-
你的“Cat”对象实现了一个线程。你使用线程进行并发操作,以同时执行任务。难道你的“meow”真的值得开启一个线程吗?
-
那么成员变量“1”呢?你声明它,初始化它,然后却没有在任何地方使用它。问:这样做有何意义?
-
System.out.println(c)
打印的是“对象”本身;并不打印任何“有意义”的内容。
建议修改:
public class Cat
{
private int i;
public void meow() {
System.out.println("Meowing: " + i);
}
public Cat(int i) {
this.i = i;
}
public static void main(String args[]) {
Cat cat = new Cat (1);
cat.meow();
}
}
英文:
There are so many things wrong...
-
"Code snippets" are for Javascript. Your program is Java. Java <> Javascript
-
Your "Cat" object implements a thread. You use threads for "concurrency", to do things "in parallel". Does your "meow" really merit spawning off a thread?
-
What about member "1"? You declare it. You initialize it. And then you fail to use it for ANYTHING. Q: Why bother?
-
System.out.println(c)
prints the "object"; it doesn't print anything "meaningful".
Suggested modifications:
public class Cat
{
private int i;
public void meow() {
System.out.println("Meowing: " + i);
}
public Cat(int i) {
this.i = i;
}
public static void main(String args[]) {
Cat cat = new Cat (1);
cat.meow();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论