Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

// sorts an array of movies by name or year import java.util.*; public class DebugNine2 { public static void main(String[] args) { Scanner input =

// sorts an array of movies by name or year import java.util.*; public class DebugNine2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); Movie[] movies = new Movie[8]; 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); System.out.println( "Sort Movies by (N)ame, or (Y)ear"); entry = input.next(); if(entry.charAt(0) == 'N') { nameSort(movies); message = "Sorted by Name "; } else { yearSort(movies); message = "Sorted by Year "; } display(movies, message); } public static void nameSort(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].getName().compareTo(array[b+1].getName())>0) { temp = array[b]; array[b] = array[b]; array[b + 1] = temp; } } } } public static void yearSort(Movie[] array) { int a, b; Movie temp; int highSub = array.length - 1; 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) { int len = s.length; for (int i = 0; i < len; i++) msg = msg + s[i].getName() + ", " + s[i].getYear() + " "; System.out.println(msg); } } What is wrong with my code? I can sort by year, but not by name. When I used the name sort it give this:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8. Why can I not use the name sort,but I can use the year sort?

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Design Application And Administration

Authors: Michael Mannino, Michael V. Mannino

2nd Edition

0072880678, 9780072880670

More Books

Students also viewed these Databases questions

Question

Comment should this MNE have a global LGBT policy? Why/ why not?

Answered: 1 week ago