如何将键盘输入传递给构造函数?

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

how to pass keyboard input to a constructor?

问题

如何将用户输入传递给构造函数以供进一步处理,我应该使用BufferedReader吗?

Constructor(String nameClient, String idClient)

BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
try {
    System.out.println("插入一些名称:");
    String nameClient = obj.readLine();
    System.out.println("插入一些ID:");
    String idClient = obj.readLine();
} catch(Exception e) {
    System.out.println(e);
}
英文:

How could I pass the input from the user in the constructor for further workings, should i use bufferedreader or not

Constructor(String nameClient, String idClient)


BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
try {
	System.out.println("Insert some name: ");
	String nameClient=obj.readLine();
	System.out.println("Insert some id: ");
	String idClient=obj.readLine();
} catch(Exception e) {
    System.out.println(e);
}

答案1

得分: 0

你在创建对象时需要调用构造函数。

以下是一个示例:

import java.io.BufferedReader;
import java.io.InputStreamReader;

class SomeClass {
    String nameClient;
    String idClient;

    public SomeClass(String nameClient, String idClient) {
        this.nameClient = nameClient;
        this.idClient = idClient;
    }
    // ...
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("插入一些名称:");
            String nameClient = obj.readLine();
            System.out.println("插入一些 ID:");
            String idClient = obj.readLine();
            SomeClass someObj = new SomeClass(nameClient, idClient);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

查看此链接获取更多信息。

英文:

You need to call the constructor while creating an object.

I have given below an example:

import java.io.BufferedReader;
import java.io.InputStreamReader;

class SomeClass {
	String nameClient;
	String idClient;

	public SomeClass(String nameClient, String idClient) {
		this.nameClient = nameClient;
		this.idClient = idClient;
	}
	// ...
}

public class Main {
	public static void main(String[] args) throws InterruptedException {
		BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
		try {
			System.out.println("Insert some name: ");
			String nameClient = obj.readLine();
			System.out.println("Insert some id: ");
			String idClient = obj.readLine();
			SomeClass someObj = new SomeClass(nameClient, idClient);
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}

Check this for more information.

huangapple
  • 本文由 发表于 2020年3月4日 03:56:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/60514585.html
匿名

发表评论

匿名网友

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

确定