gpt4 book ai didi

java - 基本 Java 解码器程序未传递正确的值?

转载 作者:行者123 更新时间:2023-12-01 07:58:47 27 4
gpt4 key购买 nike

我有一个程序,应该读取一系列字符串,从它们的 ascii 值中减去数字键,然后打印出解码后的单词。我的逻辑某个地方有问题。有什么想法吗?

import java.util.*;
import java.io.*;
public class MsgDecoder
{
public static void main(String[] args)
throws Exception
{
Scanner input1 = new Scanner(new File("data5b.txt"));
String word, temp, newMsg = "";
word = input1.next();
while(input1.hasNext())
{
temp = decoder(input1, word);
newMsg = newMsg + " " + temp;
word = input1.next();
}
System.out.println(newMsg);
}

static String decoder(Scanner in, String w)
throws Exception
{
String temp = "";
char c;
int key;
Scanner altInput = new Scanner(new File("data5a.txt"));
key = altInput.nextInt();
for(int i = 0; i < w.length(); i++)
{
c = w.charAt(i);
c = Character.toLowerCase(c);
if(c > 96 && c < 123)
{
c = (char)(c - key);
}
temp = temp + "" + Character.toString(c);
}
return temp;
}
}

这是两个数据文件

data5a.txt
9

data5b.txt
Xwuh cqn vnmrxlan jan jufjhb jc cqnra knbc
Cqn zdrlt kaxfw oxg sdvynm xena cqn ujih mxp
Anjurch rb cqn vdamna xo j knjdcrodu cqnxah kh j pjwp xo dpuh ojlcb
Fqx hxd pxwwj cx ljuu, pqxbckdbcnab
Cx naa rb qdvjw, kdc cx anjuuh oxdu cqrwpb dy anzdranb j lxvydcna
Cx kn xa Wxc cx kn cqjc rb cqn zdnbcrxw
Adunb jan vjmn oxa cqn pdrmjwln xo frbn vnw jwm cqn xknmrnwln xo oxxub
Hxd ljw wnena dwmnanbcrvjcn cqn bcdyrmrch xo cqn pnwnaju ydkurl
Cqxbn fqx frbq cx jyynja frbn jvxwp oxxub, jvxwp cqn frbn bnnv oxxurbq
stop

最佳答案

在输入的第一行,我得到了这个输出:

only the mediocre are always at their best

在你之后

c = (char)(c - key);

您需要检查它是否仍在 97 到 122 的范围内所以我添加了一个 if then 语句

if(!(c > 96)){
c = (char) (c + 26) ;
}

所以你的整个代码循环现在看起来像这样

for(int i = 0; i < w.length(); i++){
c = w.charAt(i);
c = Character.toLowerCase(c);
if(c > 96 && c < 123){
c = (char)(c - key);
if(!(c > 96)){
c = (char) (c + 26) ;
}
}
temp = temp + "" + Character.toString(c);
}

关于java - 基本 Java 解码器程序未传递正确的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27042715/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com