Отвечая на предыдущий вопрос, связанный здесь (https://stackoverflow.com/questions/15487706/try-and-catch-block-not-functioning-in-user-defined-method), мой первоначальный ответ на этот вопрос был решен, но у меня была другая проблема, когда дело дошло до цикла, который был позже решен просто используя цикл for. Тем не менее, моя проблема заключается в том, что я не хочу, чтобы пользователю постоянно приходилось перезапускать программу после обработки исключения, вместо этого я хочу, чтобы он зацикливал на пользователя те же самые начальные вопросы. Я попытался разместить инструкции печати после операторов возврата, а также попытался полностью скопировать логический код после попытки улова, однако, понимая, что это не приведет к тому, что пользователь зациклирует неограниченное время на исключение. Кроме того, на боковой ноте да, мой предыдущий вопрос имел хорошие ответы, однако никто не смог ответить на мою более повторяющуюся проблему, поэтому никто не получил галочку к их ответу.Как сделать обработку исключений Loop (Неограниченное количество раз)
import java.io.*;
import java.text.DecimalFormat;
public class Test
{
public static void main(String[] args) throws IOException
{
double x;
x = circlemethods(0.0, 0.0, 0.0, 1.0);
}
public static double circlemethods(double volume, double surfacearea,
double area, double radius) throws IOException
{
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
String numInput;
String reqInput;
String amountStr;
double numInt = 0;
double num = 0;
double answer = 0;
double amount = 0;
double answer2 = 0;
double answer3 = 0;
double answer4 = 0;
for (double i = 0; i < 999; i++)
;
try
{
// for (double i = 0; i < 999; i++);
// while (numInt != 999) {
System.out.println("This program will ask for a given user radius, then proceed to calculate the user input");
System.out.println("The program will use four methods to achieve this, all calling back to the main method");
System.out.println("Press any key to continue");
numInput = myInput.readLine();
System.out.println("First, what would you like to calculate?");
System.out.println("Enter '1' for Circumference, '2' for area, '3' for volume, or '4' for surface area");
reqInput = myInput.readLine();
numInt = Double.parseDouble(reqInput);
System.out.println("Now enter the radius of the required shape(Half of diameter)");
numInput = myInput.readLine();
num = Double.parseDouble(numInput);
DecimalFormat nextAmount = new DecimalFormat("0.00");
amountStr = nextAmount.format(amount);
if (numInt == 1)
{
System.out.println("You chose to calculate circumference, given the radius :" + num);
answer = (3.14) * (2) * (num);
System.out.print("The circumference of that sphere is :");
System.out.println(answer + "cm³");
return answer;
}
else if (numInt == 2)
{
System.out.println("You chose to calculate area, given the radius :" + num);
answer2 = (3.14) * 2;
System.out.print("The area of the circle is :");
System.out.println(answer2 + "cm²");
return answer2;
}
else if (numInt == 3)
{
System.out.println("You chose to calculate volume, given the radius :" + num);
answer3 = 4/3 * (3.14) * (num) * (3) * (3) * (3);
System.out.print("The volume of that sphere is : cm³");
System.out.println(answer3 + "cm³");
return answer3;
}
else
// if (numInt == 4)
{
System.out.println("You chose to calculate surface area, given the radius :" + num);
answer4 = 4 * (3.14) * (num) * (2) * (2);
System.out.print("The Surface area of that sphere is :");
System.out.println(answer4 + "cm²");
return answer4;
}
} catch (Exception e)
{
System.out.println("Please do not enter any string values, next time input enter a number ");
return 0;
// how to loop this untill the user inputs a number????
}
}
}
Вам нужно улучшить форматирование кода, так как его очень трудно прочитать и понять, как он написан. Это особенно важно, когда вы просите других помочь вам с этим кодом. Подумайте о создании метода ввода ввода, наличии цикла while в методе и не возврата из метода, если вход не является допустимым. –