[英]Trying to output an if else if, else loop. using arrays and Scanners. What am i doing wrong?
尝试输出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;
}
}
}
}
您不需要为要完成的任务做循环。 根据您的代码,您似乎想要执行的操作是获取一个介于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);
}
如果用户在此处输入一个四位数的数字:
int[] arr = {S.nextInt(),S.nextInt(),S.nextInt(),S.nextInt()};
扫描仪将使用整数作为输入。 要解决此问题,您可以要求输入4个数字,并用空格分隔,并四次获取S.nextInt()
或像下面那样将输入int分解:
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是否大于1000 ||。 <9999,然后将数字分解为个位数。
顺便说一句,您有一个错字,带有“加密”一词。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.