我正在学习Java,我们有一个项目可以制作一个程序,将文本转换为ASCII,然后再转换为ASCII。
到目前为止,我的主要方法是
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char decisionOne;
System.out.println("Are we making a new message or decrypting an old one?");
decisionOne = s.nextLine().charAt(0);
switch(decisionOne) {
case 'd':
decrypt();
System.exit(0);
break;
case 'D':
decrypt();
System.exit(0);
break;
case 'E':
encrypt();
System.exit(0);
break;
case 'e':
encrypt();
System.exit(0);
break;
}
while (!(decisionOne == 'd') && !(decisionOne == 'D') && !(decisionOne == 'e') && !(decisionOne == 'E')) {
System.out.println("Hey! Choose one of them.");
decisionOne = s.nextLine().charAt(0);
switch(decisionOne) {
case 'd':
decrypt();
System.exit(0);
break;
case 'D':
decrypt();
System.exit(0);
break;
case 'E':
encrypt();
System.exit(0);
break;
case 'e':
encrypt();
System.exit(0);
break;
}
}
}
我加密成ASCII的方法是
Scanner s = new Scanner(System.in);
System.out.println("What is your message?");
String message = s.nextLine();
char m;
int length = message.length();
int tracker = 0;
int ascii;
while (length >= 0 ) {
m = message.charAt(tracker);
length--;
ascii = (int)m;
System.out.print(ascii + " ");
tracker ++;
}
}
我环顾了其他问题,但似乎没有一个人回答这里发生的事情。当我跑步时,我得到正确的输出,所以如果我输入
11
我会得到
49 49线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:2
我该怎么做才能解决此问题?
将加密方法中的代码从更改while(length >= 0)
为while(length - 1 >= 0)
。使用扫描仪对象后也要关闭它,因为它会导致内存泄漏。
length()方法返回字符串的长度,例如String message = "Hello"; length = message.length();
length等于5。但是在while循环中使用它时,必须使用message.length()-1,因为在Java中索引从0开始而不是从0开始在1。
我重构了您的encypt方法和main方法,并且我觉得不需要使用switch语句。用if else语句替换它们以减少冗余代码。
如果您觉得此解决方案有用,请对该解决方案表示感谢。
public static void encrypt() {
Scanner s = new Scanner(System.in);
System.out.println("What is your message?");
String message = s.nextLine();
char m;
int length = message.length();
int tracker = 0;
int ascii;
while (length - 1 >= 0 ) {
m = message.charAt(tracker);
length--;
ascii = (int)m;
System.out.print(ascii + " ");
tracker++;
}
s.close();
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char decisionOne;
System.out.println("Are we making a new message [e (or) E] or decrypting an old one [d (or) D] ?");
decisionOne = s.nextLine().charAt(0);
if (decisionOne == 'd' || decisionOne == 'D') {
decrypt();
System.exit(0);
}
else if (decisionOne == 'e' || decisionOne == 'E') {
encrypt();
System.exit(0);
}
while (!(decisionOne == 'd') && !(decisionOne == 'D') && !(decisionOne == 'e') && !(decisionOne == 'E')) {
System.out.println("Hey! Choose one of them.");
decisionOne = s.nextLine().charAt(0);
if (decisionOne == 'd' || decisionOne == 'D') {
decrypt();
System.exit(0);
}
else if (decisionOne == 'e' || decisionOne == 'E') {
encrypt();
System.exit(0);
}
}
s.close();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句