Java Box программа с несколькими методами и конструкторами - PullRequest
0 голосов
/ 19 октября 2018

Я новичок в программировании и у меня проблемы с использованием конструкторов, в частности.Я должен написать программу для одной из моих лабораторий, которая должна состоять только из:

  1. Три переменных экземпляра - длина, ширина и высота (каждая из типов double)
  2. Переменные одного экземпляра - вход (тип Scanner), инициализированный в System.in
  3. Конструктор по умолчанию (без аргументов) - инициализировать все три переменные экземпляра в 1
  4. Исходный конструктор - инициализировать все трипеременные экземпляра
  5. Конструктор копирования - копирование Box * Методы ввода
  6. inputWidth, inputLength и inputHeight, которые устанавливают переменные экземпляра на основе пользовательского ввода, не имеют параметров и не возвращают значение.
  7. метод displayDimensions, который отображает длину X Width X height (разделенную «X») и не возвращает значение.
  8. метод calcVolume, который не имеет параметров и вычисляет объем поля

Нам также было дано приложение BoxTest, в котором выходные данные должны точно соответствовать следующему:

  • Размеры по умолчанию: 1,0 X 1,0 X 1,0 с объемом 1,0 * 1026.*
  • Начальные размеры 8,5 X 11,0 X 1,0 с объемом 93,5
  • Скопированные размеры 8,5 X 11,0 X 1,0 ш.том 93,5
  • Обновить размеры
  • Введите длину: 1
  • Введите ширину: 2
  • Введите высоту: 3
  • Обновлены размеры1,0 X 2,0 X 3,0 с объемом 6,0

Вот мой код:

import java.util.Scanner;

public class Box {
public static void main(String args[]) {
    double length, width, height;

    Scanner input=new Scanner(System.in);

new Box() {     //  

Box defaultBox=new Box();
    double length = 1.0;
    double width = 1.0;
    double height = 1.0;
    System.out.print("Default dimensions are " + length + " X " + width + " X " + height);
    defaultBox.displayDimensions();
    System.out.println(" with volume of "+defaultBox.calcVolume());

Box initialBox=new Box(length, width, height);
    length = 8.5;
    width = 11.0;
    height = 1.0;
    System.out.print("Initial dimensions are " + length + " X " + width + " X " + height);
    initialBox.displayDimensions();
    System.out.println(" with volume of "+initialBox.calcVolume());

Box copyBox=new Box(initialBox);
    System.out.print("Copied dimensions are " + length + " X " + width + " X " + height);
    copyBox.displayDimensions();
    System.out.println(" with volume of "+copyBox.calcVolume());

    System.out.println("\nUpdate dimensions");
    initialBox.inputLength();
    initialBox.inputWidth();
    initialBox.inputHeight();
    System.out.print("Updated dimensions are ");
    initialBox.displayDimensions();
    System.out.println(" with volume of "+initialBox.calcVolume());
}
double inputLength() {
    Scanner input;
    double length = input.nextDouble(); 
    }
double inputWidth() {
    Scanner input;
    double width = input.nextDouble();
    }
double inputHeight() {
    Scanner input;
    double height = input.nextDouble();
    }

double displayDimensions(double length, double width, double height) {   
    Scanner input;
    }

double calcVolume() {
}

}

Чего мне не хватает?Моя программа не компилируется и выдает сообщение об ошибке

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    Syntax error, insert "Identifier (" to complete MethodHeaderName
    Syntax error, insert ")" to complete MethodDeclaration
    Syntax error, insert ";" to complete MethodDeclaration
    Syntax error, insert "}" to complete ClassBody
at Box.main(Box.java:18)

1 Ответ

0 голосов
/ 19 октября 2018

Как я сказал в комментариях, вы поместили все в main.Не делай этого.Таким образом, ваш класс Box в основном пуст, и вы в настоящее время почти создаете анонимный подкласс в main.Ваши указания не упоминают main, но довольно просты.Вы должны были написать что-то вроде

public class Box {
    // Three instance variables – length, width and height (each of type double)
    private double length, width, height;
    // One instance variables – input (type Scanner) initialized to System.in
    private Scanner input = new Scanner(System.in);

    // Default constructor (no-arg) – initialize all three instance variables to 1
    public Box() {
        this.length = this.width = this.height = 1;
    }

    // Initial constructor – initialize all three instance variables
    public Box(double length, double width, double height) {
        this.length = length;
        this.width = width;
        this.height = height;
    }

    // Copy constructor – copy Box
    public Box(Box b) {
        this(b.length, b.width, b.height);
    }

    // inputWidth, inputLength, and inputHeight methods that set the instance
    // variables based on user input have not parameters and do not return a value.
    public void inputWidth() {
        this.width = input.nextDouble();
    }

    public void inputLength() {
        this.length = input.nextDouble();
    }

    public void inputHeight() {
        this.height = input.nextDouble();
    }

    // a displayDimensions method that displays the length X Width X height
    // (separated by “X”) and does not return a value.
    public void displayDimensions() {
        System.out.printf("%.2fX%.2fX%.2f%n", length, width, height);
    }

    // a calcVolume method that has no parameters and calculates the volume of the
    // box
    public double calcVolume() {
        return length * width * height;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...