I want to implement a Caesar Cipher shift to increase each letter in a string by 3.
我想要实现一个凯撒密码转换,将每一个字母在一个字符串中增加3。
I am receiving this error:
我收到这个错误:
possible loss of precision required char; found int
Here is my code so far:
下面是我的代码:
import java.util.Scanner;
import java.io.*;
public class CaesarCipher
{
public static void main (String [] args) {
char[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'};
char[] message = "onceuponatime".toCharArray();
char[] eMessage = new char[message.length];
char shift = 3;
//encrypting message
for(int i = 0; i <= message.length; ++i)
{
eMessage[i] = (message[i] + shift) % (char) letters.length;
System.out.println(x);
}
}
}
What causes this error? How can I implement a caesar Cipher shift to increase each letter in a string by 3?
导致这个错误的原因是什么?我怎样才能实现一个凯撒密码转换,将每一个字母在一个字符串中增加3?
5 个解决方案
#1
8
Java Shift Caesar Cipher by shift
spaces.
Restrictions:
限制:
- Only works with a positive number in the shift parameter.
- 只在移位参数中使用正数。
- Only works with shift less than 26.
- 只适用于小于26的移动。
- Does a += which will bog the computer down for bodies of text longer than a few thousand characters.
- a +=会使计算机的正文长度超过几千个字符。
- Does a cast number to character, so it will fail with anything but ascii letters.
- 将一个数字转换成字符,因此它将以任何形式失败,而不是ascii字符。
- Only tolerates letters a through z. Cannot handle spaces, numbers, symbols or unicode.
- 只允许字母a到z。不能处理空格、数字、符号或unicode。
- Code violates the DRY (don't repeat yourself) principle by repeating the calculation more than it has to.
- 代码违背了DRY(不要重复自己)的原则,重复计算比它必须要多。
Pseudocode:
伪代码:
- Loop through each character in the string.
- 循环遍历字符串中的每个字符。
- Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26)
- 增加字符的转换,如果它从字母表的末尾掉下来,那么将字母表中的字母的数量从字母表中减去。
- If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
- 如果转换不能使字符从字母表的末尾下降,那么就增加字符的转换。
- Append the character onto a new string. Return the string.
- 将字符追加到一个新字符串中。返回字符串。
Function:
功能:
String cipher(String msg, int shift){
String s = "";
int len = msg.length();
for(int x = 0; x < len; x++){
char c = (char)(msg.charAt(x) + shift);
if (c > 'z')
s += (char)(msg.charAt(x) - (26-shift));
else
s += (char)(msg.charAt(x) + shift);
}
return s;
}
How to invoke it:
如何调用它:
System.out.println(cipher("abc", 3)); //prints def
System.out.println(cipher("xyz", 3)); //prints abc
#2
2
Below code handles upper and lower cases as well and leaves other character as it is.
下面的代码处理上和下的情况,并留下其他字符。
import java.util.Scanner;
public class CaesarCipher
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int length = Integer.parseInt(in.nextLine());
String str = in.nextLine();
int k = Integer.parseInt(in.nextLine());
k = k % 26;
System.out.println(encrypt(str, length, k));
in.close();
}
private static String encrypt(String str, int length, int shift)
{
StringBuilder strBuilder = new StringBuilder();
char c;
for (int i = 0; i < length; i++)
{
c = str.charAt(i);
// if c is letter ONLY then shift them, else directly add it
if (Character.isLetter(c))
{
c = (char) (str.charAt(i) + shift);
// System.out.println(c);
// checking case or range check is important, just if (c > 'z'
// || c > 'Z')
// will not work
if ((Character.isLowerCase(str.charAt(i)) && c > 'z')
|| (Character.isUpperCase(str.charAt(i)) && c > 'Z'))
c = (char) (str.charAt(i) - (26 - shift));
}
strBuilder.append(c);
}
return strBuilder.toString();
}
}
#3
1
The warning is due to you attempting to add an integer (int shift = 3
) to a character value. You can change the data type to char
if you want to avoid that.
警告是由于您试图向一个字符值添加一个整数(int shift = 3)。如果想要避免,可以将数据类型更改为char。
A char
is 16 bits, an int
is 32.
一个字符是16位,一个整数是32。
char shift = 3;
// ...
eMessage[i] = (message[i] + shift) % (char)letters.length;
As an aside, you can simplify the following:
顺便提一下,你可以简化以下内容:
char[] message = {'o', 'n', 'c', 'e', 'u', 'p', 'o', 'n', 'a', 't', 'i', 'm', 'e'};
To:
:
char[] message = "onceuponatime".toCharArray();
#4
1
Two ways to implement a Caesar Cipher:
实现凯撒密码的两种方法:
Option 1: Change chars to ASCII numbers, then you can increase the value, then revert it back to the new character.
选项1:将chars更改为ASCII码,然后您可以增加该值,然后将其还原为新的字符。
Option 2: Use a Map map each letter to a digit like this.
选项2:用地图把每个字母都映射成这样的数字。
A - 0
B - 1
C - 2
etc...
With a map you don't have to re-calculate the shift every time. Then you can change to and from plaintext to encrypted by following map.
有了地图,你不需要每次都重新计算移位。然后,您可以通过以下映射更改为和从纯文本到加密。
#5
0
Hello...I have created a java client server application in swing for caesar cipher...I have created a new formula that can decrypt the text properly... sorry only for lower case..!
你好……我在swing中创建了一个java客户端服务器应用程序,用于凯撒密码…我已经创建了一个可以正确解密文本的新公式……抱歉,只是为了小写。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarserver extends JFrame implements ActionListener
{
static String cs="abcdefghijklmnopqrstuvwxyz";
static JLabel l1,l2,l3,l5,l6;
JTextField t1;
JButton close,b1;
static String en;
int num=0;
JProgressBar progress;
ceasarserver()
{
super("SERVER");
JPanel p=new JPanel(new GridLayout(10,1));
l1=new JLabel("");
l2=new JLabel("");
l3=new JLabel("");
l5=new JLabel("");
l6=new JLabel("Enter the Key...");
t1=new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
close=new JButton("Close");
close.setMnemonic('C');
close.setPreferredSize(new Dimension(300, 25));
close.addActionListener(this);
b1=new JButton("Decrypt");
b1.setMnemonic('D');
b1.addAction
Listener(this);
p.add(l1);
p.add(l2);
p.add(l3);
p.add(l6);
p.add(t1);
p.add(b1);
p.add(progress);
p.add(l5);
p.add(close);
add(p);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==close)
System.exit(0);
else if(e.getSource()==b1)
{
int key=Integer.parseInt(t1.getText());
String d="";
int i=0,j,k;
while(i<en.length())
{
j=cs.indexOf(en.charAt(i));
k=(j+(26-key))%26;
d=d+cs.charAt(k);
i++;
}
while (num < 21)
{
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException ex) { }
progress.setValue( num );
Rectangle progressRect = progress.getBounds();
progressRect.x=0;
progressRect.y=0;
progress.paintImmediately( progressRect );
num++;
}
l5.setText("Decrypted text: "+d);
}
}
public static void main(String args[])throws IOException
{
new ceasarserver();
String strm =new String();
ServerSocket
ss=new ServerSocket(4321);
l1.setText("Secure data transfer Server Started....");
Socket s=ss.accept();
l2.setText("Client Connected !");
while(true)
{
Scanner br1= new Scanner(s.getInputStream());
en=br1.nextLine();
l3.setText("Client:"+en);
}
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarclient extends JFrame
{
String cs="abcdefghijklmnopqrstuvwxyz";
static JLabel l1,l2,l3,l4,l5;
JButton b1,b2,b3;
JTextField t1,t2;
JProgressBar progress;
int num=0;
String en="";
ceasarclient(final Socket s)
{
super("CLIENT");
JPanel p=new JPanel(new GridLayout(10,1));
setSize(500,500);
t1=new JTextField(30);
b1=new JButton("Send");
b1.setMnemonic('S');
b2=new JButton("Close");
b2.setMnemonic('C');
l1=new JLabel("Welcome to Secure Data transfer!");
l2=new JLabel("Enter the word here...");
l3=new JLabel("");
l4=new JLabel("Enter the Key:");
b3=new JButton("Encrypt");
b3.setMnemonic('E');
t2=new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
p.add(l1);
p.add(l2);
p.add(t1);
p.add(l4);
p.add(t2);
p.add(b3);
p.add(progress);
p.add(b1);
p.add(l3);
p.add(b2);
add(p);
setVisible(true);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try{
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
pw.println(en);
}catch(Exception ex){};
l3.setText("Encrypted Text Sent.");
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String strw=t1.getText();
int key=Integer.parseInt(t2.getText());
int i=0,j,k;
while(i<strw.length())
{
j=cs.indexOf(strw.charAt(
i));
k=(j+key)%26;
en=en+cs.charAt(k);
i++;
}
while (num < 21)
{
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException exe) { }
progress.setValue( num );
Rectangle progressRect = progress.getBounds();
progressRect.x=0;
progressRect.y=0;
progress.paintImmediately( progressRect );
num++;
}
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
pack();
}
public static void main(String args[])throws IOException
{
final Socket s =new Socket(InetAddress.getLocalHost(),4321);
new ceasarclient(s);
}
}
#1
8
Java Shift Caesar Cipher by shift
spaces.
Restrictions:
限制:
- Only works with a positive number in the shift parameter.
- 只在移位参数中使用正数。
- Only works with shift less than 26.
- 只适用于小于26的移动。
- Does a += which will bog the computer down for bodies of text longer than a few thousand characters.
- a +=会使计算机的正文长度超过几千个字符。
- Does a cast number to character, so it will fail with anything but ascii letters.
- 将一个数字转换成字符,因此它将以任何形式失败,而不是ascii字符。
- Only tolerates letters a through z. Cannot handle spaces, numbers, symbols or unicode.
- 只允许字母a到z。不能处理空格、数字、符号或unicode。
- Code violates the DRY (don't repeat yourself) principle by repeating the calculation more than it has to.
- 代码违背了DRY(不要重复自己)的原则,重复计算比它必须要多。
Pseudocode:
伪代码:
- Loop through each character in the string.
- 循环遍历字符串中的每个字符。
- Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26)
- 增加字符的转换,如果它从字母表的末尾掉下来,那么将字母表中的字母的数量从字母表中减去。
- If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
- 如果转换不能使字符从字母表的末尾下降,那么就增加字符的转换。
- Append the character onto a new string. Return the string.
- 将字符追加到一个新字符串中。返回字符串。
Function:
功能:
String cipher(String msg, int shift){
String s = "";
int len = msg.length();
for(int x = 0; x < len; x++){
char c = (char)(msg.charAt(x) + shift);
if (c > 'z')
s += (char)(msg.charAt(x) - (26-shift));
else
s += (char)(msg.charAt(x) + shift);
}
return s;
}
How to invoke it:
如何调用它:
System.out.println(cipher("abc", 3)); //prints def
System.out.println(cipher("xyz", 3)); //prints abc
#2
2
Below code handles upper and lower cases as well and leaves other character as it is.
下面的代码处理上和下的情况,并留下其他字符。
import java.util.Scanner;
public class CaesarCipher
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int length = Integer.parseInt(in.nextLine());
String str = in.nextLine();
int k = Integer.parseInt(in.nextLine());
k = k % 26;
System.out.println(encrypt(str, length, k));
in.close();
}
private static String encrypt(String str, int length, int shift)
{
StringBuilder strBuilder = new StringBuilder();
char c;
for (int i = 0; i < length; i++)
{
c = str.charAt(i);
// if c is letter ONLY then shift them, else directly add it
if (Character.isLetter(c))
{
c = (char) (str.charAt(i) + shift);
// System.out.println(c);
// checking case or range check is important, just if (c > 'z'
// || c > 'Z')
// will not work
if ((Character.isLowerCase(str.charAt(i)) && c > 'z')
|| (Character.isUpperCase(str.charAt(i)) && c > 'Z'))
c = (char) (str.charAt(i) - (26 - shift));
}
strBuilder.append(c);
}
return strBuilder.toString();
}
}
#3
1
The warning is due to you attempting to add an integer (int shift = 3
) to a character value. You can change the data type to char
if you want to avoid that.
警告是由于您试图向一个字符值添加一个整数(int shift = 3)。如果想要避免,可以将数据类型更改为char。
A char
is 16 bits, an int
is 32.
一个字符是16位,一个整数是32。
char shift = 3;
// ...
eMessage[i] = (message[i] + shift) % (char)letters.length;
As an aside, you can simplify the following:
顺便提一下,你可以简化以下内容:
char[] message = {'o', 'n', 'c', 'e', 'u', 'p', 'o', 'n', 'a', 't', 'i', 'm', 'e'};
To:
:
char[] message = "onceuponatime".toCharArray();
#4
1
Two ways to implement a Caesar Cipher:
实现凯撒密码的两种方法:
Option 1: Change chars to ASCII numbers, then you can increase the value, then revert it back to the new character.
选项1:将chars更改为ASCII码,然后您可以增加该值,然后将其还原为新的字符。
Option 2: Use a Map map each letter to a digit like this.
选项2:用地图把每个字母都映射成这样的数字。
A - 0
B - 1
C - 2
etc...
With a map you don't have to re-calculate the shift every time. Then you can change to and from plaintext to encrypted by following map.
有了地图,你不需要每次都重新计算移位。然后,您可以通过以下映射更改为和从纯文本到加密。
#5
0
Hello...I have created a java client server application in swing for caesar cipher...I have created a new formula that can decrypt the text properly... sorry only for lower case..!
你好……我在swing中创建了一个java客户端服务器应用程序,用于凯撒密码…我已经创建了一个可以正确解密文本的新公式……抱歉,只是为了小写。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarserver extends JFrame implements ActionListener
{
static String cs="abcdefghijklmnopqrstuvwxyz";
static JLabel l1,l2,l3,l5,l6;
JTextField t1;
JButton close,b1;
static String en;
int num=0;
JProgressBar progress;
ceasarserver()
{
super("SERVER");
JPanel p=new JPanel(new GridLayout(10,1));
l1=new JLabel("");
l2=new JLabel("");
l3=new JLabel("");
l5=new JLabel("");
l6=new JLabel("Enter the Key...");
t1=new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
close=new JButton("Close");
close.setMnemonic('C');
close.setPreferredSize(new Dimension(300, 25));
close.addActionListener(this);
b1=new JButton("Decrypt");
b1.setMnemonic('D');
b1.addAction
Listener(this);
p.add(l1);
p.add(l2);
p.add(l3);
p.add(l6);
p.add(t1);
p.add(b1);
p.add(progress);
p.add(l5);
p.add(close);
add(p);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==close)
System.exit(0);
else if(e.getSource()==b1)
{
int key=Integer.parseInt(t1.getText());
String d="";
int i=0,j,k;
while(i<en.length())
{
j=cs.indexOf(en.charAt(i));
k=(j+(26-key))%26;
d=d+cs.charAt(k);
i++;
}
while (num < 21)
{
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException ex) { }
progress.setValue( num );
Rectangle progressRect = progress.getBounds();
progressRect.x=0;
progressRect.y=0;
progress.paintImmediately( progressRect );
num++;
}
l5.setText("Decrypted text: "+d);
}
}
public static void main(String args[])throws IOException
{
new ceasarserver();
String strm =new String();
ServerSocket
ss=new ServerSocket(4321);
l1.setText("Secure data transfer Server Started....");
Socket s=ss.accept();
l2.setText("Client Connected !");
while(true)
{
Scanner br1= new Scanner(s.getInputStream());
en=br1.nextLine();
l3.setText("Client:"+en);
}
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarclient extends JFrame
{
String cs="abcdefghijklmnopqrstuvwxyz";
static JLabel l1,l2,l3,l4,l5;
JButton b1,b2,b3;
JTextField t1,t2;
JProgressBar progress;
int num=0;
String en="";
ceasarclient(final Socket s)
{
super("CLIENT");
JPanel p=new JPanel(new GridLayout(10,1));
setSize(500,500);
t1=new JTextField(30);
b1=new JButton("Send");
b1.setMnemonic('S');
b2=new JButton("Close");
b2.setMnemonic('C');
l1=new JLabel("Welcome to Secure Data transfer!");
l2=new JLabel("Enter the word here...");
l3=new JLabel("");
l4=new JLabel("Enter the Key:");
b3=new JButton("Encrypt");
b3.setMnemonic('E');
t2=new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
p.add(l1);
p.add(l2);
p.add(t1);
p.add(l4);
p.add(t2);
p.add(b3);
p.add(progress);
p.add(b1);
p.add(l3);
p.add(b2);
add(p);
setVisible(true);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try{
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
pw.println(en);
}catch(Exception ex){};
l3.setText("Encrypted Text Sent.");
}
});
b3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String strw=t1.getText();
int key=Integer.parseInt(t2.getText());
int i=0,j,k;
while(i<strw.length())
{
j=cs.indexOf(strw.charAt(
i));
k=(j+key)%26;
en=en+cs.charAt(k);
i++;
}
while (num < 21)
{
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException exe) { }
progress.setValue( num );
Rectangle progressRect = progress.getBounds();
progressRect.x=0;
progressRect.y=0;
progress.paintImmediately( progressRect );
num++;
}
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
pack();
}
public static void main(String args[])throws IOException
{
final Socket s =new Socket(InetAddress.getLocalHost(),4321);
new ceasarclient(s);
}
}