我正在创建一种方法来接受用户的输入并验证它以确保它是正确的。如果它是正确的,它将调用一个方法并输入用户输入。但由于某种原因,方法调用不起作用。它不会产生任何错误,它只是没有做到。我在代码的末尾放置了一个print语句,以确保它实际到达那里并确实如此,但由于某种原因,它只是没有像它应该的那样调用方法。如果我自己调用它并通过参数输入字符串,则另一种方法可以正常工作。
代码是:
public void getGetScheduledShowByFilmInput()////new - omar////
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
String filmInput;
filmInput = "";
boolean foundFilm;
foundFilm = false;
System.out.println("Here is a list of films that are currently showing:");
for(Film film : films){
System.out.println(film.getFilmName());
}
System.out.println("");
System.out.println("Please type the film name that you wish to view the corresponding shows for and press enter.");
System.out.println("Type 'exit' and press enter to exit this process.");
while(foundFilm == false){
try{
filmInput = reader.readLine();
}
catch (IOException e){
System.out.println("Error");
}
//If user enters "exit" then return.
if(filmInput.equals("exit")){
return;
}
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName() == filmInput){
foundFilm = true;
break;
}
}
if(foundFilm = true){
System.out.println("Film found.");
}
else{
System.out.println("The film name you entered has not been recognised. Please try again.");
}
}
//Call the function and input the film name input by the user.
getScheduledShowsByFilm(filmInput); ////This is the code that seems to be the problem.
System.out.println("reached bottom");
}
,第二种方法是:
public void getScheduledShowsByFilm(String inputFilmName)
{
ArrayList<Show> scheduledShows;
scheduledShows = new ArrayList<Show>();
for(Film film : films){
if(inputFilmName == film.getFilmName()){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}
for(Show show : scheduledShows){
System.out.println("**********************************");
show.getShowDetails();
System.out.println("**********************************");
}
}
当我自己调用它并手动输入参数时,第二种方法非常有效。
这可能非常简单,我不理解!哈哈,谢谢你的帮助:)
答案 0 :(得分:2)
foundFilm永远不会是假的,因为你总是赋予它真实:
if(foundFilm = true){
System.out.println("Film found.");
}
尝试将其更改为:
if(foundFilm)
{
System.out.println("Film found.");
}
答案 1 :(得分:0)
在getGetScheduledShowByFilmInput()
和getScheduledShowsByFilm(String)
中,避免使用相等运算符(==)进行字符串比较。 ==运算符测试对象相等性,但是您想测试两个字符串是否包含相同的字符序列。因此,请改用equals
:
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName().equals(filmInput)){
foundFilm = true;
break;
}
}
和
for(Film film : films){
if(inputFilmName.equals(film.getFilmName())){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}