Caesar Cipher in Java - printing blank line - java

I'm currently trying to write a Caesar Cipher in Java with key 18.
The code I have so far is as follows, but for some reason I cannot work out, it isn't working.
import java.util.Objects;
import java.util.Scanner;
class MainApplication {
private static final Scanner input = new Scanner(System.in);
private static String CryptMessage(int key, String message) {
StringBuilder temp = new StringBuilder();
for (int i = 0; i == message.length(); i++) {
if (Character.isLetter(message.charAt(i))) {
int num = (int) message.charAt(i);
num = num + key;
if (Character.isUpperCase(message.charAt(i))) {
if (num > (int) ('Z')) {
num = num - 26;
} else if (num < (int) ('A')) {
num = num + 26;
}
}
if (Character.isLowerCase(message.charAt(i))) {
if (num > (int) ('z')) {
num = num - 26;
} else if (num < (int) ('a')) {
num = num + 26;
}
}
temp.append((char) num);
} else {
temp.append(message.charAt(i));
}
}
message = temp.toString();
return message;
}
private static void encrypt(){
int key = 18;
System.out.println("Please enter a message to encrypt: ");
String message = input.nextLine();
System.out.println(CryptMessage(key, message));
}
private static void decrypt(){
int key = -18;
System.out.println("Please enter a message to decrypt: ");
String message = input.nextLine();
System.out.println(CryptMessage(key, message));
}
public static void main(String args[]){
System.out.println("Message Encryption System 3.0");
System.out.println("Please select an option:");
System.out.println("[1] - Encrypt Message");
System.out.println("[2] - Decrypt Message");
String opt = input.nextLine();
if(Objects.equals(opt, "1")){
encrypt();
}
else if(Objects.equals(opt, "2")){
decrypt();
}
else{
System.out.println("Invalid input.");
}
}
}
The program runs, however, it prints a blank line where the encrypted (or decrypted) message should be.

The loop condition i == message.length() should be i < message.length().
The condition in a for loop determines when to continue to the next iteration. Your condition is false on the first iteration and the loop terminates immediately (after the first iteration).

This is a problem that can be solved with a debugger. If you go through your code one line at a time it is easier to catch the fact that the loop conditon nimrodm pointed out doesn't execute the way you expect it to. In addition you can check the values of the variables during execution and make sure they are correct at each step.

Related

Decrement by a certain amount on java

i'm trying to create a program where the number that the user has input would decrease by a certain amount. something that would like this:
Update by (Increment/Decrement):decrement
Enter starting number:15
Enter update number:3
Enter end number:3
loop#1 value=15
loop#2 value=12
the end number is where the loop would stop and the update number is how much the starting number should decrement by. so far this is the code I have and I'm stuck on how to keep the loop going until the end number.
package jaba;
import java.util.Scanner;
public class loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String Decrement = scan.nextLine();
System.out.print("Enter starting number:");
String number = scan.nextLine();
System.out.print("Enter update number:");
String upnumber = scan.nextLine();
System.out.print("Enter end number:");
String endnumber = scan.nextLine();
int i,j;
i = 15;
j = 1;
do {
System.out.println("loop#" +j+ "\tvalue="+i);
j++;
}while(i<15);
i = i-3;
System.out.println("loop#" +j+ "\tvalue="+i);
};
}
how about something like this:
public class loop {
public enum Operation {INCREMENT, DECREMENT, INVALID}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String operationString = scan.nextLine();
System.out.print("Enter starting number:");
String numberString = scan.nextLine();
System.out.print("Enter update number:");
String upnumberString = scan.nextLine();
System.out.print("Enter end number:");
String endnumberString = scan.nextLine();
// Determine and parse stuff
int startNumber = Integer.parseInt(numberString);
int updateNumber = Integer.parseInt(upnumberString);
int endNumber = Integer.parseInt(endnumberString);
// Parse operation, but assume invalid operation
Operation operation = Operation.INVALID;
if (operationString.equalsIgnoreCase("increment")) {
operation = Operation.INCREMENT;
} else if (operationString.equalsIgnoreCase("decrement")) {
operation = Operation.DECREMENT;
}
// now do the "meat" of the assignment
int loopNumber = 0; // we'll keep the loop number as a separate counter
switch (operation) {
case INCREMENT:
for (int i = startNumber; i < endNumber; i = i + updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i);
}
break;
case DECREMENT:
for (int i = startNumber; i > endNumber; i = i - updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i)
}
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
}
private static void performAssignmentPrinting(int loopNumber, int value) {
System.out.println("loop#" + loopNumber + "\tvalue=" + value);
}
}
or the do/while version:
// now do the "meat" of the assignment
int currentNumber = startNumber;
int loopNumber = 0; // we'll keep the loop number as a separate counter
do {
loopNumber++;
switch (operation) {
case INCREMENT:
currentNumber += updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case DECREMENT:
currentNumber -= updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
} while (currentNumber != endNumber);
you have i = i-3; out of loop.
Move decrementation of i into loop:
do {
System.out.println("loop#" + j + "\tvalue=" + i);
j++;
i = i - 3;
} while (i > endnumber);
For loop is the solution for your program. for(a ; b ; c) {...}
Google how a for loop works. And try to understand how the 3 parts a,b,c works.
Pseudo:
// if decrease mode
// for (i = upperbound ; i >= lowerbound ; i-= decrement)
// print i
// if increase mode
// for (i = lowerbound ; i <= upperbound ; i+= increment)
// print i
Update: This is sufficient to get you started and add more validation on your journey.

Trying to iterate certain interval using "do -while"

Hi this code is part of my code that is supposed to check if the number string is palindrome.
I want to iterate from top to botoom of my code but it doesn't iterate at all , what is wrong ??
I searched in youtube and realized this kind of things , people usually use do-while loop so I was trying to follow the instruction but it doesn't give me what I want .
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
Here is my full code.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
char choice;
long firstNum = 0;
firstNum = getLong(" Enter the first number: ", '-');
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
public static long getLong(String prompt, char exitChar)
{
long retVal = 0;
boolean validInput = false;
String userInput = "";
Scanner kbd = new Scanner(System.in);
while (!validInput) {
System.out.println(prompt);
try
{
userInput = kbd.nextLine().trim();
if (userInput.length() > 0 && userInput.charAt(0) == exitChar)
{
System.out.println("Ending the program at the user's request");
System.exit(1);
}
retVal = Long.parseLong(userInput);
validInput = true;
}
catch (Exception ex)
{
System.out.println("That is not numeric. Try again or press " + exitChar + "to Quit");
}
}
return retVal;
}
}
Change this:
String str = kbd.nextLine().trim();
to this
String str = kbd.next();
When read choice, using nextLine() intead of next():
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.nextLine().charAt(0); // <---here, change to nextLine()
}while(choice=='y'||choice =='Y');
}
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. so in next loop it reads last input line that will be empty string.

After re-run program with while loop , exception method doesn't work

I'm handling exceptions for an exercise and runs fine until I enter an invalid number (to try) after running the program for the first time, this is after the first run when asking to re-run with different values if I happen to enter invalid values it won't throw the exception and I don't know why? It's something I don't know or is it my code? Thanks
//program ReverseNumbers.java
//This program reverses the digits of each number in an array.
import java.util.Scanner;
public class ReverseNumbers{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
boolean continueInput = true; //controls loop for input
String another = "y";
while(another.equalsIgnoreCase("Y")){ //loop to re-run program
do{
System.out.print("\nEnter 5 positive integers: "); //prompt the user to enter 5 integers
//try block
try{
for(int i = 0; i < numbers.length ; i++) //initialize the array
numbers[i] = input.nextInt();
checkInput(numbers); //handler method
continueInput = false;
}
//catch block
catch(IllegalArgumentException ex){
System.out.print("\nInvalid input: ");
//input.nextLine();
}
}while(continueInput);
//outputs
System.out.print("\nEntered numbers:\t\t");
for(int e: numbers)
System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
reverse(numbers);
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
//Exception method
public static void checkInput(int[] array) throws IllegalArgumentException {
for(int i = 0; i < array.length; i++){
if(array[i]<0)
throw new IllegalArgumentException();
}
}
//method reverse.
public static void reverse(int[] array) {
//reverse order of element within the array
int i, k, t;
int n = array.length;
for (i = 0; i < n / 2; i++) {
t = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = t;
}
reverse(array, array.length-1);
}
//helper method
public static void reverse(int[] array, int n){ //reverse the order of the number for each element in the array
// n, number of elements in the array
if(n>=0){
int Element = array[n]; //element n in array
int NewElement = -1;
int Digit = -1;
String s = "";
if(Element<10)
s = Element + "";
while(Element >= 10){ //loop up to element is reduced to one digit number
Digit = Element%10;
s = s + "" + Digit; //save the digits
NewElement = Element/10;
if(NewElement < 10) //when NewElement has 1 digit left
s = s + "" + NewElement;
Element = NewElement;
}
System.out.print(s + " "); //print digit
reverse(array, n-1); //recursive call
}
}
}
This can be fixed simply by inserting continueInput = true in your outer while loop. Without that, continueInput will always be false after the first time you enter a valid input, and your do-while loop will always exit after one iteration.
However, I wouldn't suggest throwing exceptions yourself, and you should probably handle Scanner's InputMismatchException. Also, your reverse method is unnecessarily complicated. Here's the code I got:
import java.util.Scanner;
public class ReverseNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
String another = "y";
while (another.equalsIgnoreCase("Y")) { //loop to re-run program
boolean continueInput = true; //controls loop for input
outer: do {
System.out.print("\nEnter " + numbers.length + " positive integers: ");
try {
for (int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
if (num < 0) {
System.out.print("Invalid input, found a negative integer " + num)
continue outer;
} else {
numbers[i] = num;
}
}
continueInput = false;
}
//handle bad inputs that aren't digits
catch (InputMismatchException ex) {
System.out.print("\nInvalid input, please enter integers");
}
} while (continueInput); //outputs
System.out.print("\nEntered numbers:\t\t");
for (int e: numbers) System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + (i == 0 ? "\n" : " "));
}
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
}

Index out of bounds issue with number systems code

I am currently having an issue with a problem where my java index is out of bounds. The specific error is inside my binaryToDecimal method and is Index 32 out of bounds for length 32. I have tried to reorganize my code as in declaring the int binaryVal[] = new int[32]; as a global variable to fix the error but it does not work. How do I fix this issue?
import java.util.Scanner;
public class NumberConverter {
public static Scanner input = new Scanner(System.in);
static boolean success;
static String originalNum;
static int value = 0;
static int choice = 0;
static int intNum = 0;
static int remainder;
static char [] valueBinaryArray;
public static void main(String[] args) {
// TODO Auto-generated method stub
greeting();
getOriginalNumber();
getOutputType();
//checkValidInput();
if (value == 2 && choice == 3) {
decimalToHex();
}
else if (value == 3 && choice == 2) {
hexToDecimal();
}
else if (value == 2 && choice == 1) {
decimalToBinary();
}
else if (value == 1 && choice == 2) {
binaryToDecimal();
}
}
public static void greeting() {
System.out.println("Hello and welcome to the number systems converter");
System.out.println("Below you will be givin options as to what numbers you'd like to convert");
System.out.println("");
}
public static String getOriginalNumber() {
System.out.println("Enter a number:");
originalNum = input.next();
System.out.println("What type of number is this?");
System.out.println("");
System.out.println("1. Binary");
System.out.println("2. Decimal");
System.out.println("3. Hexadecimal");
value = input.nextInt();
return originalNum;
}
public static void getOutputType() {
System.out.println("Which number system would you like to convert to?");
System.out.println("");
System.out.println("1. Binary");
System.out.println("2. Decimal");
System.out.println("3. Hexadecimal");
choice = input.nextInt();
}
public static void checkValidInput() {
}
public static void decimalToHex() {
int intNum = Integer.valueOf(originalNum);
String str2 = "";
char hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while (choice > 0) {
remainder = intNum % 16;
str2 = hex[remainder] + str2;
intNum = intNum/16;
}
}
public static void hexToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
String hexVal = "";
int digit;
while (choice > 0) {
digit = intNum % 16;
switch (digit) {
case 1:
hexVal+="F"; break;
case 2:
hexVal+="E"; break;
case 3:
hexVal+="D"; break;
case 4:
hexVal+="C"; break;
case 5:
hexVal+="B"; break;
case 6:
hexVal+="A"; break;
default:
hexVal+=Integer.toString(digit);
}
intNum = intNum/16;
}
for (counter = hexVal.length()-1; counter>=0; counter--)
System.out.print(hexVal.charAt(counter));
}
public static void decimalToBinary() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.println(binaryVal[i]);
}
}
public static void binaryToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.print(binaryVal[i]);
}
}
}
If you have an array with 32 items the first one is index 0 and the last one is index 31. Trying to access the item at position 32 goes out of the range of the array which is why you get an array index out of bounds exception.
To see the output I would suggest maybe make the array 33 big instead of 32. It's not a proper fix but you should be able to see what it is doing.
If it still goes out of bounds I'd have a closer look at your while loop end condition.
so what is causing your error is your condition in your for statement. Currently, you are just checking if choice >= 0 the problem with this check is that it allows the for statement to go beyond the length of the array you have specified (32). In order to fix this error, you simply need to add another check to make sure the for loop cannot go beyond the length of the array you have specified. This can be done by adding this statement into your for loop: counter < binaryVal.length. This should prevent the for loop from going beyond the length of your array and you shouldn't run into any errors. Your final code for your binaryToDecimal method should look like this:
public static void binaryToDecimal() {
int intNum = Integer.valueOf(originalNum);
int counter = 0;
int binaryVal[] = new int[32];
while (choice > 0 && counter < binaryVal.length) {
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
for (int i = counter-1; i >= 0; i--) {
System.out.print(binaryVal[i]);
}
}

Getting a program to loop within its self

I need help getting this program to loop within its self after it runs the first time. It asks the user if they want to encode, decode or exit. The program runs, it encodes/decodes like it should. I now need to get another Pane to pop up and ask if they user wants to code another input then loop through everything it ran through the first time. I have the pane to where it asks the user if they want to run again but cant get it to loop through the coder.
public void encoding()
{
int userChoice;
int i;
int p=1;
int counter=0;
counter++;
String fin = "";
String input = JOptionPane.showInputDialog("Want to ENCODE, DECODE or EXIT? Press
1, 2, or 3");
userChoice = Integer.parseInt(input);
if (userChoice == 1 )
{
String encode = JOptionPane.showInputDialog(null, "What Are We
Encoding? ");
char[] array = encode.toCharArray();
for(i=0; i <array.length; i++)
{
char Ecode = encode.charAt(i);
Ecode--;
Ecode--;
fin += Character.toString(Ecode);
}
JOptionPane.showMessageDialog(null, fin);
}
else if (userChoice == 2)
{
String decode =JOptionPane.showInputDialog(null, "What Are We
Decoding? ");
char[] array1 = decode.toCharArray();
for(i=0; i < array1.length; i++)
{
char Dcode = decode.charAt(i);
Dcode++;
Dcode++;
fin += Character.toString(Dcode);
}
JOptionPane.showMessageDialog(null,fin);
String again = JOptionPane.showInputDialog("Want to code another?
Press 1 or 2");
int aChoice = Integer.parseInt(again);
if (aChoice==1)
{
System.out.print("bob");
}
else
{
JOptionPane.showMessageDialog(null, "Good Bye");
System.exit(0);
}
}
Wrap you code starting int i; and include if-else block in a do-while loop as:
do{
int i;
int p=1;
.....
.....
}while(userChoice != 3);
Please Note: This will not let you exit, until you enter 3.
You may want to add another block to handle th conditions when user enters anything other that 1,2 or 3.
Alternatively, you can do like:
do{
String input = JOptionPane.showInputDialog...
.....
.....
}while(userChoice == 1 || userChoice == 2);
This will exit the loop for any choice other than 1 or 2.
EDIT: Please find below the fixed code:
public void encoding(){
int userChoice, i;
do{
String fin = "";
String input = JOptionPane
.showInputDialog("Want to ENCODE, DECODE or EXIT? Press 1, 2, or 3");
userChoice = Integer.parseInt(input);
if (userChoice == 1 ){
String encode = JOptionPane.showInputDialog(null, "What Are We Encoding?");
char[] array = encode.toCharArray();
for(i=0; i <array.length; i++){
char Ecode = encode.charAt(i);
Ecode--;
Ecode--;
fin += Character.toString(Ecode);
}
JOptionPane.showMessageDialog(null, fin);
} else if (userChoice == 2) {
String decode =JOptionPane.showInputDialog(null, "What Are We Dencoding?");
char[] array1 = decode.toCharArray();
for(i=0; i < array1.length; i++){
char Dcode = decode.charAt(i);
Dcode++;
Dcode++;
fin += Character.toString(Dcode);
}
JOptionPane.showMessageDialog(null, fin);
}
}while(userChoice != 3);
JOptionPane.showMessageDialog(null, "Good Bye");
System.exit(0);
}
You could enclose the JOptionPane inputs + the full corresponding if block in a while loop:
int userChoice = 0;
while (userChoice != 3) {
int i;
int p=1;
// the rest of the params here
String input = JOptionPane.showInputDialog(...)
...
}

Categories