【问题标题】:Create for loop in Java to take in information在 Java 中创建 for 循环以获取信息
【发布时间】:2014-12-21 20:30:02
【问题描述】:
我想使用 for 循环向用户询问电影名称、类型和评分,并让它迭代 3 次并存储在一个数组中并将信息显示给用户。
在代码的 for 循环中,我不确定要插入什么作为“电影 1”,以及如何在每次迭代后将其更改为“电影 2”和“电影 3”。
这是我目前所拥有的:
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Creates a Movie array of size three.
Movie[] movies = new Movie[3];
for (int i=0; i < movies.length; i++) {
// Initialises the 3 movie objects in the array.
movies[i] = new Movie();
}
// Loop will execute 3 times.
for (int x = 0; x < 3; x += 1){
System.out.println("Please enter the title of Movie 1: ");
System.out.println("Please enter the genre of Movie 1: ");
System.out.println("Please enter the rating of Movie 1: ");
}
}
【问题讨论】:
标签:
arrays
loops
for-loop
input
【解决方案1】:
你做的大部分事情都是正确的,只是你需要弄清楚在下面的 cmets 中解释的时候该怎么做:
Scanner input = new Scanner(System.in);
// Creates a Movie array of size three.
//here you are declaring your array of movies of size 3
Movie[] movies = new Movie[3];
String name;
//lets ask user to enter movie name three times and simultaneously populate movie object and store them in an array.
for (int i=0; i < movies.length; i++) {
System.out.println("Please enter the title of Movie " + (i+1));
name = input.nextLine();
movies[i] = new Movie(name);
}
// Loop will execute 3 times and just print out the movie names that we populated.
for (int x = 0; x < movies.length; x += 1){
System.out.println("movie " + (x+1) + " is " + movies[x].name);
}
【解决方案2】:
请发布您的电影课程,以帮助我们提出更详细的答案。
你可以试试这样的...
Scanner sc=new Scanner(system.in);
for (int x = 0; x < 3; x++){
System.out.println("Please enter the title of Movie 1: ");
movies[i].title=sc.next();
System.out.println("Please enter the genre of Movie 1: ");
movies[i].genre=sc.next();
System.out.println("Please enter the rating of Movie 1: ");
movies[i].genre=sc.nextInt();
}
使用 x++ 而不是 x+=1 ,尝试在 Java 中使用增强的 for 循环,并使用 import java.util.* 让 Scanner 工作