我在网上解决了多个练习,我无法回答这个问题。任务是创建一个程序,接受格式为TITLE-CHARACTER-YEAR的输入,并打印出角色的名称和漫画的年份类别,如下所示
year less than 2000 and print "90s"
2000 less than or equal to year but less than 2006 and print "early 2000s"
2006 less than or equal to year and print "latest"
我尝试过编码,但我对如何正确运行它缺乏逻辑思考。尝试搜索语法但失败了。
public class HelloWorld {
public static void main(String[] args) {
String title1 = "Yuyu Hakusho";
String title2 = "Bleach-Ichigo";
String title3 = "Bakuman";
String name1 = "Eugene";
String name2 = "Ichigo Kurosaki";
String name3 = "Moritaka Mashiro";
int year1 = 1994;
int year2 = 2004;
int year3 = 2008;
if (year1 < 2000);
System.out.println(name1 + " 90s");
}
}
答案 0 :(得分:2)
if (year1 < 2000);
System.out.println(name1 + " 90s");
相当于:
if (year1 < 2000) { }
System.out.println(name1 + " 90s"); //will be always executed
删除;
声明后的多余if
:
if (year1 < 2000);
↑
现在,您需要在代码中使用的另一件事是Scanner
。浏览文档以了解如何使用它。
答案 1 :(得分:2)
要允许您的应用程序从用户输入读取,您有几种方法。最简单的方法是使用Scanner
类。这是一个例子:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Hello, please tell me your name: ");
String name = Scanner.nextLine();
System.out.println("Hello " + name);
}
有几种方法可以帮助您解析用户输入,例如nextInt
和nextLine
。有关它们的更多信息,请查看本文开头链接的正确Javadoc。
除此之外,在编写块语句时要小心,例如if
:
if (year1 < 2000);
上述意味着,如果int变量year1
小于2000
,则无需执行任何操作。
答案 2 :(得分:0)
试试这个。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(" please tell input with format of TITLE-CHARACTER-YEAR ");
String input = scanner.nextLine(); //reads the input from console
String arr[] = new String[3]; // size ur wish
arr=input.split("-"); //splits the input with the - delimiter into array of strings
String name=arr[1]; //contains character
int year=Integer.parseInt(arr[2]); //contains year
if(year<2000)
System.out.println( name + " 90's");
else if(year>=2000 && year<2006)
System.out.println(name + " early 2000's");
else if(year>=2006)
System.out.println(name + " latest");
}
还有很多其他方法可以做到,简单易懂就是这个
对于codingbat.com,请查看此内容。
public String methodName(String input){
String arr[] = new String[3]; // size ur wish
arr=input.split("-"); //splits the input with the - delimiter into array of strings
String name=arr[1]; //contains character
int year=Integer.parseInt(arr[2]); //contains year
if(year<2000)
return name + " 90's";
else if(year>=2000 && year<2006)
return name + " early 2000's";
else if(year>=2006)
return name + " latest";
else
return "wrong format";
}