2014-02-17 4 views
0

поэтому я пишу программу, в которой должен быть список предметов, которые являются либо играми, либо фильмами. Каждый элемент имеет 3-значный идентификационный номер (сохраненный как строка), заголовок, цену, проверку запасов (вкл/выкл) и имя арендатора (либо имя, либо пустое). Я должен был иметь список пунктов меню вещей, связанных с этими элементами. Класс предмета является абстрактным, и оба фильма и игры расширяют его. Вот код магазина для магазина:Ошибка ввода ошибки несоответствия с наследованием

import java.util.*; 
import java.io.*; 
public class MovieStore 
{ 
    private Item[] items=null; 
    private int numItems; 

    public MovieStore() //default constructor 
    { 
    items=new Item[30]; 
    numItems=0; 
    } 

    public MovieStore(String testFileName) throws IOException 
    { 
    File f=new File(testFileName); 
    if(!f.exists()) 
    { 
     System.out.println("File "+testFileName+" does not exist."); 
     System.exit(0); 
    } 
    Scanner input=new Scanner(f); 

    items=new Item[30]; 
    numItems=0; 
    String code; 
    while (input.hasNext()) 
    { 
     code=input.next(); 
     if (code.equals("M")) 
     { 
     String id=input.next(); 
     String title=input.next(); 
     double price=input.nextDouble(); 
     int runTime=input.nextInt(); 
     String rating=input.next(); 
     String format=input.next(); 
     int stockcheck=input.nextInt(); 
     String renter=input.next(); 
     if (stockcheck==1) //true, in stock 
      items[numItems]=new Movie(id, title, price, true, runTime, rating, format); 
     else //false, not in stock 
      items[numItems]=new Movie(id, title, price, false, renter, runTime, rating, format); 
     } 
     else if (code.equals("G")) 
     { 
     String id=input.next(); 
     String title=input.next(); 
     double price=input.nextDouble(); 
     int stockcheck=input.nextInt(); 
     int ageLevel=input.nextInt(); 
     String renter=input.next(); 
     if (stockcheck==1) //true, in stock 
      items[numItems]=new Game(id, title, price, true, ageLevel); 
     else //false, not in stock 
      items[numItems]=new Game(id, title, price, false, renter, ageLevel); 
     } 
     numItems++; 
    } 
    SelectionSort.sort(items, numItems); 
    } 

    public int search(String id) 
    { 
    Item key=new Item(id, "", 0.0, true, ""); 
    return (BinarySearch.search(items, numItems, key)); 
    } 

    public void addItem(Item s) 
    { 
    items[numItems]=s; 
    numItems++; 
    SelectionSort.sort(items, numItems); 
    } 


    public static String menu() 
    { 
    String code=""; 
    Scanner input=new Scanner(System.in); 
    System.out.println("Enter one of the following options as a letter."); 
    System.out.println("a. Check out an item."); 
    System.out.println("b. Check in an item."); 
    System.out.println("c. Search an item by ID to see if it is in stock."); 
    System.out.println("d. Search an item by name."); 
    System.out.println("e. Display inventory."); 
    System.out.println("f. Add a new item to the inventory."); 
    System.out.println("g. Delete an item from the inventory."); 
    System.out.println("h. Display the menu."); 
    System.out.println("i. Exit."); 
    return (input.next()); 
    } 

    public void performAction(String choice) 
    { 
    Scanner input=new Scanner(System.in); 
    if (choice.equalsIgnoreCase("a")) 
    { 
     BinarySearch s=new BinarySearch(); 
     System.out.println("Enter the ID Number of the item."); 
     String id=input.next(); 
     int search=search(id); 
     if (search==-1) 
     System.out.println("Item not found. Try again."); 
     else 
     { 
     if (items[search].getStock()==false) 
      System.out.println("Sorry, this item is out of stock."); 
     else 
     { 
      System.out.println("Please enter the renter's name in the format last,first [with no spaces]."); 
      String name=input.next(); 
      items[search].setName(name); 
      items[search].setStock(false); 
      System.out.println("Item checked out."); 
     } 
     } 
    } 
    else if (choice.equalsIgnoreCase("b")) 
    { 
     BinarySearch s=new BinarySearch(); 
     System.out.println("Enter the ID Number of the item."); 
     String id=input.next(); 
     int search=search(id); 
     if (search==-1) 
     System.out.println("Item not found. Try again."); 
     else 
     { 
     if (items[search].getStock()==true) 
      System.out.println("This item is already in stock."); 
     else 
     { 
      items[search].setName(""); 
      items[search].setStock(true); 
      System.out.println("Item checked in."); 
     } 
     } 
    } 
    else if (choice.equalsIgnoreCase("c")) 
    { 
     BinarySearch s=new BinarySearch(); 
     System.out.println("Enter the ID Number of the item."); 
     String id=input.next(); 
     int search=search(id); 
     if (search==-1) 
     System.out.println("Item not found. Try again."); 
     else 
     { 
     if (items[search].getStock()==true) 
     { 
      System.out.println("This item is in stock."); 
      System.out.println(items[search]); 
     } 
     else 
     { 
      System.out.println("This item is not in stock."); 
      System.out.println(items[search]); 
     } 
     } 
    } 
    else if (choice.equalsIgnoreCase("d")) 
    { 
     System.out.println("Enter the title of the item [using dashes instead of spaces]."); 
     String title=input.next(); 
     for (int i=0; i<numItems; i++) 
     { 
     if (title.equals(items[i].title)) 
     { 
      if (items[i].getStock()==true) 
      { 
      System.out.println("This item is in stock."); 
      System.out.println(items[i]); 
      } 
      else 
      { 
      System.out.println("This item is not in stock."); 
      System.out.println(items[i]); 
      } 
     } 
     } 
    } 
    else if (choice.equalsIgnoreCase("e")) 
    { 
     for (int i=0; i<numItems; i++) 
     items[i].display(); 
    } 
    else if (choice.equalsIgnoreCase("f")) 
    { 
     System.out.println("Please enter an M for a movie or a G for a game."); 
     String type=input.next(); 
     if (type.equalsIgnoreCase("M")) 
     { 
     System.out.println("Please enter the ID number for the movie."); 
     String id=input.next(); 
     System.out.println("Please enter the movie's title (no spaces, dashes instead)."); 
     String title=input.next(); 
     System.out.println("Please enter the price of the movie."); 
     double price=input.nextDouble(); 
     System.out.println("Please enter the run time of the movie."); 
     int runTime=input.nextInt(); 
     System.out.println("Please enter the rating of the movie."); 
     String rating=input.next(); 
     System.out.println("Please enter the format of the movie, V(HS) or D(VD)."); 
     String format=input.next(); 
     Item s=new Movie(id, title, price, true, runTime, rating, format); 
     addItem(s); 
     } 
     else if (type.equalsIgnoreCase("G")) 
     { 
     System.out.println("Please enter the ID number for the game."); 
     String id=input.next(); 
     System.out.println("Please enter the games's title (no spaces, dashes instead)."); 
     String title=input.next(); 
     System.out.println("Please enter the price of the game."); 
     double price=input.nextDouble(); 
     System.out.println("Please enter the age level of the game."); 
     int ageLevel=input.nextInt(); 
     Item s=new Game(id, title, price, true, ageLevel); 
     addItem(s); 
     } 
     else 
     System.out.println("Invalid input. Try again."); 
    } 
    else if (choice.equalsIgnoreCase("g")) 
    { 
     System.out.println("Delete item."); 
    } 
    } 


    public static void main(String [] args) throws IOException 
    { 
    MovieStore m = new MovieStore("data.txt"); 
    String choice; 
    do 
    { 
     System.out.println(); 
     choice = m.menu(); 
     m.performAction(choice); 
     System.out.println(); 
    } while (!choice.equalsIgnoreCase("I")); //exits when you click i 
    } 
} 

Кино и игровые классы аналогичны. Предмет реализует сопоставимые и сравнивает, исходя из идентификационного номера. У них есть разные конструкторы, основанные на их предметах, но они созданы правильно в программе MovieStore. Вот файл data.txt

M 121 The-Departed 4.90 209 R D 0 Underwood,Frank 
G 698 Drakes-Uncharted 3.90 0 16 White, Walter 
M 345 Frozen 5.50 163 G D 0 Sheeran,Ed 
M 768 School-of-Rock 1.99 155 PG V 1 empty 
G 904 Lego-Batman 6.77 0 6 Pinkman,Jesse 
M 564 The-Hobbit 6.50 255 PG13 D 0 Swift,Taylor 
G 532 Wii-Sports 4.35 0 12 Goodman,Saul 
M 196 Scarface 3.68 213 R V 1 empty 
M 333 Love-Actually 4.58 130 PG13 D 1 empty 
M 889 Shutter-Island 6.98 193 PG13 D 0 Smith,Matt 
M 508 The-Notebook 3.45 175 PG13 V 1 empty 
G 132 Fifa 8.99 0 7 Stark,Ned 
G 666 Call-of-Duty 0 16 Snow,Jon 
M 401 Titanic 5.90 240 PG13 V 1 empty 
M 837 The-Amazing-Spiderman 6.89 198 PG D 0 Pond,Amy 
M 424 The-Wolf-of-Wall-Street 9.99 216 R D 0 Lannister,Tyrion 
G 999 Battlefield 7.88 1 16 empty 
G 444 Borderlands 6.44 1 14 empty 
M 774 Mean-Girls 3.50 154 PG13 V 1 empty 
M 582 Flight 5.66 201 R D 0 Montgomery,Aria 
G 999 Madden 4.33 1 10 empty 
M 130 The-Boondock-Saints 6.77 234 R V 0 Beckham,David 
M 420 Airplane! 6.55 121 PG V 1 empty 
M 699 Inception 7.56 221 PG13 D 0 Mars,Bruno 
G 100 Civilization 8.99 1 16 empty 
M 834 The-Great-Gatsby 8.55 215 PG13 D 1 empty 
M 555 The-Grinch 2.11 121 G V 1 empty 
G 333 Pokemon 1.50 1 6 empty 
M 800 21-Jump-Street 5.10 200 PG13 D 1 empty 
M 945 Pitch-Perfect 7.89 191 PG13 D 0 Cyrus,Miley 

А вот ошибка я получаю, когда я запустить программу:

java.util.InputMismatchException 
    at java.util.Scanner.throwFor(Scanner.java:840) 
    at java.util.Scanner.next(Scanner.java:1461) 
    at java.util.Scanner.nextInt(Scanner.java:2091) 
    at java.util.Scanner.nextInt(Scanner.java:2050) 
    at MovieStore.<init>(MovieStore.java:51) 
    at MovieStore.main(MovieStore.java:233) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
    at java.lang.reflect.Method.invoke(Method.java:597) 
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272) 

Если вы могли бы просто объяснить ошибку и дайте мне знать, что я делаю неправильно, это было бы здорово! Спасибо, парни!

ответ

2

Я бы просто добавил это в качестве комментария, но у меня нет репутации, чтобы добавлять комментарии.

Похоже, проблема связана с входным файлом и необязательным кодом.

Если вы прочитали этот API о том, что может вызвать исключение InputMismatchException при использовании объекта сканера, это будет иметь смысл.

Вторая строка вашего входного файла имела место во имя арендатора фильма/игры. Вызов scanner.next() будет считаться с буфера до этого места. Это приводит к тому, что сканер подбирает имя до точки в пространстве, тогда остальная часть имени ожидает, чтобы его прочитали. После вызова scanner.nextInt() вы ожидаете прочитать int, но в буфере есть строка, вызывающая исключение InputMismatch.

G 698 Drakes-Uncharted 3.90 0 16 White, Walter 
+0

Хорошее место с пространством! – ATG

+0

Спасибо за голосование, поэтому теперь я могу добавлять комментарии. :-) – Justine

 Смежные вопросы

  • Нет связанных вопросов^_^