尝试输出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 回答
您不需要循环来完成您要完成的任务 . 根据您的代码,看起来您要做的是获取一个应该介于1000和9999之间的数字,并在数字有效时加密并输出每个数字,如果无效则退出程序 .
首先,您只需要获得单个数字,而不是单独获取每个数字 . 然后检查它是否在1000和9999之间 . 这个检查可以在一个if语句中完成,这样你就不必重复代码告诉用户数字是坏的 . 如果数字没问题,那么你可以把它分成四位数并加密每一位数 .
如果用户在此处输入四位数字:
扫描仪将使用整数作为输入 . 要解决这个问题,你可以要求4个数字用空格分隔,得到
S.nextInt()
四次或者像在这里一样打破输入int:除了首先将输入分配给变量,然后使用以下内容获取每个数字:
然后像以前一样将每个数字分配给数组 .
另外,如上所述,您的数组长度为4.实现目标的一种方法是让用户输入一个四位数字,然后使用if / if else确定整个int是否> 1000 || <9999,然后将数字分解为个位数 .
顺便说一句,你有一个拼写单词加密 .