[英]I'm having a hard time understanding and implementing a constructor and I'm looking for some guidance
我正在学习构造函数,但是我看过的视频似乎没有帮助,而且我在 google 上找到的所有内容似乎都以高级的方式描述了它。
我想编写一个简单的程序,它接受两个输入,一个名称(字符串)和一个 id(整数),然后将其输出为“id”-“name”。 例如:
01 - hello
这是我要修复的程序:
import java.util.Scanner;
public class ConstructorTest {
public static void main(String[] args) {
ConstructorTest();
toString(null);
}
//Constructor
public ConstructorTest(){
Scanner name = new Scanner(System.in);
Scanner id = new Scanner(System.in);
}
// Method
public String toString(String name, int id) {
System.out.print(id + " - " + name);
return null;
}
}
我得到的错误是说我的方法和构造函数未定义。
构造函数创建(“构造”)一个新对象。 然后,您可以针对该对象调用方法。
这是一个简单的对象:
public class MyObject {
private int id;
private String name;
public MyObject(int id, String name) {
this.id = id;
this.name = name;
}
// Other methods here, for example:
public void print() {
System.out.println(id + " " + name);
}
}
你会像这样调用这个构造函数:
MyObject thing = new MyObject(1, "test");
然后你可以像这样调用它的方法:
thing.print();
因此,对于您的示例,您在 main 方法中所做的是首先提示用户输入 id 和 name,然后使用构造函数创建一个对象,然后在构造函数上调用一个方法。
public class ConstructorTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// get the id and name from the scanner (I would suggest using prompts)
String name = in.nextLine();
int id = in.nextInt();
// create an object:
ConstructorTest myObject = new ConstructorTest(id, name);
// call the method:
String myString = myObject.toString();
// print the result:
System.out.println(myString);
}
// private variables, effectively the "properties" stored by the object:
private int id;
private String name;
// constructor:
public ConstructorTest(int id, String name) {
this.id = id;
this.name = name;
}
// method
@Override // because this is a method in java.lang.Object and we're overriding it
public String toString() {
return id + " - " + name;
}
}
尝试这个:
import java.util.Scanner;
public class ConstructorTest {
private int id;
private String name;
public static void main(String[] args) {
String name = args[0];
int id = Integer.valueOf(args[1]);
ConstructorTest ct = new ConstructorTest(name, id);
System.out.println(ct);
}
public ConstructorTest(String n, int i) {
this.id = i;
this.name = n;
}
// Method
public String toString() {
return String.format("%d - %s", id, name);
}
}
永远不要将 I/O 放在构造函数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.