public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
}
}
Вы должны реорганизовать, чтобы отделить петлю от поиска/не находить мяч (или нет) и делать все, что вам нужно делать с мячом (или ошибка, если не найдена) вне цикла. Это помогает с удобочитаемостью, потому что больше ваших строк меньше с отступом, и это помогает сообщить ваше намерение, потому что большая часть вашего кода в цикле будет только однажды выполнена.
int ballIndex = -1;
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
ballIndex = nameBallArray[i];
break;
}
}
if (ballIndex >= 0) {
// found - do everything using ballIndex
} else {
// not found - display error
}
Вы можете создать логическое значение и установить его в true в вашем операторе if, что означает его обнаружение. Вы можете проверить цикл boolean after, чтобы убедиться, что это true или false, а затем отобразить сообщение об ошибке, если true.
Пример:
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
boolean found = false; //boolean for if it found or not
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
found = true; //set boolean if found
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
break; //break out of loop if item found
}
}
//check if boolean is false then print error message
if (!found)
{
System.out.println("There was a problem finding your item.");
}
Я также добавил разрыв в конце инструкции if, чтобы выйти из цикла, если элемент был найден (нет смысла продолжать, если элемент уже найден).
Попробуй это:
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
return;
}
}
System.out.println("ball not found");
}
Установите переменную флага в 0 перед циклом. Внутри, если установить его 1. После проверки цикла, если он все еще равен нулю. затем напечатайте соответствующее сообщение, которое не найдено.
Boolean flag = false; // before loop
flag = true; //inside if
// After loop
if(!flag)
System.out.println("Not Found");