Методы вызываются множество раз

#java #methods

Вопрос:

У меня есть методы x, y, z, которые вызываются методами balloonsNeeded и roomVolume.

Методы вызываются дважды и, следовательно, выполняются дважды. Мне нужно, чтобы методы xyz запускались только один раз, но мне нужны их переменные дважды. Проблема может быть легко устранена, если я объединю методы, но я должен разделить все упомянутые методы.

я забыл упомянуть, что я пытался использовать массивы (возможно, неправильно), и у меня все еще была та же проблема.

 package com.company; import java.util.Scanner;  class Main {  public static Scanner scanner = new Scanner(System.in);   public static void main(String[] a) {  //X(); \testing  //Y(); \testing  //Z(); \testing  //roomVolume(); \testing  //balloonVolume(); \testing  balloonsNeeded();  System.exit(0);  }    //Finding axis X  public static double X() {  String x;  double xDouble;   //takes the users input  System.out.println("What is the rooms width in cm?");  x = scanner.nextLine();   //insures the user hasnt entered any letters  if (x.matches(".*[a-zA-Z.*]")) {  System.out.println("The value you entered is invalid, please enter a value using only [0-9]");  return X();  } else {  //converts the users input into a double value  xDouble = Double.parseDouble(x);  }   //insures the users input is larger than 0  if (xDouble lt;= 0) {  System.out.println("The value you entered is 0 or smaller, please enter a value larger than 0");  return X();  } else {  //returns the users input.  return xDouble;  }  }    //Finding axis Y  static double Y() {  String y;  double yDouble;   //takes the users input  System.out.println("What is the rooms length in cm?");  y = scanner.nextLine();   //insures the user hasnt entered any letters  if (y.matches(".*[a-zA-Z.*]")) {  System.out.println("The value you entered is invalid, please enter a value using only [0-9]");  return Y();  } else {  //converts the users input into a double value  yDouble = Double.parseDouble(y);  }   //insures the users input is larger than 0  if (yDouble lt;= 0) {  System.out.println("The value you entered is 0 or smaller, please enter a value larger than 0");  return Y();  } else {  //returns the users input.  return yDouble;  }  }   //Finding axis Z  public static double Z() {  String z;  final double zDouble;   //takes the users input  System.out.println("What is the rooms height in cm?");  z = scanner.nextLine();   //insures the user hasnt entered any letters  if (z.matches(".*[a-zA-Z.*]")) {  System.out.println("The value you entered is invalid, please enter a value using only [0-9]");  return Z();  } else {  //converts the users input into a double value  zDouble = Double.parseDouble(z);  }   //insures the users input is larger than 0  if (zDouble lt;= 0) {  System.out.println("The value you entered is 0 or smaller, please enter a value larger than 0");  return Z();  } else {  //returns the users input.  return zDouble;  }  }    //Calculating the rooms volume  public static double roomVolume(){  double rvDouble;  final int million = 1000000;  double rvRounded;   //calls for the X, Y, Z methods to be run in order to obtain the variables  double axisx = X();  double axisy = Y();  double axisz = Z();   //calculates the rooms volume then divides it by 1,000,000 to convert it to m³  rvDouble = (axisx*axisy*axisz)/million;   //rounds the volume to 2 decimal points  rvRounded = (double)Math.round(rvDouble*100)/100;   //returns rooms volume  return rvRounded;  }   //finding the balloons volume  public static double balloonVolume() {  String bv;  double bvDouble;   System.out.println("Whats your balloons volume?");  bv = scanner.nextLine();   //insures the user hasnt entered any letters  if (bv.matches(".*[a-zA-Z.*]")) {  System.out.println("The value you entered is invalid, please enter a value using only [0-9]");  return balloonVolume();  } else {  //converts the users input into a double value  bvDouble = Double.parseDouble(bv);  }   //insures the users input is larger than 0  if (bvDouble lt;= 0) {  System.out.println("The value you entered is 0 or smaller, please enter a value larger than 0");  return balloonVolume();  } else {  //returns balloon volume.  return bvDouble;  }  }    //finding the number of balloons needed to fill a room.  public static int balloonsNeeded(){  int bNeeded;  double bNdouble;   double rVol = roomVolume();  double bVol = balloonVolume();  double ax = X();  double ay = Y();  double az = Z();   //calculates the number of balloons needed by dividing the rooms volume by the balloons volume.  bNdouble = rVol/bVol;  //converts the value from a double to an integer  bNeeded = (int)bNdouble;   //prints out the information to the user.  System.out.println("The dimensions you entered are "   ax   "x"   ay   "x"   az   "cm." );  System.out.println("This means your rooms volume is "   rVol   "m³");  System.out.println("You will need "   bNeeded   " balloons to fill the room.");  return bNeeded;  } }  

Комментарии:

1. Как насчет вызова x,y,z один раз перед вызовом других методов и после передачи значений этим методам.

Ответ №1:

Как и @KunLun, упомянутый в комментариях,

 public static double roomVolume(double axisx, double axisy, double axisz){  double rvDouble;  final int million = 1000000;  double rvRounded;   //calculates the rooms volume then divides it by 1,000,000 to convert it to m³  rvDouble = (axisx*axisy*axisz)/million;   //rounds the volume to 2 decimal points  rvRounded = (double)Math.round(rvDouble*100)/100;   //returns rooms volume  return rvRounded; }  

И тогда вы можете просто вызвать свой метод

 public static int balloonsNeeded(){  int bNeeded;  double bNdouble;   double ax = X();  double ay = Y();  double az = Z();  double rVol = roomVolume(ax, ay, az);  double bVol = balloonVolume();   //calculates the number of balloons needed by dividing the rooms volume by the balloons volume.  bNdouble = rVol/bVol;  //converts the value from a double to an integer  bNeeded = (int)bNdouble;   //prints out the information to the user.  System.out.println("The dimensions you entered are "   ax   "x"   ay   "x"   az   "cm." );  System.out.println("This means your rooms volume is "   rVol   "m³");  System.out.println("You will need "   bNeeded   " balloons to fill the room.");  return bNeeded; }  

Комментарии:

1. хотя предыдущее решение более эффективно, спасибо, что дали мне это решение, это то, что мне было нужно, так как мне нужно было разделить методы X Y Z.

Ответ №2:

Во-первых, у вас много повторяющегося кода. Объедините все это в одну функцию. Затем один раз получите входные данные и при необходимости передайте их в качестве параметров.

 package com.company; import java.util.Scanner;  class Main {  public static Scanner scanner = new Scanner(System.in);   public static void main(String[] a) {  balloonsNeeded();  System.exit(0);  }   public static double getDouble(String prompt) {  while (true) {  //takes the users input  System.out.println(prompt);  String x = scanner.nextLine();  try {  double val = Double.parseDouble(x);  if (val gt; 0) return val;  System.out.println("The value you entered is 0 or smaller, please enter a value larger than 0");  }  catch (NumberFormatException e) {  System.out.println("The value you entered is invalid, please enter a value using only [0-9]");  }  }  }   //Calculating the rooms volume  public static double roomVolume(double axisx, double axisy, double axisz) {  double rvDouble;  final int million = 1000000;  double rvRounded;   //calculates the rooms volume then divides it by 1,000,000 to convert it to m³  rvDouble = (axisx*axisy*axisz)/million;   //rounds the volume to 2 decimal points  rvRounded = (double)Math.round(rvDouble*100)/100;   //returns rooms volume  return rvRounded;  }   //finding the number of balloons needed to fill a room.  public static int balloonsNeeded(){  double ax = getDouble("What is the rooms width in cm?");  double ay = getDouble("What is the rooms length in cm?");  double az = getDouble("What is the rooms height in cm?");   double rVol = roomVolume(ax, ay, az);  double bVol = getDouble("Whats your balloons volume?");   //calculates the number of balloons needed by dividing the rooms volume by the balloons volume.  double bNdouble = rVol/bVol;  //converts the value from a double to an integer  int bNeeded = (int)bNdouble;   //prints out the information to the user.  System.out.println("The dimensions you entered are "   ax   "x"   ay   "x"   az   "cm." );  System.out.println("This means your rooms volume is "   rVol   "m³");  System.out.println("You will need "   bNeeded   " balloons to fill the room.");  return bNeeded;  } }  

Комментарии:

1. большое вам спасибо за вашу помощь