我正在完成作业并遇到了一些有趣的事情。我试图让用户输入一个句子,例如“计算机编程很有趣!”然后让它使用我的自定义转换使用ASCII将其转换为数字。我注意到它只会转换用户给出的句子中的第一个单词。解码时,它也只解码第一个字。以下是我的工作:
import java.util.Scanner;
public class Project7{
public static String decode(String finalDecode){
Scanner input = new Scanner(System.in);
System.out.println("How many characters long is your encoded message?");
int characters = input.nextInt();
System.out.println("Enter your encoded message on a single line:");
String decodeMessage = "";
int ascii = input.nextInt();
char ch = (char)ascii;
decodeMessage = decodeMessage + Character.toString(ch);
for(int i = 1; i < characters;i++){
int val = input.nextInt();
ch = (char)(ascii + val);
decodeMessage = decodeMessage + Character.toString(ch);
ascii = ascii+val;
}
System.out.print("Your decoded message is: " + decodeMessage);
return finalDecode;
}
public static int encode(int[] encodeArray){
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence to encode:");
String encode = input.next().toUpperCase();
encodeArray = new int[encode.length()];
int ascii = encode.charAt(0);
encodeArray[0] = ascii;
System.out.println("Encoded sentence is:");
System.out.print(ascii + " ");
for (int i = 1; i < encode.length(); i++) {
ascii = encode.charAt(i - 1);
encodeArray[i] = encode.charAt(i) - ascii;
System.out.print(encode.charAt(i) - ascii + " ");
}
System.out.println();
return encodeArray.length;
}
public static void main(String[] args){
String finalDecode = " ";
int choice = 0;
Scanner input = new Scanner(System.in);
do{
System.out.println("Enter 1 to encode, 2 to decode, 0 to quit:");
choice = input.nextInt();
if(choice == 1){
int[] array = null;
encode(array);
}else if(choice == 2){
String decode = "";
decode(decode);
System.out.println(finalDecode);
}else{
System.out.println("Goodbye.");
break;
}
}while(true);
}
}
答案 0 :(得分:1)
检查编码方法的第三行。
String encode = input.next().toUpperCase();
Scanner.next()只占一个字。将其更改为
String encode = input.nextLine().toUpperCase();
将读取整行。并且你的程序有效。
这是因为Scanner.next()用于使用分隔符来迭代字符串的一部分。默认分隔符是空格“” 看这个例子:
Scanner s = new Scanner("Computer Programming is fun!");
while(s.hasNext())
System.out.println(s.next());
它以新的一行打印句子的每个单词。
现在,您可以将Newline设置为分隔符并保留next(),而不是在编码方法中使用nextLine()。
Scanner input = new Scanner(System.in);
input.useDelimiter("\n");