Caesar Shift Cipher, input exception error [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I was having some issues with this originally, but found some different help on here. now I seem to be having an issue with an input exception error. I believe I have the correct formatting for the input.
import java.util.Scanner;
public class CaesarShift
{
//initialize private string for the alphabet
private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
//public encryption code
public String encryptionMethod(String normText, int caesarShift)
{
normText = normText.toLowerCase();
String cipherText = "";
for (int a = 0; a < normText.length(); a++)
{
int charP = ALPHABET.indexOf(normText.charAt(a));
int shiftValue = (caesarShift + charP) % 26;
char replaceValue = this.ALPHABET.charAt(shiftValue);
cipherText += replaceValue;
}
return cipherText;
}
public String decryptionMethod(String cipherText,int caesarShift)
{
cipherText = cipherText.toLowerCase();
String normText = "";
for (int a = 0; a < cipherText.length(); a++)
{
int charP = this.ALPHABET.indexOf(cipherText.charAt(a));
int keyValue = (charP - caesarShift) % 26;
if(keyValue < 0)
{
keyValue = this.ALPHABET.length() + keyValue;
}
char replaceValue = this.ALPHABET.charAt(keyValue);
normText += replaceValue;
}
return normText;
}
}
Then I have the tester method it where i am having the actual issue of the input exception error
import java.util.Scanner;
public class CaesarShiftTester
{
public static void main(String args[])
{
//import of the scanner method to ask the user for the input they would like
Scanner in = new Scanner(System.in);
System.out.println("What is the text you would like to do something with?");
String normText = in.next();
System.out.println("What is the Caesar Shift Value?");
int caesarShift = in.nextInt();
//new declaration of the CaesarShift class to report back to easily
CaesarShift shift = new CaesarShift();
//decalre the need properties for the encryption
String cipherText = shift.encryptionMethod(normText, caesarShift);
System.out.println("Your normal text is: " + normText);
System.out.println("Your text after encryption is: " + cipherText);
String cnormText = shift.decryptionMethod(cipherText, caesarShift);
System.out.println("Your encrypted text is: " + cipherText);
System.out.println("Your decrypte text is: " + cnormText);
}
}
Sorry for the somewhat messy code, I typically do clean up when a program is done and working.

Your program should work OK if you input only 1 word. If you include spaces, exception appears. The problem is on line
String normText = in.next();
It should be
String normText = in.nextLine();
to get the whole line as input text. next() doesn't work as you expected because
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace.
So it matched only the first word and tried to parse the next word as an int (because of your next line int caesarShift = in.nextInt();)
Some other points:
in your encryption/decryption methods, you should check if the input char is a letter (e.g. using Character.isLetter()) and shift only those chars (currently, it won't find space in ALPHABET so indexOf returns -1)
using StringBuilder when concatenating Strings in a loop, it's faster

Related

How to replace multiple occurences of a character in a java string using replace and charAt methods

This is my second question here and still a beginner so please bear with me.
I have this code of a very basic hangman type game.I have changed the characters to "-",I am able to get the indices of the input but I am not able to convert back the "-" to the characters entered.
Its an incomplete code.
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
for (int j=0;j<10;j++){ //Asks 10 times for user input
input = inpscanner.nextLine();
int check = line.indexOf(input);
while (check>=0){
//System.out.println(check);
System.out.println(encrypt.replaceAll("-",input).charAt(check));
check = line.indexOf(input,check+1);
}
Here is how it looks like:
You have 10 chances to guess the movie
------
o
o
o
L
L
u //no repeat because u isn't in the movie.While 'o' is 2 times.
I would like to have it like loo---(looper).
How can I do like this "[^ ]","-" in case of a variable?
This might help.
public static void main(String[] args) {
String line = "xyzwrdxyrs";
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
System.out.println(line);
Scanner scanner = new Scanner(System.in);
for (int j=0;j<10;j++) { //Asks 10 times for user input
input = scanner.nextLine();
//int check = line.indexOf(input);
int pos = -1;
int startIndex = 0;
//loop until you all positions of 'input' in 'line'
while ((pos = line.indexOf(input,startIndex)) != -1) {
//System.out.println(check);
// you need to construct a new string using substring and replacing character at position
encrypt = encrypt.substring(0, pos) + input + encrypt.substring(pos + 1);
//check = line.indexOf(input, check + 1);
startIndex = pos+1;//increment the startIndex,so we will start searching from next character
}
System.out.println(encrypt);
}
}

Finding the number of occurances of a letter within a word in java

So first of all, hello everyone this is my first time stackoverflow as a question asker and I know you folks don't like people asking homework questions on here but I've been struggling with this for about a week now and have given it several reasonable attempts so I actually need help here and am not just trying to mooch answers off you amazing coders :)
So my task at hand is I'm trying (the language is java btw) to find the number of times a letter (which the user inputs) occurs in a word (which the user also picks, and then to output the number of time that word occurs, for example: the word hello has two 'l's in it.. it should be pretty easy but for some reason I can't get it :/
I believe using my current code the variable "let" gets turned into an ascii character and idk what to do with that, or rather how I should compare it with all the other characters in the word.
Please help :)
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String word = "";
String letter;
int limit = 0;
String input = null;
String let;
int count = 0;
int j = 0;
while(limit == 0){
System.out.println("Type a word.");
word = scan.nextLine();
System.out.println("Type a single letter.");
letter = scan.nextLine();
let = letter.substring(0,1);
char car;
while(j<word.length()){
car = word.charAt(j);
for(int x=1; x==j; x++){
if(let.charAt(0)==car){
count ++;
}
}
j+=1;
}
System.out.println(count + " " + "occurances.");
}
}
}
Here is a sample code that should work
import java.util.Scanner;
public class LetterCounter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type a word.");
String word = scan.nextLine();
System.out.println("Type a single letter.");
String letter = scan.nextLine();
char let = letter.charAt(0);
int count = 0;
for (char char1: word.toCharArray()) {
if (char1 == let) {
count++;
}
}
System.out.println(count + " " + "occurrences.");
}
}
Here is the test output
Type a word.
letter
Type a single letter.
t
2 occurrences.

Java Array Manipulation and Bugfixing

I'm working my way through a java learning book and at the moment I'm learning about arrays and vectors. I've been doing ok up until now I've been stuck on this question for ages and have no idea how to tackle it, my head is about to explode!
The questions for this certain program I have to tackle are:
Elementary error checking is introduced, specifically check that the array Tokens has two elements, if there is a problem with the format of the data inform the user but carry on accepting input.
It will accept input of either
quit
put name mark
get name
The quit scenario works as before, the second scenario stores the student and their mark at the next
available array index; whilst get just returns the mark of any student who matched to the name ( there
may be more than one such student, there many be none).
The program reads in the mark as an integer not a String (you can find examples of the structure you
need by searching for Integer.parseInt on Google).
Upon typing quit, the mean mark, and the highest mark are also displayed.
The java code is as follows:
import java.util.Scanner;
public class ArrayInput {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String b;
String student[] = new String[50];
String mark[] = new String[50];
int i = 0;
while ((b = s.nextLine()) != null) {
if (b.equals("quit")) break;
String Tokens[] = b.split(' ');
// System.out.println(Tokens[0] + ' ' + Tokens[1]);
student[i] = Tokens[0];
mark[i] = Tokens[1];
i++;
}
for (int j = 0; j < i; j++) {
System.out.println(student[j] + ' ' + mark[j]);
}
}
}
It also throws out on error on this line:
String Tokens[] = b.split(' ');
use:
b.split("\\s+");
to split on whitespaces.
This will cause any number of consecutive spaces to split your string into tokens as the split() method in java is constructed to be used with regular expressions anyway
I would've written it like this (tried it on IDEONE):
import java.util.Scanner;
public class ArrayInput {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String b;
String[] student = new String[50]; // changed here
String[] mark = new String[50]; // Changed here
int i = 0;
b = s.nextLine(); // Get the next line here first
while (b != null) { // Evalaute b as for while loop here
if (b.equals("quit")) break;
String[] Tokens = b.split(" "); // Changed to use " ", not ' '
// System.out.println(Tokens[0] + ' ' + Tokens[1]);
student[i] = Tokens[0];
mark[i] = Tokens[1];
i++;
b = s.nextLine(); // get the next line here before looping again.
}
for (int j = 0; j < i; j++) {
System.out.println(student[j] + ' ' + mark[j]);
}
}
}
The Scannerclass has a method called hasNext() which you can use quite helpfully for the while() loops. If you use that the following snippet is improved:
// b = s.nextLine() not needed anymore
while(s.hasNext()){
...
...
...
}

Char array updating

I have been working on my hangman program for far to long and cannot figure out why it is not replacing the characters entered with the asterisks.
There are a lot of details I have not added so please do not sit here and judge that. I need someone to tell my why the character the user enters is not replacing the asterisks and If you know what I could do to fix it please tell me.
I'm struggling. I have edited my program to show you where I know the logic error is coming from however I do not know what the error is.
String hiddenWord = wordList[rand];
char[] asterisks = new char[MAXCHAR];
hideWord(hiddenWord);
System.out.println(Arrays.toString(hideWord(hiddenWord)));
numGuess( hiddenWord,asterisks);
public static char[] hideWord(String hiddenWord)
{
int wordLength = hiddenWord.length();
//int length = wordLength * 2;
char[] asterisks = new char[wordLength];
for(int i=0; i < wordLength; i++)
{
asterisks[i] = '*';
}
return asterisks;
}
public static void numGuess(String hiddenWord,char[] asterisks)
{
Scanner keyboard = new Scanner(System.in);
hideWord(hiddenWord);
int remAttempts = MAXGUESS;
int i = 0;
while(i < (hiddenWord.length()-1))
{
System.out.println("Enter a letter or 9 to quit");
char guess = keyboard.next().charAt(i);
if(asterisks[i] == (hiddenWord.charAt(i)))
{
//attemtps == hiddenWord.charAt(i);
System.out.println("Nice job!");
remAttempts--;
}
i++;
}
}
Look at this code (I changed the formatting a bit):
while (i < hiddenWord.length() - 1) {
System.out.println("Enter a letter or 9 to quit");
char guess = keyboard.next().charAt(i);
//...
i++;
}
You're asking for a letter, but you really request a String with at least the size + 1 that equals i: keyboard.next().charAt(i);. Therefore, if you write just a letter, then you'll get an Exception at the second iteration of that loop.
I guess what you meant was: keyboard.next().charAt(0);. This will return the first character of the given String.
If this doesn't solve the problem, then provide the whole Stacktrace and mark the line in your code, where the Exception occurs.

How do I display a word diagonally in Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to make a program that accepts a word then displays the word diagonally. So far I've only gotten it to display vertically.
The scanner accepts "zip", then outputs:
z
i
p
How do i make it go like this:
z
i
p
Here is my code:
import java.util.Scanner;
public class exercise_4
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your words");
String word = scan.nextLine();
for (char ch: word.toCharArray())
{
System.out.println(ch);
}
}
}
You can try something like this:-
String s = "ZIP";
String spaces = "";
for (int i = 0; i < s.length(); i++) {
System.out.println(spaces + s.charAt(i));
spaces += " ";
}
You can do
String spaces = ""; // initialize spaces to blank first
for (int i = 0; i < word.length(); i++) { // loop till the length of word
spaces = spaces + " "; //
// increment spaces variable
// for first iteration, spaces = ""
// for second iteration, spaces = " "
// for third iteration, spaces = " "
// for fourth iteration, spaces = " " and so on
System.out.println(spaces + word.charAt(i));
// this will just print the spaces and the character of your word.
}
Try this
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your words");
String word = scan.nextLine();
String i = new String();
for (char ch : word.toCharArray()) {
System.out.println(i+ch);
i=i+" ";
}
I would prefer a StringBuilder for concatenation.
String s = "ZIP";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
System.out.println(sb.toString()+ s.charAt(i));
spaces.append(" ");
}
With StringUtils from commons-lang:
int indent = 0;
for (final char c : "ZIP".toCharArray()) {
System.out.println(StringUtils.repeat(" ", indent) + c);
indent++;
}

Categories

Resources