我是Java的初学者,想知道如何读取Java中的对象列表。我有一个问题,要求实现有理数的列表并打印它们(以及其他一些方法)
import java.util.Scanner;
public class Rational {
private int a;
private int b;
public Rational (int a, int b){
this.a = a;
this.b = b;
}
@Override
public String toString() {
return a + "/" + b;
}
public static void main(String []args) throws Exception {
// Take input from the user in the form of 2 numbers
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
Rational array[] = new Rational[n];
for(int i=0;i<n;i++) {
int num = scanner.nextInt();
int deno = scanner.nextInt();
// Create a rational obj with 2 args
Rational array[i] = new Rational(num, deno);
}
}
}
所以我试图读取一个对象数组:例如:n = 4然后是第2个3秒5 4 .....
我收到错误提示类型不匹配:无法从Rational转换为 理性[]
答案 0 :(得分:1)
假设你想从键盘输入信息:
Scanner scanner = new Scanner(System.in);
List<Rational> rationals = new ArrayList<>(); // create a list
String line = scanner.nextLine(); // read list of numbers; e.g., "1/2, 3/4, 7/8"
for (String rational : line.split(",")) { // split string at each ","
String[] parts = rational.split("/"); // split each of those at "/" character
rationals.add(new Rational( // parse each half as int; create Rational; add to list
Integer.parseInt(parts[0].trim()),
Integer.parseInt(parts[1].trim())));
}
答案 1 :(得分:1)
您可以使用类似
的内容public class Rational {
private int a;
private int b;
public Rational (int a, int b){
this.a = a;
this.b = b;
}
@Override
public toString() {
return a + "/" + b;
}
public static void main(String []args) throws Exception {
// Take input from the user in the form of 2 numbers
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
int deno = scanner.nextInt();
// Create a rational obj with 2 args
Rational x = new Rational(num, deno);
System.out.println(x);
}
}