This is one of my school assignments and I just wanted to ask if there are some obvious mistakes or things I could maybe improve in this code. Thank you for any suggestions.
import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class App { public static void main(String[] args) { //Initialize and populate alphabet HashMap HashMap<Integer, Character> alphabet = new HashMap<Integer, Character>(); alphabet.put(1, 'A'); alphabet.put(2, 'B'); alphabet.put(3, 'C'); alphabet.put(4, 'D'); alphabet.put(5, 'E'); alphabet.put(6, 'F'); alphabet.put(7, 'G'); alphabet.put(8, 'H'); alphabet.put(9, 'I'); alphabet.put(10,'J'); alphabet.put(11, 'K'); alphabet.put(12, 'L'); alphabet.put(13, 'M'); alphabet.put(14, 'N'); alphabet.put(15, 'O'); alphabet.put(16, 'P'); alphabet.put(17, 'Q'); alphabet.put(18, 'R'); alphabet.put(19, 'S'); alphabet.put(20, 'T'); alphabet.put(21, 'U'); alphabet.put(22, 'V'); alphabet.put(23, 'W'); alphabet.put(24, 'X'); alphabet.put(25, 'Y'); alphabet.put(26, 'Z'); try { //Load file File ciphertext = new File("ciphertext.txt"); Scanner reader = new Scanner(ciphertext); //Input for key Scanner keyboard = new Scanner(System.in); System.out.println("Enter the key: "); int key = keyboard.nextInt(); //Main while loop while (reader.hasNext()) { String data = reader.nextLine(); String decrypted = ""; //Loop through ciphertext.txt for (int i = 0; i < data.length(); i++) { //If current character is a space, append space to decrypted if (data.charAt(i) == ' '){ decrypted += ' '; } //For each element in alphabet for (Map.Entry<Integer, Character> entry : alphabet.entrySet()) { //If entry == curr char in data (entry = one alphabet letter) if (entry.getValue() == data.charAt(i)) { //If entry + key is greater than 26 if (entry.getKey() + key > 26) { //Total key - 26 decrypted += alphabet.get(entry.getKey() + key - 26); } else { decrypted += alphabet.get(entry.getKey() + key); } } } } System.out.println(decrypted); } //Close reader reader.close(); //File not found exception } catch (FileNotFoundException e) { System.out.println("File not found"); e.printStackTrace(); } }
}