#java #exception
#java #исключение
Вопрос:
Что не так с этим кодом:
DebugTwelve4.java: 25: ошибка: не удается найти выбрасывание символа (новое исключение FixDebugEmployeeIDException(«Слишком большое число» emps [x])); ^ символ: класс FixDebugEmployeeIDException расположение: класс DebugTwelve4 DebugTwelve4.java:36: ошибка: не удается найти перехват символа (ошибка FixDebugEmployeeIDException) ^ символ: класс FixDebugEmployeeIDException расположение: класс DebugTwelve4 2 ошибки Ошибка: не удалось найти или загрузить основной класс DebugTwelve4
DebugEmployeeIDException.java:
public class DebugEmployeeIDException extends Exception
{
public DebugEmployeeIDException()
{
super("Debug employee exception");
}
}
-----------------------------------------------------------
DebugTwelve4.java:
// An employee ID can't be more than 999
// Keep executing until user enters four valid employee IDs
// This program throws a FixDebugEmployeeIDException
import java.util.*;
public class DebugTwelve4
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String inStr, outString = "";
final int MAX = 999;
int[] emps = new int[4];
int x;
try
{
for(x = 0; x < emps.length; x)
{
System.out.println("Enter employee ID number");
inStr = input.next();
throw(new NumberFormatException("Number format exception"));
{
emps[x] = Integer.parseInt(inStr);
if(emps[x] > MAX)
{
throw(new FixDebugEmployeeIDException("Number too high " emps[x]));
}
}
}
}
catch(NumberFormatException error)
{
--x;
System.out.println(inStr "nNonnumeric ID");
}
catch(FixDebugEmployeeIDException error)
{
--x;
System.out.println("FixDebugEmployeeIDException");
}
for(x = 0; x < emps.length; x);
{
outString = outString emps[x] " ";
}
System.out.println("Four valid IDS are: " outString);
}
}
Комментарии:
1. попробуйте создать новое исключение FixDebugEmployeeIDException («Слишком большое число» emps [x]);
2. Это не сработало.
3. почему вы вызываете исключение NumberFormatException?
Ответ №1:
Поскольку вы пишете все свои коды одним методом (основным методом), на самом деле нет необходимости создавать какие-либо исключения.
Как правило, вы создаете исключение, когда вы связываете вызовы методов и не хотите обрабатывать ошибку там, а затем -> вы создаете ее и передаете обратно вызывающему для обработки вызывающим.
В контексте вашего вопроса вы можете просто выполнить простую проверку if / else в цикле, чтобы убедиться, что ввод никогда не превышает 999.
int[] employeeIds = new int[4]
final int _MAX_ = 999;
for (int i = 0 ; i < employeeIds.length; i ) {
int input = sc.nextInt();
if (input > _MAX_) {
System.out.println("Invalid ID, please try again!");
i--; // when invalid input, this ensures that the index stays the same
continue;
} else {
employeeIds[i] = input;
}
}
// loop through employeeIds and print your output
Ответ №2:
Ниже работает для меня.
public class DebugEmployeeIDException extends Exception
{
public DebugEmployeeIDException()
{
super("Debug employee exception");
}
public DebugEmployeeIDException(String message) {
super(message);
}
}
import java.util.*;
public class DebugTwelve4
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String inStr="", outString = "";
final int MAX = 999;
int[] emps = new int[4];
int x=0;
try
{
for(x = 0; x < emps.length; x)
{
System.out.println("Enter employee ID number");
inStr = input.next();
emps[x] = Integer.parseInt(inStr);
if(emps[x] > MAX)
{
throw new DebugEmployeeIDException("Number too high " emps[x]);
}
}
}
catch(NumberFormatException error)
{
--x;
System.out.println(inStr "nNonnumeric ID");
}
catch(DebugEmployeeIDException error)
{
--x;
System.out.println("FixDebugEmployeeIDException");
}
for(x = 0; x < emps.length;x )
{
outString = outString emps[x] " ";
}
System.out.println("Four valid IDS are: " outString);
}
}