2015-07-08 1 views
0

Все, что мне нужно, это повторить цикл, чтобы пользователь мог постоянно использовать программу, если она есть. Дайте мне знать, если есть какая-либо ссылка, которую я могу прочитать, чтобы помочь мне понять больше об этой проблеме. Заранее спасибо.Как исправить ошибку «java.util.InputMismatchException»?

import java.util.Scanner; 

public class Module3Assignment1 { 

    // public variables 
    public static String letterChosen; 
    public static int loop = 0; 
    public static double radius, area; 
    public static Scanner scanner = new Scanner(System.in); 

    public static void main(String[] args) { 

     // tells user what the program is about 
     System.out.println("Welcome to the Round Object Calculator"); 
     System.out.println("This program will calculate the area of a circle of the colume of a sphere."); 
     System.out.println("The calculations will be based on the user input radius."); 
     System.out.println(""); 

      // loops while the user wants to calculate information 
      while (loop == 0){ 

       Input(); 
       System.out.print(Answer()); 

       System.out.println("Do you want to calculate another round object (Y/N)? "); 
       String input = scanner.next().toUpperCase(); 
        if (input == "N"){ 
         loop = 1; 
         } 
      } 

     // ending message/goodbye 
     Goodbye(); 
     scanner.close(); 

    } 

    private static void Input(){ 

     // prompts user for input 
     System.out.print("Enter C for circle or S for sphere: "); 
     letterChosen = scanner.nextLine().toUpperCase(); 
     System.out.print("Thank you. What is the radius of the circle (in inches): "); 
     radius = scanner.nextDouble(); 

    } 

    private static double AreaCircle(){ 

     // calculates the area of a circle 
     area = Math.PI * Math.pow(radius, 2); 
     return area; 

    } 

    private static double AreaSphere(){ 

     // calculates the area of a sphere 
     area = (4/3) * (Math.PI * Math.pow(radius, 3)); 
     return area; 

    } 

    private static String Answer(){ 

     //local variables 
     String answer; 

     if(letterChosen == "C"){ 
      // builds a string with the circle answer and sends it back 
      answer = String.format("%s %f %s %.3f %s %n", "The volume of a circle with a radius of", radius, "inches is:", AreaCircle(), "inches"); 
      return answer; 
     }else{ 
      // builds a string with the sphere answer and sends it back 
      answer = String.format("%s %f %s %.3f %s %n", "The volume of a sphere with a radius of", radius, "inches is:", AreaSphere(), "cubic inches"); 
      return answer; 
     } 
    } 

    private static String Goodbye(){ 

     // local variables 
     String goodbye; 

     // says and returns the goodbye message 
     goodbye = String.format("%s", "Thank you for using the Round Object Calculator. Goodbye"); 
     return goodbye; 
    } 

} 

Внизу консольный вывод и ошибка я получаю после выполнения

Welcome to the Round Object Calculator 
This program will calculate the area of a circle of the colume of a sphere. 
The calculations will be based on the user input radius. 

Enter C for circle or S for sphere: C 
Thank you. What is the radius of the circle (in inches): 12 
The volume of a sphere with a radius of 12.000000 inches is: 5428.672 cubic inches 
Do you want to calculate another round object (Y/N)? 
Y 
Enter C for circle or S for sphere: Thank you. What is the radius of the circle (in inches): C 
Exception in thread "main" java.util.InputMismatchException 
    at java.util.Scanner.throwFor(Scanner.java:840) 
    at java.util.Scanner.next(Scanner.java:1461) 
    at java.util.Scanner.nextDouble(Scanner.java:2387) 
    at Module3Assignment1.Input(Module3Assignment1.java:48) 
    at Module3Assignment1.main(Module3Assignment1.java:24) 
+0

Читать http://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html – Sneh

+0

Что ** ** точно ваша проблема? Что происходит? Чего вы хотите сделать? Можете ли вы привести пример неудачи? – TDG

+0

ah sorry забыл вставить это. Во втором цикле после первого утверждения, которое у меня есть, я получаю это .... Исключение в потоке «main» java.util.InputMismatchException \t at java.util.Scanner.throwFor (Unknown Source) \t на java.util.Scanner.next (Unknown Source) \t в java.util.Scanner.nextDouble (Unknown Source) \t в Module3Assignment1.Input (Module3Assignment1.java:47) \t в Module3Assignment1 .main (Module3Assignment1.java:25) – Joe

ответ

0
import java.util.Scanner; 

public class Module3Assignment1 { 
// public static variables are discouraged... 
private static char letterChosen; //char takes less memory 
private static char useAgain = 'Y'; //just use the answer to loop... 
private static double radius, area; 
private static String answer; 
private static Scanner scanner = new Scanner(System.in); 


//you might want to clear the screen after the user gave an answer to another round object 
private static void clearScreen(){ 
    for(int i =0;i<50;i++){System.out.print("\n");} 
} 

public void input(){ 

    // prompts user for input 
    System.out.print("Enter C for circle or S for sphere: "); 
    letterChosen = scanner.next().charAt(0); 
    System.out.print("Thank you. What is the radius of the circle (in inches): "); 
    radius = scanner.nextDouble(); 
    this.answer= answer(letterChosen); 

} 

public double areaCircle(double radius){ 

    // calculates the area of a circle 
    area = Math.PI * Math.pow(radius, 2); 
    return area; 

} 

public double areaSphere(double radius){ 

    // calculates the area of a sphere 
    area = (4/3) * (Math.PI * Math.pow(radius, 3)); 
    return area; 

} 

public String answer(char letterChosen){ 

    //local variables 
    String answer = ""; 
    if(letterChosen=='c'||letterChosen=='C'){ 
     answer = String.format("%s %f %s %.3f %s %n", "The volume of a circle with a radius of", radius, "inches is:", areaCircle(radius), "inches"); 
    }else{ 
     answer = String.format("%s %f %s %.3f %s %n", "The volume of a sphere with a radius of", radius, "inches is:", areaSphere(radius), "cubic inches"); 
    } 
    return answer; 
} 

private static String goodbye(){ 

    // local variables 
    String goodbye; 

    // says and returns the goodbye message 
    goodbye = String.format("%s", "Thank you for using the Round Object Calculator. Goodbye"); 
    return goodbye; 
} 

public static void main(String[] args) { 

    // tells user what the program is about 
    System.out.println("Welcome to the Round Object Calculator"); 
    System.out.println("This program will calculate the area of a circle of the colume of a sphere."); 
    System.out.println("The calculations will be based on the user input radius."); 
    System.out.println(""); 
    Module3Assignment1 ass1 = new Module3Assignment1(); 

     // loops while the user wants to calculate a round object 
     while (useAgain == 'Y'||useAgain=='y'){ 

      ass1.input(); 
      System.out.print(answer); 
      System.out.println("Do you want to calculate another round object (Y/N)? "); 
      useAgain = scanner.next().charAt(0); 
      System.out.println(useAgain); 
      clearScreen(); 
     } 

    // ending message/goodbye 
    System.out.println(goodbye()); 
    scanner.close(); 

} 

}

Некоторые вещи, которые я изменил:

  • я использовал полукокса вместо строки. Строка занимает другая память than знак.
  • добавлен метод clearScreen(), который «очищает» экран при использовании консоли.
  • Я добавил радиус параметра в методы areaSphere и areaCircle. Это делает методы многоразовыми.

  • Я изменил все статические переменные public на private static. используя общедоступные статические переменные is ВЫСОКО ОТКРЫТЫЙ. Вы можете прочитать this, чтобы узнать, почему.

  • и для предотвращения общедоступных статических переменных я создал экземпляр модуля 3Assignment1 вместо того, чтобы иметь все в статике.

  • изменен облик имен методов. Пожалуйста, следуйте верблюжьего корпуса, что означает, что первая буква метода в нижнем регистре, а остальные слова будут иметь первую букву в верхнем регистре (например, вход(), areaSphere())

Комментарий о сравнении строк :

== сравнивает ссылки на объект, НЕ ЗНАЧЕНИЯ

использовать .equals() или .equalsIgnoreCase(), если вы хотите сравнить значения двух строк. вот пример синтаксиса:

if(string1.equals(string2)){ 
//do something 
} 
0

Concept One

Всегда использовать .equals Method Сравнивая строки в Java

Таким образом,

if(letterChosen == "C") 

Должно быть if(letterChosen.equals("C")) и так Другие

Concept Two.

Возможно, это одна из причин, которые происходят с вашим кодом. Вы уже выбрали UserInput из объекта клавиатуры класса сканера, поэтому он дает ответ else. Это особенно происходит, если вы берете на себя другой вход, чем String от этого объекта.

Это потому, что метод Scanner # nextDouble не считывает последний символ новой строки вашего ввода и, следовательно, эта строка используется в следующем вызове Scanner # nextLine ,

WorkAround Fire a blank Scanner#nextLine call after Scanner#nextDouble to consume newline. 

Or Use Two Scanner Object. 

Demo Что происходит с тем же объектом сканера для обоих nextLine() и nextInt()

общественного класс Test {

public static void main(String[] args) { 
     Scanner keyboard= new Scanner(System.in); 
     int n=keyboard.nextInt(); 

     String userResponse; 
     while(true) { 
      userResponse = keyboard.nextLine(); 
      if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') { 
       System.out.println("Great! Let's get started."); 
       break; 
      } 
      else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') { 
       System.out.println("Come back next time " + "" + "."); 
       System.exit(0); 
      } 
      else { 
       System.out.println("Invalid response."); 
      } 
     } 
    } 

} 

Выходного

5 
Invalid response. 

Теперь измените код структуру, чтобы получить String. Вход из этого объекта сканера и не получить другой тип данных, который работает код.

С строки, как предыдущий Input

public class Test { 

    public static void main(String[] args) { 
     Scanner keyboard= new Scanner(System.in); 
     String n=keyboard.nextLine(); 
     String userResponse; 
     while(true) { 
      userResponse = keyboard.nextLine(); 
      if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') { 
       System.out.println("Great! Let's get started."); 
       break; 
      } 
      else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') { 
       System.out.println("Come back next time " + "" + "."); 
       System.exit(0); 
      } 
      else { 
       System.out.println("Invalid response."); 
      } 
     } 
    } 

} 

Выход

j 
y 
Great! Let's get started. 

Без предыдущего ответа с тем, что объект ваш код будет работать.

public class Test { 

    public static void main(String[] args) { 
     Scanner keyboard= new Scanner(System.in); 

     String userResponse; 
     while(true) { 
      userResponse = keyboard.nextLine(); 
      if(userResponse.length() == 1 && userResponse.charAt(0) == 'y') { 
       System.out.println("Great! Let's get started."); 
       break; 
      } 
      else if(userResponse.length() == 1 && userResponse.charAt(0) == 'n') { 
       System.out.println("Come back next time " + "" + "."); 
       System.exit(0); 
      } 
      else { 
       System.out.println("Invalid response."); 
      } 
     } 
    } 

} 

и дает мне желаемый результат

y 
Great! Let's get started. 

Я обычно делал все это время, создавая два ОБЪЕКТА сканер класс один, чтобы получить входную строку и другие, чтобы получить другие типы данных Ввода (Too быть откровенным, даже я не мог понять, почему мне нужно было создать два объекта для получения типов строк и других данных в java без каких-либо ошибок. Если кто-нибудь знает, пожалуйста, дайте мне знать)

+0

использовать следующий() и не следующийLine() – triForce420