[英]How to read alphabets (a-z || A-Z) and digits (0-9) characters from a text file only in Java?
[英]Caesar Cipher program, How to use only characters a-z?
凱撒密碼分別應用於字符串中的每個字母。 每個字母必須在字母表中向前移動n步。 如果將字母從字母末尾('z')移開,則它將一直移回字母開頭('a')。 `
import java.util.*;
class question7{
public static void main (String[] args ){
String str = "";
//allowing program to take user input using the keyboard
Scanner kb = new Scanner(System.in);
Scanner s = new Scanner(System.in);
int n = 0;
System.out.println("increasing the letters in string by n");
while (true){
System.out.println("Please enter your string");
str = kb.nextLine();
System.out.println("Please enter your n value");
n = s.nextInt();
String incrementedword=new String();
for (int i=0;i<str.length();i++){
incrementedword+=(char)(str.charAt(i)+n);
}
System.out.println ("your word is "+incrementedword);
}
}
}
例如,以下輸入(“ hello world”,1)應返回“ ifmmp xpsme”
但是,當我鍵入(“ hello world”,1)時,輸出為“ ifmmp!xpsme”
我究竟做錯了什么?
您在這里有兩個問題:
我不會在此處提供完整且有效的代碼,因為它看起來像是一項家庭作業。
如果字母不在范圍內,則需要控制環繞。 要對字母z以外的字母進行環繞操作。 下面的代碼將只移動字符串中的字母。
import java.util.*;
class question7{
public static void main (String[] args ){
String str = "";
//allowing program to take user input using the keyboard
Scanner kb = new Scanner(System.in);
Scanner s = new Scanner(System.in);
int n = 0;
int a = 'a';
int z = 'z';
System.out.println("increasing the letters in string by n");
while (true){
System.out.println("Please enter your string");
str = kb.nextLine().toLowerCase();
System.out.println("Please enter your n value");
n = s.nextInt();
int newCharValue;
int currentChar;
String incrementedword=new String();
for (int i=0;i<str.length();i++){
currentChar = str.charAt(i);
if(!Character.isLetter(currentChar)){
incrementedword+=currentChar;
continue;
}
newCharValue = currentChar + n;
if(newCharValue <= z)
incrementedword+=(char)newCharValue;
else
incrementedword+=(char)(a + (newCharValue - a + 1)%26);
}
System.out.println ("your word is "+incrementedword);
}
}
}
您也許可以將字母轉換為ascii,然后以這種方式遞增?
我的意思是,您必須設置約束,“ a”為97,“ z”為122。這將確保它保持在小寫字符內,並且您可以告訴它循環回到“ a”。
在循環中放置一個條件,該條件將檢查當前字符是否從字母“ a”到“ z”小寫:
用於檢查當前字符是否為小寫字母(a到z)的代碼段代碼:
if (currentChar >= 'a' && currentChar <= 'z') {
//Process the shifting of the characters here
}
現在,為了將每個字母向前移動n個字母,請嘗試以下公式:
if (currentChar >= 'a' && currentChar <= 'z') {
currentChar = (char) ((currentChar - 'a' + k) % 26 + 'a');
//Where n is the number of shifts forward (ex: a + 2 = c)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.