最后一个字符没有正确旋转

last character not rotating correctly

我已经为凯撒密码编写了一个代码,其中第一个输入是不带任何空格的字符串长度,第二个输入是要旋转的字符串,第三个是旋转的密钥。除了字符串的最后一个字符,我的代码工作正常。为此,出现了一些奇怪的字符而不是字母表。请帮忙!!!..我束手无策..只是想不通!下面是代码:-

    import java.io.*;
    import java.util.*;
    public class Solution {
    public static void main(String[] args) {
    int length,rotate,i,x;
    Scanner scan=new Scanner(System.in);
    String s;
    length=scan.nextInt();
    s=scan.next();
    rotate=scan.nextInt();
    char c[]=s.toCharArray();
    for(i=0;i<length;i++) {
    x=c[i];
    if(((x>65)||(x==65))&&((x==90)||(x<90))) {
    x=x+rotate;
    if(x>90)
    x=x-90;
    }
    else if(((x>97)||(x==97))&&((x==122)||(x<122))) {
    x=x+rotate;
    if(x>122)
    x=x-122;
    }
    c[i]=(char)x;
    }
    System.out.println();
    for(i=0;i<length;i++) 
    System.out.print(c[i]);
    }
    }

输入是:-

    11
    middle-Outz
    2

输出应该是:-

    okffng-Qwvb

但我的输出是:-

    okffng-Qwv

请帮忙!!!请...有人告诉我代码中的错误是什么!

如果旋转偏移超过某个阈值,您目前没有任何逻辑来处理字母环绕到字母表开头的情况。您的逻辑应该是将初始移位的剩余部分加上旋转量除以字母表的大小,以添加到基值(即第一个字母)。像这样:

public static void main(String[] args) {
    int length, rotate, i, x;
    Scanner scan = new Scanner(System.in);
    String s;
    // don't input the length of the array, let it tell you what its length is
    //length = Integer.parseInt(scan.nextLine());
    s = scan.nextLine();
    // make sure you really enter a pure integer here, to avoid a crash
    rotate = Integer.parseInt(scan.nextLine());
    char c[] = s.toCharArray();
    for (i=0; i < c.length; i++) {
        x = c[i];
        int base;
        if (x >= 65 && x <= 90) {
            base = 65;
        }
        else if (x >= 97 && x <= 122) {
            base = 97;
        }
        else {
            continue;
        }
        int diff = x - base;
        x = base + (rotate + diff) % 26;
        c[i] = (char)x;
    }
    System.out.println();
    for (i=0; i < c.length; i++) 
        System.out.print(c[i]);
}

请注意,我选择不修改非小写或大写英文字母的字符。如果是其他字符,则不会旋转。

按照下面的 link 进行演示,该演示显示输入 middle-Outz 已正确转换为 okffng-Qwvb

Rextester

更新:

正如您正确指出的那样,您的 Scanner 逻辑也存在一些问题。一种安全模式,使用它始终读取字符串行中的所有内容,然后 parse/format 适当地输入。您收到的输入不匹配异常可能是由于扫描仪使用不当造成的。