Reputation: 113
I'm a beginner in Java and wanted to know how can I read a list of objects in Java. I have a problem that asks to implement a list of rational numbers and print them (and some other methods)
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);
}
}
}
So I've tried to read an array of objects: ex: n=4 then first 2 3 second 5 4 .....
I'm getting an error saying Type mismatch: cannot convert from Rational to Rational[]
Upvotes: 0
Views: 979
Reputation: 533
You can use something like
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);
}
}
Upvotes: 1
Reputation: 50041
Assuming you want to take input from the keyboard:
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())));
}
Upvotes: 1