Search code examples
javaclassvariablessubclassinstance-variables

Java. User's input is working in main class through instance variable but not in other class


Java. User's input is working in main class through instance variable but not in other class

Users input value of song1 variable of class song in working in songtestdrive main class but not in the recording class. In Recording class it prints the user's value as NULL

import java.util.Scanner;

class songtestdrive{ 
public static void main(String[] args)
{   song rock = new song(); 
    recording record = new recording();
    rock.songtype();
    record.recording();
    // here song class's user value is working with rock.song1 
    System.out.println("So you are "+rock.song1+" Music lover");
}}

class song
{   Scanner in = new Scanner(System.in);

String song1;
 String songtype()
{   System.out.println("Which type of songs you like");
    song1= in.nextLine();
    return(song1);
}}

class recording
{
String record,yesno;
  public void recording()
{   song song_recording = new song();
    // need help here song_recording.song1 is unable to show the user's input instead showing null
    System.out.println("Do you want to record songtype "+ song_recording.song1);
}}

Solution

  • The song(rock) instance you create in main and the song instance you create in recording (song_recording) are different.

    You can pass the rock variable to the recording method

    public void recording(Song song)
    {  
        //song song_recording = new song(); <-- Remove this
        System.out.println("Do you want to record songtype "+ song.song1);
    }
    

    The caller becomes

    public static void main(String[] args)
    {   song rock = new song(); 
        recording record = new recording();
        rock.songtype();
        record.recording(rock);
        System.out.println("So you are "+rock.song1+" Music lover");
    }
    

    Or the recording class constructor if a recording instance is always related to one song.

    class recording {
        String record,yesno;
        Song song;
        class recording(Song song) {
            this.song = song;
        }
         public void recording() {
             //song song_recording = new song(); <-- Remove this
            System.out.println("Do you want to record songtype "+ song.song1);
        }
    }
    

    The caller becomes

    public static void main(String[] args)
    {   song rock = new song(); 
        recording record = new recording(rock);
        rock.songtype();
        record.recording();
        // here song class's user value is working with rock.song1 
        System.out.println("So you are "+rock.song1+" Music lover");
    }
    

    Note: Follow Java naming conventions to name class names. Class names should start with an uppercase letter... Song, Recording...

    Variable names must follow camel case style - songRecording