Home > OS >  An object wont let me specified a particular variable - Java
An object wont let me specified a particular variable - Java

Time:06-12

I'm a new learner in java and created my own program to practice and upskill myself. But I have a problem that states [incompatible types: String cannot be converted to Friend] in which I'm having a hard time to figure out why the specific object wont let me specified variable like "friend.name[i]" Is my logic wrong? How can I fix this? Here's my code:

Main:

package Friendprogram;
import Libraries.*;
import java.util.Scanner;

public class forfunportfolio {
    public static void main(String[] args) {
        
        Squad gang = new Squad ("Thunder", 3, 15, 18);
        Friend [] friend = new Friend [gang.maxSlot]; 
        Scanner input = new Scanner(System.in);

                   for(int i=0; i<gang.maxSlot; i  ){ 
                                                    
                       System.out.printf("Enter Name:");
                       String tmpName = input.next();
                       friend[i] = tmpName; 
                       System.out.println("Enter Age:");
                       int tmpAge = input.nextInt();
                       friend[i] = tmpAge; 
                   }   
                   for(Friend f: friend){
                       gang.Agechecker(f); 
                       gang.newFriend(f); 
                   }
                break;
    }
}

CodePudding user response:

Instead of writing friend[i] = tmpName; and friend[i] = tmpAge;, you need to use the new keyword and the constructor for Friend. But you can pass in the variables as arguments, instead of using constants. That is, you should replace the two problematic lines with this.

friend[i] = new Friend(tmpName, tmpAge);
  •  Tags:  
  • java
  • Related