Scytale cipher plaintext and Z implementation - java

I'm having this trouble in Scytale cipher when displaying the plaintext, and also the "z" letter if there is lacking in the rows and columns.
To make the explanation easier, I want the plaintext to be displayed like this:
H E L L O
W O R L D
Z Z Z Z Z
This is my code:
import java.util.*;
public class scytale{
public static String scytaleEncode(String plaintext, int numRows){
String encodedText = "";
if(numRows>=plaintext.length() || numRows <=0){
System.out.println(plaintext + "z");
}
else{
while(plaintext.length()%numRows != 0){
plaintext += " ";
}
int numCols = plaintext.length()/numRows;
for(int i = 0; i<numCols; i++){
for (int y = i; y <plaintext.length(); y+=numCols;){
encodedText += plaintext.charAt(y);
}
System.out.println();
}
return encodedText;
}
}
public static void main(String[] args){
System.out.println("-------WELCOME TO SCYTALE CIPHER-------");
String cont;
do{
Scanner sc = new Scanner(System.in);
System.out.println("=================================");
System.out.println("Enter the String for Encryption: ");
String message = new String();
message = sc.nextLine();
System.out.println("\nEnter your key: ");
int key;
key = sc.nextInt();
System.out.println("\nCiphered:" + scytaleEncode(message.replaceAll("\\s",""), key));
System.out.println("\nWould you like to continue? (y/n): ");
cont = sc.next();
System.out.println("\n");
}while(cont.equalsIgnoreCase("y"));
System.out.println("Thank you for using SCYTALE CIPHER!\n");
}
}
How should I do this?

package cryptool;
import java.util.*;
public class scytale {
public static String scytaleEncode(String plaintext, int numRows) {
String encodedText = "";
if (numRows >= plaintext.length() || numRows <= 0) {
System.out.println(plaintext + "z");
} else {
while (plaintext.length() % numRows != 0) {
plaintext += " ";
}
int numCols = plaintext.length() / numRows;
for (int i = 0; i < numCols; i++) {
for (int y = i; y < plaintext.length(); y += numCols) {
encodedText += plaintext.charAt(y);
System.out.println(encodedText);
System.out.println(plaintext);
}
}
return encodedText;
}
return encodedText;
}
public static void main(String[] args) {
System.out.println("-------WELCOME TO SCYTALE CIPHER-------");
String cont;
do {
Scanner sc = new Scanner(System.in);
System.out.println("=================================");
System.out.println("Enter the String for Encryption: ");
// String message = new String();
String message = sc.nextLine();
System.out.println("\nEnter your key: ");
int key;
key = sc.nextInt();
System.out.println("\nCiphered:" + scytaleEncode(message.replaceAll("\\s", ""), key));
System.out.println("\nWould you like to continue? (y/n): ");
cont = sc.next();
System.out.println("\n");
} while (cont.equalsIgnoreCase("y"));
System.out.println("Thank you for using SCYTALE CIPHER!\n");
}
}

Related

Print specific characters

I have a string input which, that input have a team name and score separated by one space. e.g bb 3 , teamd 5 the winner should be teamd
In order to get the winner team that scored highest score, i'm doing following:
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
printWinnerTeam(cases);
}
public static void printWinnerTeam(int cases) {
Scanner scanner = new Scanner(System.in);
String str = "";
String winnerTeam = "";
int winnerScore = 0, countedChar = 0;
for (int i = 0; i < cases; i++) {
str += scanner.nextLine();
}
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i++) {
countedChar++;
if (arr[i] == ' ') {
if (str.charAt(i + 1) > winnerScore) {
winnerTeam = "";
winnerScore = (int) str.charAt((int) i + 1);
for (int j = 0; j < countedChar; j++) {
winnerTeam += str.charAt(j);
}
countedChar = 0;
} else {
//winnerTeam = "";
countedChar = 0;
}
}
}
System.out.println(winnerTeam);
}
But it's not work prefect, It's print wired result, how to make that work as expect ?
I haven't tried your code, But I would imagine a big problem is the concatenation of str += scanner.nextLine(); The new line is going to be appended straight onto the end of the previous lines number
Have a look at this
Scanner sc = new Scanner(System.in);
int bestScore = Integer.MIN_VALUE;
String team = "Nothing entered";
System.out.println("how many teams");
int count = sc.nextInt();
sc.nextLine();
while (count-- > 0) {
System.out.println("Entered team,score");
String line = sc.nextLine();
String arr [] = line.split(" ");
// check size - TBD
if (Integer.parseInt(arr[1]) > bestScore) {
bestScore = Integer.parseInt(arr[1]);
team = arr[0];
}
}
System.out.println("nest team is " + team + " with a score of " + bestScore);
If I have to do something like that I will do it like this:
import java.util.*;
public class winner {
public static void main (String args []) {
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
printWinnerTeam(cases);
}
public static void printWinnerTeam(int cases) {
Scanner scanner = new Scanner(System.in);
String winnerTeam = "";
String Team="";
int winnerScore = 0, score = 0;
for (int i = 0; i < cases; i++) {
Team = scanner.next();
score = scanner.nextInt();
if(score > winnerScore){
winnerTeam = Team;
winnerScore = score;
}
}
System.out.println("Winner team" + winnerTeam + "Score:" + winnerScore);
}
}

Want to find the output as given below using Java program?

Input text: are you ready
Output text: ArE YoU ReAdY
Help me what i am missing.
Below is the code which I am using:
import java.util.Scanner;
import java.lang.*;
public class Testdemo{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
String result = "";
System.out.println("enter the string");
String name =sc.nextLine();
String[] words = name.split("\\s");
for(int i=0;i<words.length;i++){
String med = words[i];
for(int j=0;j<med.length;j++){
if(i%2 == 0){
result = result + Character.toUpperCase(words[i].charAt(0)) + words[i].substring(1) + " ";
}
else{
result = result + Character.toLowerCase(words[i].charAt(0)) + words[i].substring(1) + " ";
}
}
}
System.out.println(result);
}
}
Scanner sc = new Scanner(System.in);
StringBuffer result = new StringBuffer();
System.out.println("enter the string");
String name = sc.nextLine();
String[] words = name.split("\\s");
for (int i = 0; i < words.length; i++) {
String med = words[i];
for (int j = 0; j < med.length(); j++) {
if (j % 2 == 0) {
result.append(Character.toUpperCase(words[i].charAt(j)));
} else {
result.append(Character.toLowerCase(words[i].charAt(j)));
}
}
result.append(" ");
}
System.out.println(result);

how to find common suffix in java by using method

How to find common suffix in java by using method
public static String commonSuffix (String s1, String s2)
I can't return the result in method. Please help me
import java.util.Scanner;
public class ders1 {
public static void main(String[] args) {
//HW3 Topic 3
Scanner input = new Scanner(System.in);
String reverse1="";
String reverse2="";
System.out.println("Please enter the first string: ");
String s1=input.nextLine();
System.out.println("Please enter the second string: ");
String s2=input.nextLine();
int l1=reverse1.length();
int l2=reverse2.length();
for ( int i = s1.length() - 1 ; i >= 0 ; i-- )
{
reverse1 = reverse1 + s1.charAt(i);
}
for ( int i = s2.length() - 1 ; i >= 0 ; i-- )
{
reverse2 = reverse2 + s2.charAt(i);
}
if(l1<l2){
int l3=l2;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1,reverse2,l3));
}
else {
int l3=l1;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1,reverse2,l3));
}
}
public static String commonSuffix (String reverse1, String reverse2,int l3){
String suffixies="";
for(int k=0; k<=l3 ; k++){
if(reverse1.charAt(k)!=reverse2.charAt(k)){
}
else{
suffixies+=reverse1.charAt(k);
}
}
return suffixies;
}
}
Can someone help me fix this code??
Your issue is that you return inside of the for loop. You should return after the for loop terminates.
Please see the following code (I have tested it):
import java.util.Scanner;
public class ders1 {
public static void main(String[] args) {
// HW3 Topic 3
Scanner input = new Scanner(System.in);
String reverse1 = "";
String reverse2 = "";
System.out.println("Please enter the first string: ");
String s1 = input.nextLine();
System.out.println("Please enter the second string: ");
String s2 = input.nextLine();
for (int i = s1.length() - 1; i >= 0; i--) {
reverse1 = reverse1 + s1.charAt(i);
}
for (int i = s2.length() - 1; i >= 0; i--) {
reverse2 = reverse2 + s2.charAt(i);
}
int l1 = reverse1.length();
int l2 = reverse2.length();
if (l1 < l2) {
int l3 = l1;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1, reverse2, l3));
} else {
int l3 = l2;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1, reverse2, l3));
}
}
public static String commonSuffix(String reverse1, String reverse2, int l3) {
String suffixies = "";
for (int k = 0; k < l3; k++) {
if (reverse1.charAt(k) != reverse2.charAt(k)) {
break;
} else {
suffixies += reverse1.charAt(k);
}
}
// Reverse again
String reverse = "";
for (int i = suffixies.length() - 1; i >= 0; i--) {
reverse = reverse + suffixies.charAt(i);
}
return reverse;
}
}
Output:
Please enter the first string:
caption
Please enter the second string:
action
noitpac noitca
tion
This could be the best
**
package com.tm;
import java.util.Scanner;
public class CommSuffix {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str[] = scan.nextLine().split(",");
String commSufffix=null;
if(str[0].trim().length() > str[1].trim().length()) {
String temp = str[0].trim();
str[0] = str[1].trim();
str[1] = temp;
}
for(int i=0;i<str[0].length();i++) {
String subStr = str[0].substring(i,str[0].length());
if(str[1].endsWith(subStr)) {
commSufffix = subStr;
break;
}
}
System.out.println(commSufffix);
}
} **

Loop back the beginning of the code

So my code works completely; the only thing now is a very simple problem that I cannot figure out. I have to make the program loop back to the beginning if the user type restart and I cannot think how to that.
import java.util.Scanner;
public class MutantGerbil {
public static String []foodName;
public static int [] maxAmount;
public static Gerbil [] gerbilAttributes;
public static int [] consumption;
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
String userInput1 = keyboard.nextLine();
int food = Integer.parseInt(userInput1);
foodName = new String[food]; //array of food names
maxAmount = new int[food]; // array of max amount of food given everyday
for (int i = 0; i < food; i++){
System.out.println("Name of food item" + (i+1) +": " );
String foodType = keyboard.nextLine();
foodName[i] = foodType;
System.out.println("Maximum consumed per gerbil: ");
String consumption = keyboard.nextLine();
int consumption2 = Integer.parseInt(consumption);
maxAmount [i] = consumption2;
}
System.out.println("How many gerbils are in the lab?");
String userInput2 = keyboard.nextLine();
int numberOfGerbils = Integer.parseInt(userInput2);
gerbilAttributes = new Gerbil [numberOfGerbils];// Array with the gerbil attributes
for (int i = 0; i < numberOfGerbils; i++)
{
consumption = new int[food]; // Array with amount of the food the gerbil eat each day
System.out.println("Gerbil" + (i+1) + "'s" + "lab ID: ");
String gerbilID = keyboard.nextLine();
System.out.println("What name did the students give to "+ gerbilID);
String gerbilName = keyboard.nextLine();
for (int j = 0; j < food; j++)
{
System.out.println(gerbilID + " eats how many " + foodName[j] + " per day?");
String gerbilComsumption = keyboard.nextLine();
int gerbilFood = Integer.parseInt(gerbilComsumption);
if (gerbilFood <= maxAmount[j])
{
consumption[j] = gerbilFood;
}
}
System.out.println("Does " + gerbilID + " bite?");
boolean biter = keyboard.nextBoolean();
System.out.println("Does " + gerbilID + " try to escape?");
boolean flightRisk = keyboard.nextBoolean();
keyboard.nextLine();
Gerbil temp = new Gerbil (gerbilID, gerbilName, consumption, biter, flightRisk);
gerbilAttributes [i] = temp;
}
boolean end1 = false;
while (! end1){
System.out.println("What information would you like to know");
sortGerbilArray (gerbilAttributes);
String userInput3 = keyboard.nextLine();
if (userInput3.equalsIgnoreCase("average"))
{
String average1 = foodAverage();
System.out.println(average1);
}
if (userInput3.equalsIgnoreCase("search"))
{
System.out.println("Enter a Gerbil ID to search for");
userInput3 = keyboard.nextLine();
Gerbil findGerbil = searchForGerbil(userInput3);
if (findGerbil == null)
{
System.out.println("Error");
}
else {
String h = ("Name: " + findGerbil.getName());
if (findGerbil.getAttacker())
{
h+= " (will bite, ";
}
else
{
h+= " (will not bite, ";
}
if (findGerbil.getFilghtRisk())
{
h+= "will run away), ";
}
else
{
h+= "will not run away), ";
}
h+= "Food:";
for (int i = 0; i < foodName.length; i++){
h+=" " + foodName[i] + "-";
h+= findGerbil.getConsumption2()+"/"+ maxAmount[i];
if (i < foodName.length-1)
{
h+=",";
}
System.out.println(h);
}
}
}
if (userInput3.equalsIgnoreCase("restart")){
}
if (userInput3.equalsIgnoreCase("quit"))
{
System.out.println("Good-bye!");
break;
}
}
}
private static void sortGerbilArray(Gerbil[]sortGerbil){
for (int i = 0; i < sortGerbil.length; i++){
for (int j = 0; j < sortGerbil.length - i - 1; j++){
if(sortGerbil[j].getID().compareToIgnoreCase(sortGerbil[j+1].getID())>0){
Gerbil t = sortGerbil[j];
sortGerbil[j] = sortGerbil[j+1];
sortGerbil[j+1] = t;
}
}
}
}
private static String foodAverage()
{
double average = 0.0;
double totalMaxAmount = 0;
double totalConsumption = 0;
String averageFood = "";
for (int i = 0 ; i < gerbilAttributes.length;i++)
{
for(int j = 0; j < maxAmount.length; j++)
{
totalMaxAmount += maxAmount[j];
}
totalConsumption += gerbilAttributes[i].getConsumption();
average = totalConsumption/totalMaxAmount*100;
averageFood += gerbilAttributes[i].getID() + "(" + gerbilAttributes[i].getName() + ")" + Math.round(average) + "%\n";
totalMaxAmount = 0;
totalConsumption = 0;
}
return averageFood;
}
private static Gerbil searchForGerbil (String x) {
for (Gerbil l: gerbilAttributes){
if (l.getID().equals(x)){
return l;
}
}
return null;
}
}
there are two solutions.
1. wrap your code in "while" loop. but it will be difficult for you because your code is so messy :(
change the code as follow
import java.util.Scanner; public class MutantGerbil {
public static String []foodName;
public static int [] maxAmount;
public static Gerbil [] gerbilAttributes;
public static int [] consumption;
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
String userInput1 = keyboard.nextLine();
int food = Integer.parseInt(userInput1);
foodName = new String[food]; //array of food names
maxAmount = new int[food]; // array of max amount of food given everyday
for (int i = 0; i < food; i++){
System.out.println("Name of food item" + (i+1) +": " );
String foodType = keyboard.nextLine();
foodName[i] = foodType;
System.out.println("Maximum consumed per gerbil: ");
String consumption = keyboard.nextLine();
int consumption2 = Integer.parseInt(consumption);
maxAmount [i] = consumption2;
}
System.out.println("How many gerbils are in the lab?");
String userInput2 = keyboard.nextLine();
int numberOfGerbils = Integer.parseInt(userInput2);
gerbilAttributes = new Gerbil [numberOfGerbils];// Array with the gerbil attributes
for (int i = 0; i < numberOfGerbils; i++)
{
consumption = new int[food]; // Array with amount of the food the gerbil eat each day
System.out.println("Gerbil" + (i+1) + "'s" + "lab ID: ");
String gerbilID = keyboard.nextLine();
System.out.println("What name did the students give to "+ gerbilID);
String gerbilName = keyboard.nextLine();
for (int j = 0; j < food; j++)
{
System.out.println(gerbilID + " eats how many " + foodName[j] + " per day?");
String gerbilComsumption = keyboard.nextLine();
int gerbilFood = Integer.parseInt(gerbilComsumption);
if (gerbilFood <= maxAmount[j])
{
consumption[j] = gerbilFood;
}
}
System.out.println("Does " + gerbilID + " bite?");
boolean biter = keyboard.nextBoolean();
System.out.println("Does " + gerbilID + " try to escape?");
boolean flightRisk = keyboard.nextBoolean();
keyboard.nextLine();
Gerbil temp = new Gerbil (gerbilID, gerbilName, consumption, biter, flightRisk);
gerbilAttributes [i] = temp;
}
boolean end1 = false;
while (! end1){
System.out.println("What information would you like to know");
sortGerbilArray (gerbilAttributes);
String userInput3 = keyboard.nextLine();
if (userInput3.equalsIgnoreCase("average"))
{
String average1 = foodAverage();
System.out.println(average1);
}
if (userInput3.equalsIgnoreCase("search"))
{
System.out.println("Enter a Gerbil ID to search for");
userInput3 = keyboard.nextLine();
Gerbil findGerbil = searchForGerbil(userInput3);
if (findGerbil == null)
{
System.out.println("Error");
}
else {
String h = ("Name: " + findGerbil.getName());
if (findGerbil.getAttacker())
{
h+= " (will bite, ";
}
else
{
h+= " (will not bite, ";
}
if (findGerbil.getFilghtRisk())
{
h+= "will run away), ";
}
else
{
h+= "will not run away), ";
}
h+= "Food:";
for (int i = 0; i < foodName.length; i++){
h+=" " + foodName[i] + "-";
h+= findGerbil.getConsumption2()+"/"+ maxAmount[i];
if (i < foodName.length-1)
{
h+=",";
}
System.out.println(h);
}
}
}
if (userInput3.equalsIgnoreCase("restart")){
main();
}
if (userInput3.equalsIgnoreCase("quit"))
{
System.out.println("Good-bye!");
break;
}
}
}
private static void sortGerbilArray(Gerbil[]sortGerbil){
for (int i = 0; i < sortGerbil.length; i++){
for (int j = 0; j < sortGerbil.length - i - 1; j++){
if(sortGerbil[j].getID().compareToIgnoreCase(sortGerbil[j+1].getID())>0){
Gerbil t = sortGerbil[j];
sortGerbil[j] = sortGerbil[j+1];
sortGerbil[j+1] = t;
}
}
}
}
private static String foodAverage()
{
double average = 0.0;
double totalMaxAmount = 0;
double totalConsumption = 0;
String averageFood = "";
for (int i = 0 ; i < gerbilAttributes.length;i++)
{
for(int j = 0; j < maxAmount.length; j++)
{
totalMaxAmount += maxAmount[j];
}
totalConsumption += gerbilAttributes[i].getConsumption();
average = totalConsumption/totalMaxAmount*100;
averageFood += gerbilAttributes[i].getID() + "(" + gerbilAttributes[i].getName() + ")" + Math.round(average) + "%\n";
totalMaxAmount = 0;
totalConsumption = 0;
}
return averageFood;
}
private static Gerbil searchForGerbil (String x) {
for (Gerbil l: gerbilAttributes){
if (l.getID().equals(x)){
return l;
}
}
return null;
} }

Hangman Game Finding Duplicates

So far I have got it find single characters and it even finishes with amount of guess and shows you the guessed word. But I cant get it finding duplicates :( any ideas guys.
Here's my code.
import java.util.*;
public class Hangman
{
public static void main (String[] args)
{
String tempGuess;
char blank = '_';
int amountOfGuesses = 0;
Scanner k = new Scanner(System.in);
System.out.print("Please Enter A Word : ");
String guessWord = k.nextLine();
char[] myArray = guessWord.toCharArray();
for (int i = 0; i < guessWord.length(); i++)
{
myArray[i] = blank;
}
System.out.println(myArray);
boolean whilerun = true;
while (whilerun == true)
{
System.out.print("Please Guess A Letter : ");
String guessLetter = k.nextLine();
amountOfGuesses = amountOfGuesses + 1;
int tempLG = guessWord.indexOf(guessLetter);
if (tempLG == -1)
{
System.out.println("Character Not In Word");
}
else
{
myArray[tempLG] = guessWord.charAt(tempLG);
}
System.out.println(myArray);
String tempGW = new String(myArray);
if (tempGW.equalsIgnoreCase(guessWord))
{
whilerun = false;
}
}
System.out.print("Well Done You Guessed The Word In " + amountOfGuesses + " trys.");
}
}
Thanks guys.
Change your else statement to the following if you want the code to notify you on duplicate entries.
else {
String val = String.valueOf(myArray);
if(val.contains(guessLetter)) {
System.out.println("Char already found");
}
myArray[tempLG] = guessWord.charAt(tempLG);
}
/*
* graphs - Hangman.java, Nov 18, 2013 6:08:55 PM
*
/
import java.util.;
/**
* The Class Hangman.
*
* #author Rajakrishna V. Reddy
* #version 1.0
*
*/
public class Hangman
{
/**
* The main method.
*
* #param args
* the arguments
*/
public static void main(String[] args)
{
String tempGuess;
char blank = '_';
int amountOfGuesses = 0;
final Map<String, Integer> duplicateCharIndexMap = new HashMap<String, Integer>();
Scanner k = new Scanner(System.in);
System.out.print("Please Enter A Word : ");
String guessWord = k.nextLine();
char[] myArray = guessWord.toCharArray();
for (int i = 0; i < guessWord.length(); i++)
{
myArray[i] = blank;
}
System.out.println(myArray);
boolean whilerun = true;
while (whilerun)
{
System.out.print("Please Guess A Letter : ");
String guessLetter = k.nextLine();
amountOfGuesses = amountOfGuesses + 1;
final int tempLG = guessWord.indexOf(guessLetter, duplicateCharIndexMap.get(guessLetter) == null ? 0
: duplicateCharIndexMap.get(guessLetter));
if (tempLG == -1)
{
System.out.println("Character Not In Word");
}
else
{
duplicateCharIndexMap.put(guessLetter, tempLG + 1);
myArray[tempLG] = guessWord.charAt(tempLG);
}
System.out.println(myArray);
String tempGW = new String(myArray);
if (tempGW.equalsIgnoreCase(guessWord))
{
whilerun = false;
}
}
System.out.print("Well Done You Guessed The Word In " + amountOfGuesses + " trys.");
}
}
package com.hangman;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Hangman
{
/**
* The main method.
*
* #param args
* the arguments
*/
public static void main(String[] args)
{
String tempGuess;
char blank = '_';
int amountOfGuesses = 0;
final Map<String, Integer> duplicateCharIndexMap = new HashMap<String, Integer>();
Scanner k = new Scanner(System.in);
System.out.print("Please Enter A Word : ");
String guessWord = k.nextLine();
char[] myArray = guessWord.toCharArray();
for (int i = 0; i < guessWord.length(); i++)
{
myArray[i] = blank;
}
System.out.println(myArray);
boolean whilerun = true;
boolean duplicateFlag = false;
while (whilerun)
{
duplicateFlag = true;
System.out.print("Please Guess A Letter : ");
String guessLetter = k.nextLine();
amountOfGuesses = amountOfGuesses + 1;
while (duplicateFlag)
{
final int tempLG = guessWord.indexOf(guessLetter, duplicateCharIndexMap.get(guessLetter) == null ? 0
: duplicateCharIndexMap.get(guessLetter));
if (tempLG == -1)
{
System.out.println("Character Not In Word");
duplicateFlag = false;
}
else
{
duplicateCharIndexMap.put(guessLetter, tempLG + 1);
myArray[tempLG] = guessWord.charAt(tempLG);
}
}
System.out.println(myArray);
String tempGW = new String(myArray);
if (tempGW.equalsIgnoreCase(guessWord))
{
whilerun = false;
}
}
System.out.print("Well Done You Guessed The Word In " + amountOfGuesses + " trys.");
}
}

Categories