我遇到的问题是用凯撒密码程序包裹字母表。
该程序适用于所有小写字母。完美包裹,能够应用正面和负面的转变。当我尝试输入一个大写字母时,大写字母不会回绕。
这是我的代码:
public static StringBuilder encode(String str, int numShift)
{
numShift = numShift % 26;
//assign each character of the string to a position in the character array
char[] strChars = str.toCharArray();
for (int i = 0; i < strChars.length; i++)
{
//ignore and continue if the character is not within the alphabet
if((strChars[i] < 'a' || strChars[i] > 'z') && (strChars[i]<'A' || strChars[i] > 'Z'))
continue;
//apply the shift to each character
strChars[i] += numShift;
//wrap around if the shift is beyond Z
**if(strChars[i] > 'z')
{
strChars[i] -= 'z';
strChars[i] += ('a' - 1);
}**
}
StringBuilder encodedStr = new StringBuilder();
encodedStr.append(strChars);
return encodedStr;
}
public static void init(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the string that you would like to encode:");
String str = scan.nextLine();
System.out.println("Please enter the number of letters you would like to shift:");
int strShift = scan.nextInt();
scan.close();
StringBuilder result = encode(str, strShift);
System.out.println(result);
}
public static void main(String[] args)
{
init();
}
}
提示非常感谢!当然,我不是要求任何人为我做我的工作,但一些帮助将不胜感激!谢谢! :)
编辑:这是仅包含小写字母的if语句:
if(strChars[i] > 'z')
{
strChars[i] -= 'z';
strChars[i] += ('a' - 1);
}
答案 0 :(得分:0)
让我们为单个字符实现环绕功能。这将由另一种方法使用。当您明智地分离任务和子任务时,您会发现问题变得更容易解决。在这里,我的解决方案基于<nav class="navbar navbar-default navbar-fixed-top" id="barrademenu">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Logo</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li><a href="#home" id="home">HOME</a></li>
<li><a href="#about" id="about">ABOUT US</a></li>
<li><a href="#portfolio" id="portfolio">PORTFOLIO</a></li>
<li><a href="#contact" id="contact">CONTACT US</a></li>
</ul>
</div>
</div>
</nav>
变量表示为数字的事实,我们知道字母的数量,我们可以将该数字用作模数类,以确保代数帮助我们。
char
现在,而不是
private static char wrapChar(char input, int amount) {
//assume for now that we have an upper-case letter
char start = 'A';
//if the assumption is mistaken...
if (('a' <= input) && (input <= 'z')) {
//then, if it is lower-case, then use lower-case
start = 'a';
} else if (!(('A' <= input) && (input <= 'Z'))) {
//target is not letter
return input;
}
//Calculate total offset compared to the first letter of the alphabet
//be it lower or upper
int offset = ((input - start) + amount) % 26;
//If offset happens to be negative, then shift a modulo period of 26
//To get the correct positive offset
if (offset < 26) {
offset += 26;
}
//Add the final offset to start and convert it to char
return ((char)(start + offset));
}
你需要:
//apply the shift to each character
strChars[i] += numShift;
//wrap around if the shift is beyond Z
**if(strChars[i] > 'z')
{
strChars[i] -= 'z';
strChars[i] += ('a' - 1);
}**