-6

       **NEVERMIND, I CHEATED**

Movie[] movies = new Movie[8];
movies[0] = new Movie("The Godfather", 1972);

假设我有一堆电影变量,我怎么能在电影 [] 变量中设置一个变量(称之为年份或其他东西)到年份?

(我在编程课上,我的任务是调试一个文件,我唯一的错误是我需要将年份变量设置为电影 [] 中的年份)

这是我的完整代码:

import javax.swing.*;
public class DebugNine2
{
public static void main(String[] args)
   {
  Movie[] movies = new Movie[8];
  Movie[] year;
  int i;
  String message, entry;
  movies[0] = new Movie("The Godfather", 1972);
  movies[1] = new Movie("The Good, the Bad, and the Ugly", 1966);
  movies[2] = new Movie("Pulp Fiction", 1994);
  movies[3] = new Movie("Shindler's List", 1993);
  movies[4] = new Movie("Casablanca", 1942);
  movies[5] = new Movie("Wizard of Oz", 1939);
  movies[6] = new Movie("Citizen Kane", 1941);
  movies[7] = new Movie("Some Like It Hot", 1959);
  entry = JOptionPane.showInputDialog(null,
    "Sort Movies by\n(N)ame, or (Y)ear");
  if(entry.equals("N"))
  {
     nameSort(movies);
     message = "Sorted by Name\n";
  }
  else
  {
      year=movies;
      yearSort(year);
      message = "Sorted by Year\n";
  }   
  display(movies, message);
  //System.out.println(movies+"\n"+message);
}
public static void nameSort(Movie[] array)
{
  int a, b;
  int highSub = array.length - 1;
  for(a = 0; a < highSub; ++a)
  {
     for(b = 0; b < highSub; ++b)
 {
         String first = array[b].getName();
         String second = array[b + 1].getName();
         if(first.compareTo(second) > 0)
     {

        Movie temp = array[b];
        array[b] = array[b + 1];
        array[b + 1] = temp;
     }
  }
   }
}
public static void yearSort(Movie[] array)
{
    int a, b;
    Movie temp;
    int highSub = array.length;
    for (a = 0; a < highSub; ++a)
    {
       for (b = 0; b < highSub; ++b)
       if (array[b].getYear() > array[b + 1].getYear())
       {
          temp = array[b];
          array[b] = array[b + 1];
          array[b + 1] = temp;
       }
    }
 }
 public static void display(Movie[] s,  String msg)
 {
    for (int i = 0; i < 8; i++)
       msg = msg + s[i].getName() + ", " + s[i].getYear() + "\n";
    JOptionPane.showMessageDialog(null, msg);
 }
}

此外,还有一个名为 Movie.java 的文件,其中包含代码

public class Movie
{
private String name;
private int year;
Movie(String s, int y)
{
  name = s;
  year = y;
}
public String getName()
{ 
  return name;
}
public int getYear()
{
  return year;
}
}
4

2 回答 2

1

Movie 类可以有 String name 和 int year 字段。获取它们的 setter 和 getter 方法。通过构造函数初始化它们,比如 new Movie(String name , int year);

于 2013-04-16T16:53:22.667 回答
0

您不能设置电影对象的年份,因为该变量是私有的。您需要创建一个公共方法来更改值或使变量本身公开。

于 2013-04-16T16:52:42.600 回答