Объект, созданный конструктором в следующем коде, может вызываться несколько раз. Разве я написал код плохо, делая таким образом, я надеюсь, что это написано в соответствующих конвенцияхНеправильно ли этот код вызывать один и тот же конструктор один раз
import java.util.Scanner;
/**
* this class uses the scanner to take input from the keyboard
* test if the input is a variable of type double if it is store in a
* variable called numOne then take next input test again for type double
* store in variable numTwo, then add the two variables together in the form
* of variable answer and return to the screen. The user then is asked for
* continuation as Y/N then appropriate action is taken
*/
public class Calc {
/**
* this constructer does not throw InputMismatchException
*/
public Calc() {
Scanner in = new Scanner(System.in); // create scanner object
System.out.println("please enter 1st "
+ "number then press enter"
+ "\nthen enter 2nd number then "
+ "press enter again");
/*test for a double returns true */
boolean myBool = in.hasNextDouble();
/*the actual test for a double*/
if(myBool == false) {
System.out.println("wrong format");
/**
* call constructer and instantiate as new object
* by creating a new object i hope to have overwriten
* the original object stored in memory there by getting
* around the problem of hasNextDouble not allowing the
* scanner to advance
*/
Calc c = new Calc();
} else { // 1st else
double numOne = in.nextDouble(); // keyboard input
/*test for a double returns true */
boolean myBool2 = in.hasNextDouble();
/*the actual test for a double*/
if(myBool2 == false) {
System.out.println("wrong format start again");
/**
* call constructer and instantiate as new object
* there by removing need for InputMismatchException
*/
Calc c = new Calc();
} else { // 2nd else
double numTwo = in.nextDouble(); // keyboard input
double answer = numOne + numTwo; // the maths
for(int i = 0; i<35; i++) { // print pattern
System.out.print("*");
}
System.out.println("\n**** "
+ "Your 1st number is "
+ numOne + " ****");
System.out.println("**** " // print operator
+ " " + "+"
+ " ****");
System.out.println("**** "
+ "Your 2nd number is "
+ numTwo + " ****");
System.out.println("**** " // print line
+ " ______ ****");
System.out.println("**** "
+ "The answer is "
+ answer + " ****");
for(int i = 0; i<35; i++) { //print pattern
System.out.print("*");
}
System.out.println("\nDo you have "
+ "more calculations Y or N");
String reply = in.next(); //keyboard input
if(reply.equalsIgnoreCase("Y")) {
Calc c = new Calc();
} else {
System.out.println("OK bye then");
in.close(); //close scanner
} //end else
} // end 1st else
} // end 2nd else
} // end constructor
public static void main(String[] args) {
Calc c = new Calc(); // call constructor
} // end main
} // end class
// just in case i do something wrong thanks in anticipation Simon.
Приложите больше усилий для форматирования кода. На данный момент это повсюду ... затем приложите еще несколько усилий, чтобы задать вопрос. Вы включили * много * кода, но только сообщали в общих чертах о «объекте, который создается конструктором» - какой объект? Какой конструктор? –
Кажется, это довольно ужасная идея. Я не знаю, что это технически «неправильно», но я думаю, что многие люди назвали бы это неправильным в производственном коде. – markspace
Если мы игнорируем бесконечный цикл, возникает вопрос: почему вся программа находится внутри конструктора? WTF. Конструктор должен использоваться для создания объекта, а не для выполнения программы. –