Java Homework - File Encryption - java

String letters = "abcdefghijklmnopqrstuvwxyz";
String enc = "kngcadsxbvfhjtiumylzqropwe";
Hello, for my homework assignment I have to write a program that encodes or decodes a File, and then encodes or decodes the File using the mapping above. So for example, every 'a' becomes a 'k' when encoding a text, and every 'k' becomes an 'a' when decoding. Same concept if it is capital, and numbers and other characters are not encoded and remain the same.
Now the problem I am having is how to get the index of each character from the file and then correspond it to the index of the encrypt array. As you can see, I was using a switch statement but that is just going to take forever and I know there has to be something in the api that can help me with this I just can't find anything. Thanks in advance!
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Encode {
public static void main(String[] args) throws FileNotFoundException
{
char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char[] decryption = {'k','n','g','c','a','d','s','x','b','v','f','h','j','t','i','u','m','y','l','z','q','r','o','p','w','e'};
char[] alphabetLower = new char [26];
char[] alphabetUpper = new char[26];
char[] decryptedPassword = new char[26];
/* for(int i=0; i<decryptedPassword.length; i++)
{
decryptedPassword[i] = '';
}*/
//add the letters of the alphabet to alphabet lower
for(int i=0; i<alphabet.length; i++)
{
alphabetLower[i] = alphabet[i];
}
//add the letters of the alphabet to alphabetdecryptedPassword
for(int i=0; i<alphabet.length; i++)
{
alphabetUpper[i] = Character.toUpperCase(alphabet[i]);
}
Scanner input = new Scanner(System.in); //scanner for input file name
String filePath = "C:/Users/omid/Desktop/";
System.out.println("Please enter the file name for which you want to decode");
String fileName = "password"; //input.nextLine();
String file = filePath + fileName + ".txt";
System.out.println("File name entered: " + file);
//import file
File fileEncrypted = new File(file);
Scanner in = new Scanner(fileEncrypted);
String document = "";
//store entire password in document
while(in.hasNextLine())
{
document = in.nextLine();
}
in.close();
System.out.println("password normal: " + document);
char[] letters = new char[document.length()];
for(int i = 0; i<document.length(); i++)
{
letters[i] = document.charAt(i);
}
for(int i=0; i<letters.length; i++)
{
System.out.println(letters[i]);
}
/*
for(int i=0; i<letters.length; i++)
{
switch(letters[i])
{
case 'a':
decryptedPassword[0] = decryption[0];
break;
case 'A':
decryptedPassword[0] = decryption[0];
break;
case 'b':
decryptedPassword[1] = decryption[1];
break;
case 'B':
decryptedPassword[1] = decryption[1];
break;
case 'c':
decryptedPassword[2] = decryption[2];
break;
case 'C':
decryptedPassword[2] = decryption[2];
break;
case 'd':
decryptedPassword[3] = decryption[3];
break;
case 'D':
decryptedPassword[3] = decryption[4];
break;
case 'e':
decryptedPassword[4] += 1;
break;
case 'E':
decryptedPassword[4] +=1;
break;
case 'f':
decryptedPassword[5] += 1;
break;
case 'F':
decryptedPassword[5] +=1;
break;
case 'g':
decryptedPassword[6] +=1;
break;
case 'G':
decryptedPassword[6] +=1;
break;
case 'h':
decryptedPassword[7] +=1;
break;
case 'H':
decryptedPassword[7] +=1;
break;
case 'i':
decryptedPassword[8] +=1;
break;
case 'I':
decryptedPassword[8] +=1;
break;
case 'j':
decryptedPassword[9] +=1;
break;
case 'J':
decryptedPassword[9] +=1;
break;
case 'k':
decryptedPassword[10] +=1;
break;
case 'K':
decryptedPassword[10] +=1;
break;
case 'l':
decryptedPassword[11] +=1;
break;
case 'L':
decryptedPassword[11] +=1;
break;
case'm':
decryptedPassword[12] +=1;
break;
case 'M':
decryptedPassword[12] +=1;
break;
case'n':
decryptedPassword[13] += 1;
break;
case 'N':
decryptedPassword[13] +=1;
break;
case'o':
decryptedPassword[14] +=1;
break;
case 'O':
decryptedPassword[14] +=1;
break;
case'p':
decryptedPassword[15] +=1;
break;
case 'P':
decryptedPassword[15] +=1;
break;
case'q':
decryptedPassword[16] +=1;
break;
case 'Q':
decryptedPassword[16] +=1;
break;
case'r':
decryptedPassword[17] +=1;
break;
case 'R':
decryptedPassword[17] +=1;
break;
case's':
decryptedPassword[18] +=1;
break;
case 'S':
decryptedPassword[18] +=1;
break;
case't':
decryptedPassword[19] +=1;
break;
case 'T':
decryptedPassword[19] +=1;
break;
case'u':
decryptedPassword[20] +=1;
break;
case 'U':
decryptedPassword[20] +=1;
break;
case'v':
decryptedPassword[21] +=1;
break;
case 'V':
decryptedPassword[21] +=1;
break;
case'w':
decryptedPassword[22] +=1;
break;
case 'W':
decryptedPassword[22] +=1;
break;
case'x':
decryptedPassword[23] +=1;
break;
case 'X':
decryptedPassword[23] +=1;
break;
case'y':
decryptedPassword[24] +=1;
break;
case 'Y':
decryptedPassword[24] +=1;
break;
case'z':
decryptedPassword[26] +=1;
break;
case 'Z':
decryptedPassword[26] +=1;
break;
}
}
*/
/*for(int i=0; i<decryptedPassword.length; i++)
{
System.out.println("password decrypted: " + decryptedPassword);
}*/
}
private static String split(String string) {
// TODO Auto-generated method stub
return null;
}
}

You can try using a hash structure. Essentially each character maps in a 1 to 1 mapping to every other character, so that fits nicely into a hashtable or hashmap structure. Rather than using a switch statement, just look up the character in the map.
HashMap<Character, Character> encryptionMap = new HashMap<Character,Character>();
for (char c : alphabet) {
for (char d: decryption) {
encryptionMap.put(c,d);
}
}
....
char nextChar = "a";
char encryptedChar = encryptionMap.get(nextChar);
You'll need an encryptionMap and a decryptionMap in the other direction (decryption > alphabet).

You should consider reading your file using BufferedReader but that's a different problem. As far as encoding a character without using switch, consider that a character is encoded internally as an integer. You can Google "Ascii Table" to see how each character is encoded. For example, 'A' is encoded as 65 and 'a' is encoded as 97. You can use this to your advantage to index into your alphabet and decryption arrays. If your character is uppercase, we subtract 65 from it to get the index of that character in the array. So 'A' becomes 0, 'B' becomes 1, etc. Similarly if the letter is lowercase, we subtract 97 from it.
For example lets assume that ch contains the letter you want to decode:
int index = -1;
//ch is between A and Z
if (ch >= 65 && ch <= 90){
index = ch - 65;
} else if (ch >= 97 &7 ch <= 122){//ch is between a and z
index = ch - 97;
}
if (index > -1){
char encodedChar = decryption[index];
}

Related

Calculate Points from Letters in a Switch Case

I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pointsproblem;
/**
*
*/
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PointsProblem {
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
//create new object//
PointsProblem task1 = new PointsProblem();
File file = new File("dictionary.txt");
// read the file//
Scanner input = new Scanner(file);
//check if file can be found//
if (!file.isFile()) {
System.err.println("Cannot open file: " + input);
System.exit(0);
}
else {
System.out.println("Successfully opened file: " + input + ".");
}
//read all the lines in the file//
{
while (input.hasNext()) {
String word = input.nextLine();
System.out.println(word);
System.out.println("'" + input + "' is worth " + point + " points");
int point = "";
switch(point) {
case 'a': = "1":
case 'e': = "1";
case 'i': = "1";
case 'l': = "1";
case 'n': = "1";
case 'o': = "1";
case 'r': = "1";
case 's': = "1";
case 't': = "1";
case 'u': = "1";
case 'g': = "2";
case 'g': = "2";
case 'b': = "3";
case 'm': = "3";
case 'c': = "3";
case 'p': = "3";
case 'f': = "4";
case 'h': = "4";
case 'v': = "4";
case 'w': = "4";
case 'y': = "4";
case 'k': = "5";
case 'j': = "8";
case 'x': = "8";
case 'q': = "10";
case 'z': = "10";
return score = point + "";
}//end switch
}//end point calculation loop
public int getScore() {
return score;
}
//public boolean containsLetter(Character letter) {
//return points.contains(letter);//
}
I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.
Looks like a Map<Character, Integer> would fit:
public class PointsProblem {
final Map<Character, Integer> pointsMap = Map.of(
'a', 1,
'e', 1,
//.......
'z', 10
);
Then, in your function, simply use the map to find the corresponding point for each character:
int wordPoints = 0;
for(char c : word.toCharArray())
wordPoints += pointsMap.get(c);
Use a map to store the values:
Map<Character, Integer> charValues = new HashMap();
charValues.put('a', 2);
charValues.put('b', 1);
You can use the chars() and collect as sum
int total = word.chars()
.mapToObj(c -> charValues.get((char)c))
.mapToInt(i -> (int)i)
.sum();
But according to your use case you can count the chars first and then multiply
Map<Character, Integer> counter = new HashMap<>();
while (input.hasNext()) {
String word = input.next();
word.chars().forEach(c -> counter.compute(c, (k, v) -> v == null ? 1 : v + 1));
}
counter.entrySet()
.stream()
.mapToInt(e -> charValues.get(e.getKey())*e.getValue())
.sum();
if you are using switch your code will look like:
int total = 0;
switch (c){
case 'a' : total += 1; break;
case 'b' : total += 2; break;
}
I'm not sure that the code you've shown us will compile. There are a few things you need to change;
1) You're setting a String to an int. You'll want to change that to
int point = 0
2) You aren't setting anything in the switch statement
Change case 'a': = "1": to case 'a': point = 1;
3) You will never set a unique value in the switch statement because you aren't using 'break'
Checkout this page for a good tutorial: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Basically without any break statements, your code will go through the of the statements and point will just be assigned to your last case
You want to have something along the lines of
switch(char) {
case 'a': point = 1;
break;
case 'e': point = 1;
break;
// etc.
default: point = 1; // maybe throw an error or add some logging for the default case
break;
}
return point;
I am presuming that you actually have this switch statement in it's own method and not in main as you've shown us above, otherwise the return statement won't help you.
You can also shorten this so that each case simply returns a value (again, if this is in it's own method), i.e.
switch(char) {
case 'a': return 1;
case 'b': return 1;
// etc.
}
edit:
The best way to get the point value of the whole word via a switch statement is:
char[] chars = word.toCharArray();
int point=0;
for (char c: chars) {
switch(c) {
case 'a':
point += 1;
break;
// etc.
}
}
System.out.println("Total point value of word '" + word + "' was " + point);
Instead of assigning individually for each 'case' statement, you can also use the fall through feature of the switch block.
int calcScore(String str)
{
int score = 0;
for(int i=0; i<str.length(); i++)
{
switch(str.charAt(i)) {
case 'a':
case 'e':
case 'i':
case 'l':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u': score += 1; break;
case 'g': score += 2; break;
case 'b':
case 'm':
case 'c':
case 'p': score += 3; break;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y': score += 4; break;
case 'k': score += 5; break;
case 'j':
case 'x': score += 8; break;
case 'q':
case 'z': score += 10; break;
}
}
return score;
}
This function can be called for each word.
Thanks everyone, I ended up with the following code which gives the output I am after;
System.out.println("Points problem");
File file = new File("dictionary.txt");
// read the file//
Scanner input = new Scanner(file);
//check if file can be found//
if (!file.isFile()) {
System.err.println("Cannot open file: " + file);
System.exit(0);
} else {
System.out.println("Successfully opened file: " + file + ".");
}
//read all the lines in the file//
while (input.hasNext()) {
String word = input.nextLine();
//System.out.println(word);
int l = word.length();
int point = 0;
for (int x = 0; x < l; x++) {
char c = word.charAt(x);
switch (c) {
case 'a':
case 'e':
case 'i':
case 'l':
case 'n':
case 'o':
case 'r':
case 's':
case 't':
case 'u':
point += 1;
break;
case 'd':
case 'g':
point += 2;
break;
case 'b':
case 'c':
case 'm':
case 'p':
point += 3;
break;
case 'f':
case 'h':
case 'v':
case 'w':
case 'y':
point += 4;
break;
case 'k':
point += 5;
break;
case 'j':
case 'x':
point += 8;
break;
case 'q':
case 'z':
point += 10;
break;
}//end switch*/
}//end point calculation loop
System.out.println(word + "is worth " + point + " points." );
}

the output should display a hyphen (-) after the first 3 digits and subsequently a hyphen after every 4 digits

I have an assignment but i couldn't complete this question.
Previously I add inserted else if (counter == 7) { break; } after the counter==3 but I had removed since the question said to process as many digits as the user wants.
I do not know how to add to count every 4 digit for dash after the first 3 digits dash.
the code below is what I have.
please help and explain to me if possible. thanks :)
import java.util.Scanner;
public class question1 {
public static void main (String [] args)
{
boolean notletter = false;
Scanner console = new Scanner(System.in);
String phoneletter = "";
int counter = 0;
System.out.print("Enter a phone number in letters only: ");
String phoneNumber = console.nextLine();
String phnum2 = phoneNumber.replaceAll(" ", "");
for (int i = 0; i <= phnum2.length() - 1; i++) {
if (!(Character.isLetter(phnum2.charAt(i)))) {
notletter = true;
break;
}
{
switch (Character.toUpperCase(phnum2.charAt(i))) {
case 'A':
case 'B':
case 'C':
phoneletter = phoneletter + "2";
break;
case 'D':
case 'E':
case 'F':
phoneletter = phoneletter + "3";
break;
case 'G':
case 'H':
case 'I':
phoneletter = phoneletter + "4";
break;
case 'J':
case 'K':
case 'L':
phoneletter = phoneletter + "5";
break;
case 'M':
case 'N':
case 'O':
phoneletter = phoneletter + "6";
break;
case 'P':
case 'Q':
case 'R':
case 'S':
phoneletter = phoneletter + "7";
break;
case 'T':
case 'U':
case 'V':
phoneletter = phoneletter + "8";
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
phoneletter = phoneletter + "9";
break;
}
counter++;
if (counter ==3) {
phoneletter = phoneletter + "-";
}
}
}
if (notletter == true) {
System.out.println("Please indicate only alphabets");
} else {
System.out.println(phoneletter);
}
}
}
This can be done by editing the if-statement at the end of your code:
if (counter ==3) {
phoneletter = phoneletter + "-";
}
Here you already checked if the counter is three. If it is, add a hyphen. The next thing to do is to check the case of "a hyphen after every 4 digits". To do this, we can check if counter - 3 is a multiple of 4:
(counter - 3) % 4 == 0
However, this would make it insert an extra - at the end of the output if (input length - 1) is a multiple of 4. So we shouldn't add a hyphen if we reached the end of the string. This can be done by checking whether i is phnom.length() - 1:
i != phnom.length() - 1
If we combine all these conditions together, we get
if (counter == 3 || ((counter - 3) % 4 == 0 && i != phnom.length() - 1)) {
Note: This can actually be done using a regular expression, but since this is homework, I doubt this approach will be accepted. Here is how you do this with regex:
// phoneLetter is a string of digits without any hyphens
String result = phoneLetter.replaceAll("^\\d{3}|\\d{4}(?!$)", "$0-");

Java: Lighter code for encryption

I'm trying to get a program to encrypt a message using Cesar's Cypher, which involves replacing every character of a string with the letter, whose code is the code of the replaced letter plus 3. For e.g., if the letter is A, then it has to be replaced with D, because the code of D is the code of A plus 3. The letters are case-sensitive. The code I thought of uses a really heavy switch construct, I was wondering, if you could help me to make it more straight forward.
Here's the code I use for the encryption method:
public class Util
{
public static String Encript(String stringa)
{
char[] stringaArray=stringa.toCharArray();
for (int i =0; i<stringaArray.length; i++)
{
switch (stringaArray[i])
{
case 'a':
stringaArray[i]=('D');
break;
case 'b':
stringaArray[i]='E';
break;
case 'c':
stringaArray[i]='F';
case 'd':
stringaArray[i]='G';
break;
case 'e':
stringaArray[i]='H';
break;
case 'f':
stringaArray[i]='I';
break;
case 'g':
stringaArray[i]='J';
break;
case 'h':
stringaArray[i]='K';
break;
case 'i':
stringaArray[i]='L';
break;
case 'j':
stringaArray[i]='M';
break;
case 'k':
stringaArray[i]='N';
break;
case 'l':
stringaArray[i]='O';
break;
case 'm':
stringaArray[i]='P';
break;
case 'n':
stringaArray[i]='Q';
break;
case 'o':
stringaArray[i]='R';
break;
case 'p':
stringaArray[i]='S';
break;
case 'q':
stringaArray[i]='T';
break;
case 'r':
stringaArray[i]='U';
break;
case 's':
stringaArray[i]='V';
break;
case 't':
stringaArray[i]='W';
break;
case 'u':
stringaArray[i]='X';
break;
case 'v':
stringaArray[i]='Y';
break;
case 'w':
stringaArray[i]='Z';
break;
case 'x':
stringaArray[i]='A';
break;
case 'y':
stringaArray[i]='B';
break;
case 'z':
stringaArray[i]='C';
break;
}
}
String encripted= new String(stringaArray);
return encripted;
}
}
Then I use this method in the graphical interface class so that it acts when a button is pressed like this:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
String stringa=messageTxt.getText();
encriptedTxt.setText(Util.Encript(stringa, encriptedTxt));
}
Here is an example of test-case:
Test case:
aBxyE //Input
dEabH //Output
Thank you in advance!
Khoor/#Zruog
You could iterate the characters in the String, and I would also pass in the key offset. Create a StringBuilder and append each character after performing integer addition and casting. Something like,
public static String encrypt(String msg, int key) {
StringBuilder sb = new StringBuilder();
for (char ch : msg.toCharArray()) {
char c = (char) (ch + key);
sb.append(c);
}
return sb.toString();
}
Decryption is trivial with a Caesar cipher; you can call encrypt with the negative value of the key
public static String decrypt(String msg, int key) {
return encrypt(msg, -key);
}
And I tested my example with
public static void main(String[] args) {
String msg = encrypt("Hello, World", 3);
System.out.println(msg);
System.out.println(decrypt(msg, 3));
}
Finally, as others have noted, the Caesar cipher is terribly insecure (because letter frequency is not perturbed, it's trivial in a modern sense).
This code will sawp a char with another one three chars apart, as defined in ALPHABET :
public class Util
{
private final static String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public static String encript(String stringa)
{
char[] stringaArray = stringa.toCharArray();
for (int i =0; i<stringaArray.length; i++) {
char c = stringaArray[i];
int index = ALPHABET.indexOf(c);
if(index <0)
{
continue ; //if c does not appear in ALPHABET
}
// for example c is *, leave it unchanged
if((index +3) >= ALPHABET.length() ) {
index = index - ALPHABET.length();
}
stringaArray[i] = ALPHABET.charAt(index+3);
}
String encripted= new String(stringaArray);
return encripted;
}
}
If it is not clear, do not hesitate to ask.
Here is my Short and Efficient code for your program:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//N is length of string
int N = Integer.parseInt(br.readLine());
//Reading string Input
String str = br.readLine();
//K is the key to rotate characters in the string
//In your case K = 3
int K = Integer.parseInt(br.readLine());
K %= 26; //Incase K is greater than 25
//Main [tag:algorithm]
for(int i = 0; i < N; i++){
char c = str.charAt(i);
if(c >= 65 && c <= 90){
c += K;
if(c > 90){
c = (char)(c - 90 + 64);
}
}
if(c >= 97 && c <= 122){
c += K;
if(c > 122){
c = (char)(c - 122 + 96);
}
}
System.out.print(c);
}
}
}
I am doing k = k % 26 because if the k = 26 then it will print the same letter, if k = 27 the character will rotate only 1 time and so on.

encryption using Caesar Cipher with given methods..Java

Am trying to create a method to encrypt a word with Caesar cipher
here is the code:
public static void main (String [] args)
{
String s = "ahmed";
int k = 2;
char[] c = new char[5];
int[] a = new int[s.length()];
for (int i = 0; i<s.length();i++){
a[i] = Secret_Code_Library.getDigit(s.charAt(i));
a[i] = i + k ;
c[i] = Secret_Code_Library.getLetter(a[i]);
}
String ss = String.valueOf(c);
}
Secret_Code_Library is a class that contains the two methods
(getDigit(char): returns the number of the character a =0, b= 1...etc, and
getLetter(int): returns the letter corresponding to the number).
my problem is when ever i try to encrypt a word it encrypts only
the first letter correctly and save it in to the array a.
P.S: I have to use those two methods.
the output of the above code is: cdefg
while it should be: cjogf
this is the class :
public class Secret_Code_Library {
public static final char [] LETTERS={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
public static char getLetter(int digit){
return LETTERS[digit]; }
public static int getDigit(char ch){
int digit=0;
switch (ch){
case 'A': digit=0; break; case 'B': digit=1; break; case 'C': digit=2; break;
case 'D': digit=3; break; case 'E': digit=4; break; case 'F': digit=5; break;
case 'G': digit=6; break; case 'H': digit=7; break; case 'I': digit=8; break;
case 'J': digit=9; break; case 'K': digit=10; break; case 'L': digit=11; break;
case 'M': digit=12; break; case 'N': digit=13; break; case 'O': digit=14; break;
case 'P': digit=15; break; case 'Q': digit=16; break; case 'R': digit=17; break;
case 'S': digit=18; break; case 'T': digit=19; break; case 'U': digit=20; break;
case 'V': digit=21; break; case 'W': digit=22; break; case 'X': digit=23; break;
case 'Y': digit=24; break; case 'Z': digit=25; break;
}// switch
return digit;
}}
a[i]= i + k ;
should be
a[i] = a[i] + k;
because you're not adding the key to the position of the current encrypted character, but the integer value of the character itself.
But that is not enough. What happens when you're encrypting 'z' with k = 2? You should wrap around in the alphabet, if the Secret_Code_Library.getLetter(a[i]); doesn't already do this for you.
If your alphabet is 26 characters long, then this should do it:
a[i] = (a[i] + k) % 26;

Convertion of numeros

I just saw some of my work today, and i want to enter the user how many alphabet they want and continue converting. Can i have help? It would be fantastic. I tried anything. I'm just new in java programming that's why. Thanks :)
This is my whole programming
import java.util.Scanner;
public class Try2 {
public static void main(String[] args) {
int counter = 0;
int it = 0;
Scanner keyboard = new Scanner(System. in );
System.out.println("Enter words to digits: ");
String alpha = keyboard.nextLine();
alpha = alpha.toLowerCase();
String num = (" ");
while (counter < alpha.length()) {
switch (alpha.charAt(it)) {
case 'A':
case 'a':
case 'B':
case 'b':
case 'c':
case 'C':
num += "2";
counter++;
break;
case 'D':
case 'E':
case 'F':
case 'd':
case 'e':
case 'f':
num += "3";
counter++;
break;
case 'G':
case 'H':
case 'I':
case 'g':
case 'h':
case 'i':
num += "4";
counter++;
break;
case 'J':
case 'K':
case 'L':
case 'j':
case 'k':
case 'l':
num += "5";
counter++;
break;
case 'M':
case 'N':
case 'O':
case 'm':
case 'n':
case 'o':
num += "6";
counter++;
break;
case 'P':
case 'R':
case 'S':
case 'p':
case 'r':
case 's':
num += "7";
counter++;
break;
case 'T':
case 'U':
case 'V':
case 't':
case 'u':
case 'v':
num += "8";
counter++;
break;
case 'W':
case 'w':
case 'X':
case 'x':
case 'Y':
case 'y':
case 'Z':
case 'z':
case ' ':
num += "9";
counter++;
break;
}
if ((counter % 4) == 3) {
num += "-";
}
it++;
}
System.out.println(num);
}
}
You can wrap the read line code with another while loop:
Scanner keyboard = new Scanner(System.in);
while(true) {
System.out.println("Enter words to digits: ");
String alpha = keyboard.nextLine();
alpha = alpha.toLowerCase();
String num = " ";
int counter = 0;
int it = 0;
while (counter < alpha.length()) {
...
}
//new line (optional)
num += "\n";
}
You can check if the user entered a flag to end input:
//You can choose any flag you want
if(alpha.equals("finish")) {
break;
}
About your switch:
You can remove all the upper case letters because you wrote: alpha = alpha.toLowerCase();
You forgot 'q'
If alpha don't match: [a-zA-z ] (contains only letters and spaces) an IndexOutOfBoundsException will be thrown from alpha.charAt(it) because you don't increase counter and the loop don't exit in time.
To prevent the last problem you can remove counter and it and change the while loop to for loop:
for (int i = 0; i < alpha.length(); i++) {
if ((i % 4) == 3) {
num += "-";
}
switch (alpha.charAt(i)) {
...
}
}

Categories

Resources