【问题标题】:Get result from for loop and add it to another variable for every iteration从 for 循环中获取结果并将其添加到每次迭代的另一个变量中
【发布时间】:2017-05-22 23:23:07
【问题描述】:

我有一个任务,我应该编写一个程序,该程序可以使用他们输入的“加密密钥”对用户输入的单词进行加密和解密。我想要做的是检查输入键中每个字母的值,与字母表相比(例如:a = 1,b = 2,c = 3),然后添加字母的值,然后用于移动他们分配的单词中的字符。 到目前为止,这是我的作业代码:

    /* Validity Check from http://stackoverflow.com/questions/33965542/password-check-program-checking-capitals-lowercase-letters-digit-and-special
 * 
 * 
 * 
 * 
 */
import java.util.*;
public class SecretDecoderFinal
{
  public static void main (String [] args)
  {
    optInput();

  }

  public static int optInput()
  {
    int opt = 0;
    do {
      String word = "";
      String key = "";
      System.out.println("Welcome to Seegson Security secure transmission terminal");
      System.out.println("");
      System.out.println("Enter an option for the terminal");
      System.out.println("(1) to encrypt a word");
      System.out.println("(2) to decrypt a word");
      System.out.println("(0) to exit the terminal");
      opt = In.getInt();
      System.out.println("You selected: Option " +opt);
      System.out.println("");
      switch(opt)
      {
        case 1:
          encryptWord(word, key);
          break;
        case 2:
          decryptWord(word, key);
          break;
        case 0:
          System.out.println("Thank you for using the encryption/decryption program");
          break;
        default:
          System.err.println("Invalid option. Select 1 for encryption, 2 for decryption, or 0 to exit");
          System.out.println("");
          break;
      }
    }while (!isExit(opt));

    return opt;

  }

  public static String keyInput(String key)
  {


    do
    {
      System.out.println("Enter the key you want for encryption/decryption");
      key = In.getString();
      System.out.println("Your key is: " +key);
      System.out.println("");

    }while (!isValid(key));
    //printEncrypted(key);

    return key;

  }

  public static String wordInput(String word)
  {

    do
    {
      System.out.println("Enter the word you want decrypted/encrypted");
      word = In.getString();
      System.out.println("You entered: " +word);
      System.out.println("");
    } while (!isValid(word));
    //printEncrypted(word);
    return word;

  }

  public static void encryptWord(String word, String key)
  {
   // String alphabet1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";

    wordInput(word);
    keyInput(key);
    System.out.println("The word from the encryptWord metod " +word);
    printEncrypted(word, key);

  }

  public static void decryptWord(String w, String k)
  {
    String alphabet1 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
    wordInput(w);
    keyInput(k);

  }

这部分代码来自我的朋友

public static String printEncrypted(String word, String key)
  {
    System.out.println("This is the word from the printEncrypted method: " +word);

    int shift = 0;

    //Uses the key length to determine how much the alphabet will shift
    for (int x = 0; x < key.length(); x++) 

      shift += key.charAt(x) - 96; 
    shift = shift % 26;


    //Creates an array to perform the shift
    char [] y = word.toCharArray(); 

    for (int x = 0; x < y.length; x++) 
      //Uses the shift to shift the alphabet to decrypt the word.
      for (int d = 0; d < shift; d++)

      if (y[x] == 'z') 

      y[x] = 'a';

    else {
      y[x]--;
    } 
    String newWord = new String(y);
    System.out.println("Encrypted is " +newWord);
    return newWord;


  }

  public static boolean isValid (String s)
  {
    String strSpecialChars="!@#$%&*()_+=-|<>?{}[]~";
    //String alphabet2 = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
    boolean upCase = false;
    boolean isDigit = false;
    boolean spChar = false;

    if (s.matches(".+[A-Z].+")){
      upCase = true;
    }

    if (s.matches(".+[1-9].+")){
      isDigit = true;
    }

    if (strSpecialChars.contains(s)){
      spChar = true;
    }


    if (upCase|| isDigit || spChar)

    {
      System.err.println("The string cannot contain capital letters, special characters or numbers. Try again.");
      System.out.println("");
      return false;
    }
    else 
    {
      return true;
    }

  }


  public static boolean isExit (int option)
  {
    if (option == 0)
    {

      return true;
    }
    else
    {
      return false; 
    }
  } 

}

这就是我想要为我的角色转变做的事情:

public class LetterTester
{
  public static void main (String []args)
  {

    String input="craig";
    final String alphabet="abcdefghijklmnopqrstvwxyz";
    int finalValue = 0;
    int[] numbers;
    for(int i=0;i<input.length();i++){

      finalValue=(alphabet.indexOf(input.charAt(i))+1);
      System.out.print(finalValue);

    }

  }
}

但是,我不知道如何创建变量并让我的 for 循环在每次运行时将其输出添加到变量中。 LetterTester 仅用于测试。在我的实际作业中,输入将从另一种方法中获取,然后进行测试。因此,例如,如果键是“abc”,它将确定每个字母的值,因此 a = 1,b = 2,c = 3。然后我希望将它一起添加到一个变量中我可以用。 因此,当输入的计算完成时,变量应该等于 6。

另外,不确定我是否应该为此提出第二个问题,但在我的作业代码中,我无法将我的单词和键输入的值从它们各自的方法(keyInput 和 wordInput)传递给一个名为 encryptWord 的方法,当我尝试从 encryptWord 方法测试它时,它显示单词为空白。

如果有人想知道我为输入做了什么,我正在使用 In 类,我从这里得到:http://www.ecf.utoronto.ca/~jcarter/

到目前为止,我的导师从一开始就教我们使用 In 类。

【问题讨论】:

  • WRT 到wordInput() 问题,您必须为该方法的返回值分配一些东西,例如String wordToEncrypt = wordInput();。不需要传递参数,因为它是从用户那里读取输入并返回值。
  • 我不明白包含所有注释掉的代码的目的是什么。为什么会有这么多额外的空行?请整理您的代码。
  • @KevinO 谢谢!我会试试的。
  • @LiranFunaro 谢谢,我清理了。
  • @KevinO 你能澄清一下我可以改变什么吗?我已经分配了调用 wordInput(); 的变量 String word和调用 keyInput() 的可变字符串键。你能给我举个例子吗?而且,我的 isValid 检查器和 wordInput 都给了我一个错误,说找不到变量词,即使我在上面声明了它。

标签: java encryption caesar-cipher


【解决方案1】:

OP 的问题内容太多,无法完全回答。以下代码是解决方案空间的指南。

  • 将单词和键的输入彼此分开以及任何其他操作收集起来。 getWord()getKey 方法需要使用 OP 指出的 In 类。这里的重点是方法不需要任何参数,有返回值,只收集信息(从而将输入与处理分开)。
  • encryptWord(String, String) 方法采用收集的输入并以某种方式对其进行转换,然后返回转换。它不应该做任何输出(同样,将 I/O 与处理分开)。我没有尝试复制加密算法。
  • decryptWord(String, String) 方法还采用收集的输入并按照算法对其进行转换。这里没有尝试实现任何东西,但本质上它是加密的逆过程。
  • 实际上并非所有内容都应该是静态的,但它遵循 OP 的方法。
  • isValid(String) 似乎仅限于小写字母。显然,如果该假设不正确,则可以对其进行调整。

    //  
    // is valid checks to see if only lower case characters  
    //  
    private static boolean isValid(final String chkWord)
    {
      // returns true only if the match is lower case a-z
      return chkWord.matches("^[a-z]+$");
    }
    
    private static String encryptWord(String word, String key)
    {
      // TODO: implement the encryption algorithm;
      //   The algorithm would use the key to do the encryption;
      // here will just add to character as quick example
      char[] wordChars = word.toCharArray();
    
      for (int i = 0; i < wordChars.length; ++i) {
          char c = wordChars[i];
          if (c >= 'a' && c <= 'm') { c += 13; }
          else if (c >= 'n' && c <= 'z') { c -= 13; }
          wordChars[i] = c;
      }
    
      return new String(wordChars);
    }
    
    private static String decryptWord(String word, String key)
    {
      // TODO: implement the decryption algorithm
      return "NEED TO IMPLEMENT";
    }
    
    private static String getWord()
    { 
      // the word should be gathered from the user in some fashion
      // using the In class that is provided
      return "helloworld"; 
    }
    
    private static String getKey()
    {
      // the key should be gathered from the user in some fashion
      // using the In class that is provided
      return "doit";
    }
    
    public static void main(String[] args)
    {
      final String word = getWord();
      final String key = getKey();
    
      boolean validWord = isValid(word);
      System.out.printf("Is valid [%s]: %b%n", word, validWord);
    
      if (! validWord) {
        System.err.println("Not a good word!");
        return;
      }
    
      String encrypted = encryptWord(word, key);
      System.out.printf("Encrypted %s: %s%n", word, encrypted);
    
      String decrypted = decryptWord(word, key);
      System.out.printf("Encrypted %s: %s%n", word, decrypted);
    
    }
    

isValid()的快速测试:

有效 [Hello]: false
有效 [你好]: true
是否有效 [specialchar*]: false

【讨论】:

  • 谢谢!我已经完成了您建议的更改,并且一切(嗯,参数和方法调用)工作正常。加密和解密工作正常,但这不是我打算做的方法。这是完全不同的,但我会等待答案。这就是我的代码中的内容:pastebin.com/4S3erBNH 现在我已经完成了您建议的更改,有效性检查器不会检测输入中的错误,例如特殊字符或大写字母。之前工作正常
  • @AliHammad,我不遵循所需的加密/解密,所以他们说这是留给读者的练习。我只是扔了一些东西来有一个占位符。从你的“朋友”那里你可能得到了加密片段,虽然我不知道它是否正确。
  • @AliHammad,WRT 到上面显示的isValid() 方法:"Hello" = false; “你好”=真; “特殊字符 *” = 假。不知道你看到了什么。
  • 我只需要在输入中接受小写字母,没有特殊字符、大写字母等,我可以看到你这样做了。但由于某种原因,它仍然没有给出它需要的错误
  • 是的,显示的测试用例表明上面的isValid() 只接受小写输入。 (输入中也没有空格;可能允许但目前不允许;只允许 [a-z])
猜你喜欢
  • 2018-05-23
  • 2015-03-19
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多