尝试输出if else if,else循环。使用数组和扫描仪。我究竟做错了什么?

时间:2016-10-06 19:45:58

标签: java arrays if-statement

尝试输出if else if,else循环。使用数组和扫描程序,为作业创建一个非常基本的加密程序。使用扫描仪我可以输入整数,但循环不会执行。我究竟做错了什么?

 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;
}

     }
 }
}

2 个答案:

答案 0 :(得分:0)

你不需要循环来完成你想要完成的任务。根据您的代码,看起来您要做的是获取一个应该介于1000和9999之间的数字,如果数字有效则加密并输出每个数字,如果无效,则退出程序。

首先,您只需要获取单个数字,而不是单独获取每个数字。然后检查它是否在1000和9999之间。这个检查可以在一个if语句中完成,这样你就不必重复代码告诉用户数字是坏的。如果数字没问题,那么你可以把它分成四位数并加密每一位数。

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);
}

答案 1 :(得分:0)

如果用户在此处输入四位数字:

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

扫描仪将使用整数作为输入。要解决这个问题,你可以要求用空格分隔4个数字并获得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 = S.nextInt();
int a = i / 1000;  
int b = (i / 100) % 10; 
int c = (i / 10) % 10; 
int d = i % 10;

然后像以前一样将每个数字分配给数组。

此外,如上所述,您的数组长度为4.实现目标的一种方法是让用户输入一个四位数字,然后使用if / if else确定整个int是否为&gt; 1000 || &LT; 9999,然后将数字分解为个位数。

顺便说一句,你有一个拼写错误的单词加密。