Zito. Zito. - 1 month ago 6
Java Question

Trying to output an if else if, else loop. using arrays and Scanners. What am i doing wrong?

Trying to output an if else if, else loop. using arrays and Scanners, to create a very basic encryption program for an assignment. Using the scanner i can input integers, however the loop won't execute. What am i doing wrong?

import java.util.Scanner;

public class Question1A2 {

public static void main (String [] args){

Scanner S = new Scanner(System.in);

System.out.println("\t-------------------------");
System.out.println ("\tIO's 4-digit Encrypter");
System.out.println("\t-------------------------");


System.out.print("Please enter the four digit number you would like to encyrpt: ");

int[] arr = {S.nextInt(),S.nextInt(),S.nextInt(),S.nextInt()};

int a = arr[0] %10 +7;
int b = arr[1] %10 +7;
int c = arr[2]%10 +7;
int d = arr [3] %10 +7;

int i = arr.length;

for(;;){
if (arr.length > 9999) {
System.out.println("Sorry, but that is not a four digit number. Program will terminate.");
System.out.println("Thank you for using Zito's 4-digit Encrypter program.");
break;
}

else if (arr.length < 1000) {
System.out.println("Sorry, but that is not a four digit number. Program will terminate.");
System.out.println("Thank you for using Zito's 4-digit Encrypter program.");
break;
}

else {
System.out.print("The encyrpted version of your input is ");

System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print(d);

break;
}

}
}
}

Answer

You don't need a loop for what you are trying to accomplish. Based on your code, it looks like what you are trying to do is get a number that should be between 1000 and 9999, and encrypt and output each digit if the number is valid or exit the program if it is not valid.

To start, you only need to get the single number, not get each digit individually. Then check if it is between 1000 and 9999. This check can be done in one if statement so that you don't have to repeat the code telling the user the number is bad. If the number is okay, then you can break it up into the four digits and encrypt each one.

int theNumber = S.nextInt();
if (theNumber < 1000 || theNumber > 9999) {
    System.out.println("Sorry, but that is not a four digit number. Program will terminate.");
    System.out.println("Thank you for using Zito's 4-digit Encrypter program.");
}
else {
    // I'm leaving this up to you to figure out how to get each digit.
    // There are several ways to do it, and it's out of scope for this question anyway.
    int digit1 = ...
    int digit2 = ...
    int digit3 = ...
    int digit4 = ...

    int a = digit1 % 10 + 7; 
    int b = digit2 % 10 + 7;
    int c = digit3 % 10 + 7;
    int d = digit4 % 10 + 7;

    System.out.print("The encrypted version of your input is ");

    System.out.print(a);
    System.out.print(b);
    System.out.print(c);
    System.out.print(d);
}
Comments