gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:01:51 28 4
gpt4 key购买 nike

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

用户在songtestdrive主类中输入类song的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 中创建的 song(rock) 实例和您在 recording 中创建的 song 实例( 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

关于 java 。用户的输入通过实例变量在主类中起作用,但在其他类中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51464997/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com