您好我正在尝试使用caesar cipher在java中对txt文件进行编码。我自己决定转换并且我已经编写了下面的代码但是我得到了:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
有人可以帮我解决吗?谢谢!
public class zevenedesim {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("words.txt"));
PrintStream output = new PrintStream(new File("words.txt"));
String teksti = input.nextLine();
zevenedesim(teksti, output);
}
public static void zevenedesim(String text, PrintStream output) {
int i = 0;
String s;
Scanner data = new Scanner(text);
if (data.hasNext()) {
s = data.next();
if (s.charAt(i) >= 97 && s.charAt(i) <= 120) {
int x = s.charAt(i) - 97;
x = (x + 2) % 26;
if (x < 0)
x += 26;
// = (char) (x + 32);
}
output.print(" " + data.next());
}
}
}
答案 0 :(得分:0)
您在输入的同一文件上创建输出PrintWriter
。正如the documentation所述,在现有文件上初始化Scanner input = new Scanner(new File("words.txt"));
PrintStream output = new PrintStream(new File("encoded_words.txt"));
将删除其内容:
如果文件存在,那么它将被截断为零大小。
只需使用不同的文件进行输入和输出,你应该没问题:
def list_consequences(request, proponsal_id):
try:
consequences: [Consequence] = Consequence.objects.filter(of_proponsal=proponsal_id)
user_likes =request.user.likes_consequences.get_queryset()
union = consequences | user_likes
for consequence in union:
aux =consequences.get(pk=consequence.pk)
aux.isLiked=True
pros: Consequence = consequences.filter(efecto=Consecuencia.PRO)
against: Consequence = consequences.filter(efecto=Consecuencia.AGAINST)
template = loader.get_template('participation/consequences.html')
context = {
'pros': pros,
'against': against,
'is_user_authenticated': str(request.user.is_authenticated).lower(),
}
return HttpResponse(template.render(context, request))
except Consequence.DoesNotExist:
raise Http404("The consequence with id doesn't exist")
答案 1 :(得分:0)
问题是双重的。首先,打开同一个文件进行同时读写。当您打开文件进行写入时,文件将被清除,因此当您开始阅读时,扫描程序会抛出NoSuchElementException
,因为那里没有任何内容。要解决该问题,请将输出保存到其他文件中。
其次,您的读/写逻辑都是错误的。你用data.next()
读了一个单词,通过Caesar密码运行每个字符,但不将结果存储在任何地方,然后用output.print(" " + data.next());
读取另一个单词,并将第二个单词写入输出完全un-编码,完全丢弃第一个单词。这就是为什么你正在阅读&#34; Hello Java&#34;并写作#34;爪哇&#34;没有编码。我没有试图解决这个问题,而是重写了整个事情,逐行而不是逐字逐句。
以下是我将如何实施该程序,并修复了两个错误。
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class zevenedesim {
public static void main(String[] args) throws IOException {
int shift = 2;
try (Scanner input = new Scanner(new File("words.txt"));
PrintStream output = new PrintStream(new File("encoded_words.txt"))) {
while (input.hasNextLine()) {
output.println(caesar(input.nextLine(), shift));
}
}
}
public static String caesar(String text, int shift) {
shift %= 26;
if (shift == 0) return text;
StringBuilder sb = new StringBuilder(text.length());
for (int i = 0; i < text.length(); i++) {
int c = text.charAt(i);
if (c >= 'A' && c <= 'Z') {
c += shift;
if (c > 'Z') c -= 26;
} else if (c >= 'a' && c <= 'z') {
c += shift;
if (c > 'z') c -= 26;
}
sb.append((char) c);
}
return sb.toString();
}
}