2017-02-09 2 views
-2

Я пытаюсь создать программу Java, где он запрашивает у пользователя диаметр и высоту цилиндра, где он принимает только входное значение как положительное целое число менее 2,147,483,648, а затем вычисляет объем и площадь поверхности с этого входа. Моя проблема заключается в попытке подтвердить ввод пользователя, запустив сообщение об ошибке («Введите целочисленное значение (менее 2,147,483,648) в виде десятичного числа:») ​​ , если пользователь вводит слово или неверный номер, а затем позволяет пользователю вводить новый действительный ответ.Как правильно добавить закрытый класс в открытый класс в редакторе Eclipse Neon?

Я попытался сделать частный класс, чтобы проверить, был ли введен вход пользователя после программы запрашивают ввод пользователя, используя те же определенные целые числа (диаметр, высота еще не закончена ...). Это также до того, как будут выполнены математические вычисления для определения объема и площади поверхности. Моя проблема заключается в том, что мои скобки отображаются как ошибки редактора Eclipse, когда я пытаюсь закрыть публичный класс после формул volume/SA. Извините за длинный код. Заранее благодарю за любую помощь, очень ценю.

import java.util.Scanner; 

    public class ContainerCalculator 
    { 
     public static void main(String[] args) 
     { 
      Scanner scnr = new Scanner(System.in); 
      int height = 0; 
      int diameter = 0; 
      double surfaceArea = 0.0; 
      double volume = 0.0; 
      double radius = 0.0; 
      System.out.println("Welcome to the Container Calculator!"); 
      System.out.println("===================================="); 

      //User prompts to get the diameter and height of the cylinder. 

      System.out.println("Enter the diameter of a cylinder (in centimeters): "); 
      diameter = scnr.nextInt(); 
      System.out.println(""); 

      System.out.println("Enter the height of a cylinder (in centimeters): "); 
      height = scnr.nextInt(); 
      System.out.println(""); 

     } 


     private static int inputChecker(Scanner scnr) { 
      int i = 0; 
      int diameter = -1; 
      int height = -1; 
      while (i==0){ 
       while (!scnr.hasNextInt()) { 
        System.out.println("Please enter an integer value (less than 2,147,483,648) as decimal: "); 
        scnr.nextLine(); 
       } 

       while (scnr.hasNextInt()){ 
        diameter = scnr.nextInt(); 
        // check to see if it is negative or past a 32-bit range (within range) 
        if ((diameter >= 0) && (diameter < 2147483647)) { 
         i++; 
         return diameter; 
        } 
        else { 
         System.out.println("Please enter an integer value (less than 2,147,483,648) as decimal digits: "); 
         scnr.nextLine(); 
        } 
       } 

      } 
      return -1; 
     } 




    //VOLUME CALCULATIONS: 
     radius = diameter/2.0; 
     volume = Math.PI * Math.pow(radius, 2.0) * height; 

     System.out.println("A can with a diameter of " + diameter + 
       " and a height of " + height + " has "); 
     System.out.print("\ta volume of "); 
     System.out.printf("%.2f", volume); 
     System.out.println(","); 

     //SURFACE AREA CALCULATIONS: 
     surfaceArea = (2.0 * Math.PI * radius * height) + (2.0 * Math.PI * Math.pow(radius, 2.0)); 

     System.out.print("\tand a surface area of "); 
     System.out.printf("%.2f", surfaceArea); 
     System.out.print("."); 
     System.out.println(""); 


     System.out.println("============================================="); 
     System.out.println("Thank you for using the Container Calculator."); 
} 
+0

Возможный дубликат [? Почему я не могу сделать задание за пределами метода] (http://stackoverflow.com/questions/12062481/why-cant- i-do-assign-outside-a-method) – azurefrog

+0

Весь ваш код должен быть в методах, код, начинающийся с '// VOLUME CALCULATIONS:' не находится в методе. –

ответ

1

Чтение пользовательского ввода:

while (true) { 

// read line, e.g. String line = reader.readline(); 
// try to parse line as int, e.g. Integer.valueOf(line); if this does not throw an exception, break; 
// catch NumberformatException, print error, next try 

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