Начинающий Java;Morse (De / En) шифрование.Удаление частей подстроки - PullRequest
0 голосов
/ 15 апреля 2019

У меня здесь есть кодер и декодер азбуки Морзе.У меня возникла проблема с попыткой удалить фрагменты, которые я уже сделал, из подстроки здесь

sub = encrypted.indexOf(',');
morsechar1 = encrypted.substring(0,sub);
morsechars = encrypted.substring(sub);

, чтобы она продолжала работать, а не возвращалась к первому ',' и первому '', с которым она сталкивается.Я застрял с использованием простого кода, в противном случае я бы использовал заменить или обрезать или что-нибудь еще.Могу ли я получить несколько указателей?

((Примечание: запутался, опубликовав это в Code Review, намеревался разместить здесь))

import java.io.*;

public class MORSE {
  // Scanner object
  BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
  /**
   * Constructor for objects of class MORSE
   * This is where the code for the morse encoder/decoder goes.
   */
  public MORSE() throws IOException
  //here is where all of the variables go.
  { //Starting with the morse code alphabet.
    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'
    };
    String[] morse = {
      ".-",
      "-...",
      "-.-.",
      "-..",
      ".",
      "..-.",
      "--.",
      "....",
      "..",
      ".---",
      "-.-",
      ".-..",
      "--",
      "-.",
      "---",
      ".--.",
      "--.-",
      ".-.",
      "...",
      "-",
      "..-",
      "...-",
      ".--",
      "-..-",
      "-.--",
      "--.."
    };
    //Then the blank variables so the loops play nice.
    String sentence = "";
    String encrypted = "";
    //variables to help decode.
    String morsechar1, morsechars;
    //a temporary character to hold a value.
    char temp;
    //and some blank numbers so that the loops play nice.
    int choice = 0;
    int sub = 0;
    int alt = 0;

    while (choice != 3) {
      //Menu time!
      //Here is where you ask the user their input.
      System.out.println("1. Encrypt a sentence in Morse code");
      System.out.println("2. Decrypt a sentence back to English");
      System.out.println("3. Quit");
      System.out.println("Please enter your choice (1,2,3)");
      //once you have their number, you bring it to the right loop.
      choice = Integer.parseInt(keyboard.readLine());
      //Why am I restating this? So that the values go back to blank during the loop.
      sentence = "";
      encrypted = "";
      if (choice == 1) {
        //Here you ask the user to enter the words to encode to morse.
        System.out.println("Enter the sentence you wish to turn into morse code.");
        //this reads the sentence entered.
        sentence = keyboard.readLine().substring(0);
        //no caps
        sentence = sentence.toLowerCase();
        //analyze letters entered with this loop.
        for (int x = 0; x < sentence.length(); x++) {
          //copy letter from sentence to temp using charAt
          temp = sentence.charAt(x);
          //find the temp letter in the array in the same pos as the
          //morse code blips it's letter equals.
          for (int y = 0; y < 26; y++) {
            //check if letter at position y = temp
            if (temp == letters[y]) {
              //then write out the sentence bit by bit.
              encrypted = encrypted + morse[y];
              encrypted = encrypted + ",";
            }
            //check if temp = space
            if (temp == ' ') {
              //add space where needed.
              encrypted = encrypted + " ";
            }
          }
        }
        System.out.println(encrypted);
      } else if (choice == 2) {
        //Here they enter the morse code they have and want to encode.
        System.out.println("Enter the sentence you wish to revert from Morse Code.");
        //This reads the user's entry.
        encrypted = keyboard.readLine().substring(0);
        //This just defines the variable so the program works.
        morsechar1 = "";
        //here comes the tricky bit.
        //This loop reads each letter and translates it.
        for (int x = 0; x < sentence.length(); x++) {
          /**
           *Here's where my issues is. I'm trying to remove from the substring.
           *The pieces I've already done, for both Alt and Morsechars.
           * It doesn't want to work. At all.
           */
          sub = encrypted.indexOf(',');
          //This 'sub' finds the position of the comma that separates
          //the morse code.
          morsechar1 = encrypted.substring(0, sub);
          //This goes from the first position to the comma as the
          //first character
          morsechars = encrypted.substring(sub++);
          //This should go from the first comma to the next one...
          //supposedly.
          alt = encrypted.indexOf(' ');
          //then this grabs the space as it did above.

          //find the temp letter in the array in the same pos as the letter
          //it's switching from the encrypted alphabet.
          for (int y = 0; y < 26; y++) {
            //check the morse letter and where in the array it is.
            //Find the equal letter.

            //This Morse.equals is a string command to match string.
            if (morsechars.equals(morse[y])) {
              //Then this grabs the equivalent letter in the alphabet.
              sentence = sentence + letters[y];
            }
            //check if temp = space
            if (alt == 1)
            //alt was defined as a variable index.of earlier.
            {
              //insert space.
              sentence = sentence + " ";
              alt = 0;
            }
          }
        }
        //this prints out the decoded sentence.
        System.out.println(morsechar1 + sentence);
      } else if (choice == 3) {
        //this ends the loop.
        System.out.println("Thanks for stopping by.");
        break;
      } else {
        //This sends them back into the loop for an incorrect entry.
        System.out.println("Sorry, that wasn't a proper option. Try again.");
      }
    }
  }
}

1 Ответ

0 голосов
/ 15 апреля 2019

Ваш цикл for использует sentence.length(), но sentence имеет длину 0, потому что входные данные хранятся в encrypted. Я не понял расшифровку, которую вы написали - это должно быть приемлемой заменой для блока choice == 2.

//Here they enter the morse code they have and want to encode.
System.out.println("Enter the sentence you wish to revert from Morse Code.");
//This reads the user's entry.
encrypted = keyboard.readLine().substring(0);
//This just defines the variable so the program works.
morsechar1 = "";
//here comes the tricky bit.
//This loop reads each letter and translates it.
StringBuilder tsb = new StringBuilder();
StringBuilder sb = new StringBuilder();
String ch;
for (int x = 0; x < encrypted.length(); x++) {
    if(encrypted.charAt(x) == ','){
        ch = sb.toString();
        sb = new StringBuilder();
        for (int i = 0; i < morse.length; i++) {
            if(ch.equals(morse[i])){
                tsb.append(letters[i]);
            }
        }
    } else {
        sb.append(encrypted.charAt(x));
    }
}
ch = sb.toString();
sb = new StringBuilder();
for (int i = 0; i < morse.length; i++) {
    if(ch.equals(morse[i])){
        tsb.append(letters[i]);
    }
}
tsb.append(sb.toString());
//this prints out the decoded sentence.
System.out.println(tsb.toString());
...