Question

In: Computer Science

I can't figure out why this won't run. //CryptographyTest.java //package cryptography; import java.util.Scanner; public class CryptographyTest...

I can't figure out why this won't run.

//CryptographyTest.java
//package cryptography;

import java.util.Scanner;

public class CryptographyTest {
  
public static void main(String[] args) {
// create a scanner object to read from user
Scanner s = new Scanner(System.in);
// prompt user for input option
while(true) {
// loop till user say exit
System.out.println("Select Option:");
System.out.println("1. Encrypt");
System.out.println("2. Decrypt");
System.out.println("3. Exit");
String input = s.nextLine(); // get user input
int option = 0;
try {
// check for valid input
option = Integer.parseInt(input);
if(option < 1 || option > 3) {
throw new IllegalArgumentException();
}
} catch (Exception e) {
// print error message
System.out.println("Invalid Input!");
}
      
       // check for user option
if(option == 1) {
// ask user for data to encrypt
System.out.print("Enter 4 digit number to Encrypt: ");
int data = getInput(s); // get user input
// check for valid input
if(data == -1) {
// print error message
System.out.println("Invalid Input!");
}
else {
System.out.print("Encrypted number is: ");
String encrypt_number = "" + Cryptography.encrypt(data);
// add zeroes at start of number if needed
int len = encrypt_number.length();
for(int i=4;i>len;i--) {
encrypt_number = "0" + encrypt_number;
}
System.out.println(encrypt_number);
}
}
else if(option == 2) {
// ask user for data to decrypt
System.out.print("Enter 4 digit number to Decrypt: ");
int data = getInput(s); // get user input
// check for valid input
if(data == -1) {
// print error message
System.out.println("Invalid Input!");
}
else {
System.out.print("Decrypted number is: ");
String decrypt_number = "" + Cryptography.decrypt(data);
// add zeroes at start of number if needed
int len = decrypt_number.length();
for(int i=4;i>len;i--) {
decrypt_number = "0" + decrypt_number;
}
System.out.println(decrypt_number);
}
}
else if(option == 3) {
// break the loop and exit program
System.out.println("Bye!");
break;
}
}
  
}

private static int getInput(Scanner s) {
String input;
// get user input
input = s.nextLine();
// check for input length
if(input.length() != 4) {
// return as input is not valid
return -1;
}
else {
// check for integer input
try {
int data = Integer.parseInt(input);
// return the input in integer form
return data;
} catch (Exception e) {
// return as input is not integer type
return -1;
}
}
}

}

(goes with this:)

//Cryptography.java

//package cryptography;

public class Cryptography {
  
public static int encrypt(int input) {
// input is a 4 digit integer
// convert integer to string
String str = "" + input;
// add zeroes at start of number if needed
int len = str.length();
for(int i=4;i>len;i--) {
str = "0" + str;
}
// get individual digits
int first_digit = str.charAt(0) - '0'; // remove '0' to convert char to digit
int second_digit = str.charAt(1) - '0';
int third_digit = str.charAt(2) - '0';
int fourth_digit = str.charAt(3) - '0';
// add 7 to each digit and take reminder by dividing 10
first_digit = (first_digit + 7) % 10;
second_digit = (second_digit + 7) % 10;
third_digit = (third_digit + 7) % 10;
fourth_digit = (fourth_digit + 7) % 10;
// replace first digit with third and second with fourth
String encrypt_number = "" + third_digit + fourth_digit + first_digit + second_digit;
// convert string to integer and return it
return Integer.parseInt(encrypt_number);
}
  
public static int decrypt(int input) {
// input is 4 digit integer
// convert integer to string
String str = "" + input;
// add zeroes at start of number if needed
int len = str.length();
for(int i=4;i>len;i--) {
str = "0" + str;
}
// get individual digits
int first_digit = str.charAt(0) - '0'; // remove '0' to convert char to digit
int second_digit = str.charAt(1) - '0';
int third_digit = str.charAt(2) - '0';
int fourth_digit = str.charAt(3) - '0';
// add 3 to each digit and take reminder by dividing 10
first_digit = (first_digit + 3) % 10;
second_digit = (second_digit + 3) % 10;
third_digit = (third_digit + 3) % 10;
fourth_digit = (fourth_digit + 3) % 10;
// replace first digit with third and second with fourth
String encrypt_number = "" + third_digit + fourth_digit + first_digit + second_digit;
// convert string to integer and return it
return Integer.parseInt(encrypt_number);
}

}

Solutions

Expert Solution

Please find your solutino below the code is corrected if any doubt comment and do upvote.

CryptographyTest.java:


import java.util.Scanner;
public class CryptographyTest {
          
        private static int getInput(Scanner s) {
                String input;
                // get user input
                input = s.nextLine();
                // check for input length
                if(input.length() != 4||Integer.parseInt(input)<0) {
                // return as input is not valid
                return -1;
                }
                else {
                // check for integer input
                try {
                int data = Integer.parseInt(input);
                // return the input in integer form
                return data;
                } catch (Exception e) {
                // return as input is not integer type
                return -1;
                }
                }
                }
        public static void main(String[] args) {
                // create a scanner object to read from user
                 Scanner s = new Scanner(System.in);
                 // prompt user for input option
                 while(true) {
                         // loop till user say exit
                         System.out.println("Select Option:");
                         System.out.println("1. Encrypt");
                         System.out.println("2. Decrypt");
                         System.out.println("3. Exit");
                         String input = s.nextLine(); // get user input
                         int option = 0;
                         try {
                                 // check for valid input
                         
                                 option = Integer.parseInt(input);
                                 if(option < 1 || option > 3) {
                                         throw new IllegalArgumentException();
                                 }
                                }
                          catch (Exception e) {
                                  // print error message
                             System.out.println("Invalid Input!");
                          }
                         
                 // check for user option
                 if(option == 1) {
                         // ask user for data to encrypt
                         System.out.print("Enter 4 digit number to Encrypt: ");
                         int data = getInput(s); // get user input
                         // check for valid input
                         if(data == -1) {
                                 // print error message
                                 System.out.println("Invalid Input!");
                                 }
                         else {
                                 System.out.print("Encrypted number is: ");
                                 String encrypt_number = "" + Cryptography.encrypt(data);
                                 // add zeroes at start of number if needed
                                 int len = encrypt_number.length();
                                 for(int i=4;i>len;i--) {
                                         encrypt_number = "0" + encrypt_number;
                                         }
                                 System.out.println(encrypt_number);
                                 }
                         }
                 else if(option == 2) {
                         // ask user for data to decrypt
                         System.out.print("Enter 4 digit number to Decrypt: ");
                         int data = getInput(s); // get user input
                         // check for valid input
                         if(data == -1) {
                                 // print error message
                                 System.out.println("Invalid Input!");
                                 }
                         else {
                                 System.out.print("Decrypted number is: ");
                                 String decrypt_number = "" + Cryptography.decrypt(data);
                                 // add zeroes at start of number if needed
                                 int len = decrypt_number.length();
                                 for(int i=4;i>len;i--) {
                                         decrypt_number = "0" + decrypt_number;
                                         }
                                 System.out.println(decrypt_number);
                                 }
                         }
                 else if(option == 3) {
                         // break the loop and exit program
                         System.out.println("Bye!");
                         break;
                         }
}
  
}
}

Cryptography.java:



public class Cryptography {
          
        public static int decrypt(int input) {
                // input is 4 digit integer
                // convert integer to string
                String str = "" + input;
                // add zeroes at start of number if needed
                int len = str.length();
                for(int i=4;i>len;i--) {
                str = "0" + str;
                }
                // get individual digits
                int first_digit = str.charAt(0) - '0'; // remove '0' to convert char to digit
                int second_digit = str.charAt(1) - '0';
                int third_digit = str.charAt(2) - '0';
                int fourth_digit = str.charAt(3) - '0';
                // add 3 to each digit and take reminder by dividing 10
                first_digit = (first_digit + 3) % 10;
                second_digit = (second_digit + 3) % 10;
                third_digit = (third_digit + 3) % 10;
                fourth_digit = (fourth_digit + 3) % 10;
                // replace first digit with third and second with fourth
                String encrypt_number = "" + third_digit + fourth_digit + first_digit + second_digit;
                // convert string to integer and return it
                return Integer.parseInt(encrypt_number);
                }

                

        

        
        public static int encrypt(int input) {
                // input is a 4 digit integer
                // convert integer to string
                String str = "" + input;
                // add zeroes at start of number if needed
                int len = str.length();
                for(int i=4;i>len;i--) {
                        str = "0" + str;
                }
                
                // get individual digits
                int first_digit = str.charAt(0) - '0'; 
                // remove '0' to convert char to digit
                int second_digit = str.charAt(1) - '0';
                int third_digit = str.charAt(2) - '0';
                int fourth_digit = str.charAt(3) - '0';
                // add 7 to each digit and take reminder by dividing 10
                first_digit = (first_digit + 7) % 10;
                second_digit = (second_digit + 7) % 10;
                third_digit = (third_digit + 7) % 10;
                fourth_digit = (fourth_digit + 7) % 10;
                // replace first digit with third and second with fourth
                String encrypt_number = "" + third_digit + fourth_digit + first_digit + second_digit;
                // convert string to integer and return it
                return Integer.parseInt(encrypt_number);
        }
}
        


Related Solutions

How would I prepare pseudocode and a flowchart for this? import java.util.Scanner; public class HotDogsBuns {...
How would I prepare pseudocode and a flowchart for this? import java.util.Scanner; public class HotDogsBuns {    private static int HOTDOG_COUNT_PKG = 10;    private static int BUNS_COUNT_PKG = 8;       public static void main(String[] args) {        //Scanner object to get user input        Scanner keyboard = new Scanner(System.in);               // Get number of people        System.out.print("How many people will be competing in the contest?: ");        int noOfPeople = keyboard.nextInt();...
create code for deletestudentbyID Number for choice == 4 package courseecom616; import java.util.Scanner; import java.util.ArrayList; public...
create code for deletestudentbyID Number for choice == 4 package courseecom616; import java.util.Scanner; import java.util.ArrayList; public class CourseeCOM616 {        private String courseName;     private String[] studentsName = new String[1];     private String studentId;        private int numberOfStudents;        public CourseeCOM616(String courseName) {         this.courseName = courseName;     }     public String[] getStudentsName() {         return studentsName;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public String getStudentId() {         return studentId;    ...
TASK: Based upon the following code: import java.util.Scanner; // Import the Scanner class public class Main...
TASK: Based upon the following code: import java.util.Scanner; // Import the Scanner class public class Main {   public static void main( String[] args ) {     Scanner myInput = new Scanner(System.in); // Create a Scanner object     System.out.println("Enter (3) digits: ");     int W = myInput.nextInt();     int X = myInput.nextInt();     int Y = myInput.nextInt();      } } Use the tools described thus far to create additional code that will sort the integers in either monotonic ascending or descending order. Copy your code and...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) {...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,1,2}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: " + WordsCharsLetters[1]); System.out.println("Letters: " + WordsCharsLetters[2]); } static int[] calculateAndPrintChars(String sentence) { int[] WCL = new int[3]; String[] sentenceArray=sentence.split(" "); WCL[0] = sentenceArray.length; int letterCount=0; for(int i=0;i<sentence.length();i++) { if(Character.isLetter(sentence.charAt(i))) letterCount++; } WCL[1]...
import java.util.Random; import java.util.Scanner; public class Compass { // You will need to do the following:...
import java.util.Random; import java.util.Scanner; public class Compass { // You will need to do the following: // // 1.) Define a private instance variable which can // hold a reference to a Random object. // // 2.) Define a constructor which takes a seed value. // This seed will be used to initialize the // aforementioned Random instance variable. // // 3.) Define a static method named numberToDirection // which takes a direction number and returns a String // representing...
I'm getting an error for this code? it won't compile import java.util.*; import java.io.*; public class...
I'm getting an error for this code? it won't compile import java.util.*; import java.io.*; public class Qup3 implements xxxxxlist {// implements interface    // xxxxxlnk class variables    // head is a pointer to beginning of rlinked list    private node head;    // no. of elements in the list    // private int count; // xxxxxlnk class constructor    Qup3() {        head = null;        count = 0;    } // end Dersop3 class constructor   ...
import java.util.Random; import java.util.Scanner; public class Compass { public Random r; public Compass(long seed){ r =...
import java.util.Random; import java.util.Scanner; public class Compass { public Random r; public Compass(long seed){ r = new Random(seed); }    public static String numberToDirection(int a){ if(a==0) return "North";    if(a==1) return "NorthEast"; if(a==2) return "East"; if(a==3) return "Southeast"; if(a==4) return "South"; if(a==5) return "Southwest"; if(a==6) return "West";    if(a==7) return "Northwest";    return "Invalid Direction" ; } public String randomDirection(){ return numberToDirection(r.nextInt()% 4 + 1); } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter seed: ");...
what i have: import java.util.Scanner; public class examples1 { public static void main(String[] args) { Square...
what i have: import java.util.Scanner; public class examples1 { public static void main(String[] args) { Square shade = new Square(getside()); System.out.println("Your chooses are:"); System.out.println("\nCircle"); System.out.println("Triangle"); System.out.println("Rectangle"); System.out.println("Square"); boolean moreShapes = true; boolean userChoice = true; while(moreShapes) { Scanner shapes = new Scanner (System.in); System.out.println("\nWhat shape do you want:"); String yourShape = shapes.nextLine(); if (userChoice = shade != null) { shade.getSide(); } System.out.println("\nWhat are two size paramters of the shape you choose:"); String yourParameter = shapes.nextLine(); System.out.println("\nYour shape is: " +...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public static void main(String[] args) {        System.out.println("This program will ask the user for three sets of two numbers and will calculate the average of each set.");        Scanner input = new Scanner(System.in);        int n1, n2;        System.out.print("Please enter the first number: ");        n1 = input.nextInt();        System.out.print("Please enter the second number: ");        n2 =...
How would I go about debugging this to make it work properly? import java.util.Scanner; public class...
How would I go about debugging this to make it work properly? import java.util.Scanner; public class TemperatureConverter{ public static void main(String[] args) { // Declare named constants. final double MIN_FAHRENHEIT = -459.67; // Declare the variables. double fahrenheit; double convertedDegrees; int tempScale; String tempScaleStr=""; // Creating the Scanner object Scanner keyboard = new Scanner(System.in); System.out.print("Enter the temperature in Fahrenheit: "); fahrenheit = keyboard.nextDouble(); // Set a breakpoint here // Verify the user's input if (fahrenheit > MIN_FAHRENHEIT) { // first...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT