Hi I am new to Java programming. Here I am trying to implement a code with array of objects. The problem is whenever I try to print. It only prints the last entered value 10 times.
import java.util.*;
class Tax{
int ssn,income;
void Tax(){}
void Tax(int s,int i){
this.ssn=s;this.income=i;
}
int getssn(){
return ssn;
}
int getincome(){
return income;
}
}
public class Usetaxpayer{
public static void main(String[] args){
Tax[] y=new Tax[10];
int i,inc,s=100;
Scanner in=new Scanner(System.in);Tax x=new Tax();
for(i=0;i<10;i++)
{
inc=in.nextInt();y[i]=x;
x.Tax(s,inc);
s++;
}
for(i=0;i<10;i++)
{
System.out.println("SSN"+y[i].getssn()
+"income"+y[i].getincome()+"\n");
}
}
}
Please help me out`
You've mistakenly put void
for the constructor. Also, you need to create the instance inside the loop.
Demo:
import java.util.Scanner;
class Tax {
int ssn, income;
Tax(int s, int i) {
this.ssn = s;
this.income = i;
}
int getssn() {
return ssn;
}
int getincome() {
return income;
}
}
public class Usetaxpayer {
public static void main(String[] args) {
final int SIZE = 2;
Tax[] y = new Tax[SIZE];
int i, inc = 0, s;
Scanner in = new Scanner(System.in);
for (i = 0; i < SIZE; i++) {
System.out.print("Enter SSN: ");
s = in.nextInt();
System.out.print("Enter income: ");
inc = in.nextInt();
y[i] = new Tax(s, inc);
}
for (i = 0; i < SIZE; i++) {
System.out.println("SSN: " + y[i].getssn() + ", income: " + y[i].getincome());
}
}
}
A sample run:
Enter SSN: 123
Enter income: 1000
Enter SSN: 234
Enter income: 2000
SSN: 123, income: 1000
SSN: 234, income: 2000
Note: I've used an array of size, 2 for demo. Change the value of SIZE
as per your requirement.
The problem is you are using one object 10 times and replacing the values again and again. This is persisting only the last value. Try out this:
class Tax{
int ssn,income;
void Tax(){}
void Tax(int s,int i){
this.ssn=s;this.income=i;
}
int getssn(){
return ssn;
}
int getincome(){
return income;
}
}
public class Main{
public static void main(String[] args){
Tax[] y=new Tax[10];
int i,inc,s=100;
Scanner in=new Scanner(System.in);
for(i=0;i<10;i++)
{
Tax x=new Tax();
inc=in.nextInt();
y[i]=x;
x.Tax(s,inc);
s++;
}
for(i=0;i<10;i++)
{
System.out.println("SSN "+y[i].getssn() +"income "+y[i].getincome()+"\n");
}
}
}
You have two errors:
public Tax(){}
public Tax(int s, int i){ this.ssn=s;this.income=i; }
the builders can be public or private according to your need.
Scanner in=new Scanner(System.in); for(i=0;i<10;i++) { inc= in.nextInt(); y[i]= new Tax(s,inc); s++; }
this way you always add a new Tax instance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.