【问题描述】
在情报传递过程中,为了防止情报被截获,往往需要对情报用一定的方式加密,简单的加密算法虽然不足以完全避免情报被破译,但仍然能防止情报被轻易的识别。我们给出一种最简的的加密方法,对给定的一个字符串,把其中从a-y,A-Y的字母用其后继字母替代,把z和Z用a和A替代,则可得到一个简单的加密字符串。
【输入形式】
可能有多组测试数据。每组测试数据的第一行是字符串的数目n,其余n行每行一个字符串,每个字符串长度小于80个字符。
【输出形式】
对于每组数据,输出每行字符串的加密字符串。
【样例输入】
1
Hello! How are you!
【样例输出】
Ifmmp! Ipx bsf zpv!
解题方法:将字符串逐个读取,转化每一个字符(字符加一)
String a = " ";
char [] c= a.toCharArray();
特殊处理:z->a;Z->A;
注意:nextInt():在扫描到空白符/回车符时只读取到他前面的数据,但空白符/回车符还在缓冲区,再调用nextLine()时,首先读取到的是nextInt遗留的回车符,并将其在缓冲区清除掉。
所以我们可以在nextInt后面加nextLine或者把nextInt换成nextLIne再转成int型
String str=sc.nextLine();
int n=Integer.parseInt(str);
代码如下:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
while(n>0) {
String str=sc.nextLine();
char []c= str.toCharArray();
for(int i=0;i<str.length();i++) {
if((c[i]>='A'&&c[i]<'Z')||(c[i]>='a'&&c[i]<'z'))
c[i]+=1;
else if(c[i]=='z')
c[i]='a';
else if(c[i]=='Z')
c[i]='A';
}
for(int i=0;i<str.length();i++)
System.out.print(c[i]);
System.out.print("\n");
n--;
}
}
}
import java.util.Scanner;
public class InformationHide
{
public static void main(String[] arg)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
while(n>0)
{
String str=sc.nextLine();
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i);
if(c=='Z')
{
c='A';
}
else if(c=='z')
{
c='a';
}
else if((c>='a'&&c<'z')||(c>='A'&&c<'Z'))
c++;
System.out.print(c);
}
System.out.print('\n');
n--;
}
}
}