Java。用户的输入通过实例变量在主类中起作用,而在其他类中则不起作用

用户在songtestdrive主类中工作,但在记录类中工作,输入类歌曲的song1变量的值。在Recording类中,它将用户的值打印为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);
}}

最佳答案

在main中创建的songrock)实例与在songrecording)中创建的song_recording实例是不同的。

您可以将rock变量传递给recording方法

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


来电者成为

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");
}


如果recording实例始终与一首歌曲相关,则为recording类构造函数。

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);
    }
}


来电者成为

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");
}


注意:
遵循Java命名约定来命名类名称。类名应以大写字母开头... SongRecording ...

变量名称必须遵循驼峰大小写样式-songRecording

10-08 07:12