【发布时间】:2015-01-28 12:45:19
【问题描述】:
我正在做一个练习,我必须选择一个电影类别(类型),根据我的选择,程序将从对象的 ArrayList 中返回该类别中的电影列表。
我的程序在以字符串格式输入类别时工作。但是我正在尝试使用 try catch 块来允许按数字选择类别。
我的 catch 块正在工作,但是我的 try 块没有并且不返回任何内容。有人可以帮我确定我的代码有什么问题吗?我猜我的 parseInt 分配有问题?
System.out.print("What category are you interested in?");
String catSel = sc.next();
try //Check category for Integer, otherwise catch
{
int numSel = Integer.parseInt(catSel);
if(numSel == 1)
{catSel = "animated" ;}
if(numSel == 2)
{catSel = "drama";}
if(numSel == 3)
{catSel = "horror";}
if(numSel == 4)
{catSel = "scifi";}
if(numSel == 5)
{catSel = "musical";}
if(numSel == 6)
{catSel = "comedy";}
else catSel = "";
//Check each movie for chosen category
for(int x = 0; x < list.size() - 1; x++)
{
if(catSel.equals(list.get(x).category))
System.out.println(list.get(x).movie);
}
}
catch (NumberFormatException e)
{
//Check each movie for chosen category
for(int x = 0; x < list.size() - 1; x++)
{
if(catSel.equals(list.get(x).category))
System.out.println(list.get(x).movie);
}
}
【问题讨论】:
-
那么,这里有什么问题,你能澄清一下吗?
-
有 catSel 值还是在 try 块中总是调用 else?
-
当您输入类别的数值(例如 1、2、3 等)时,它应该检查字符串中的整数,然后相应地设置类别并返回该类别中的所有电影。它没有。但是,如果我键入“戏剧”类别,它就可以正常工作。