I am trying to write a piece of code that produces a letter frequency using arrays. I am getting a bit stuck on how to compare a letter in a string to a letter in an array. my basic pseudo code is as follows.
import java.util.Scanner;
public class test {
public static void main (String[]args){
Scanner sc = new Scanner (System.in);
System.out.print ("Please enter a sentence: ");
String str = sc.nextLine();
String [] let = {"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"};
Float [] freq = new Float [25];
int x,a = 0,b = 0, strCount = 0;
String str1;
str1 = str.replaceAll(" ", "");
for (x = 0; x < str1.length(); x++)
{
strCount++;
}
System.out.println("The number of Characters in the string is :" + strCount);
System.out.println();
And now I'm stuck on how to compare the str1 to the let array. I have tried the following but it has a problem with the comparing.
while (b < strCount)
{
while (a < let.length)
{
if (let[a] == str1.charAt(b))
{
freq[a] = freq[a]++ ;
}
if(let[a] != str1.charAt(b))
{
a = a++;
}
}
b = b++;
}
Any help would be much appreciated.
Thank you.
Well, I see a number of other issues but the one you're asking about is simple enough.
if (let[a].charAt(0) == str1.charAt(b)) // <-- one letter
{
freq[a]++ ;
}
else
{
a++;
}
Also, strCount = str1.length(); with no need for a loop.
You might want to get rid of the risk of eternal loops by replacing your while loops with
for
loops.
Also,
a = a++;
is incorrect, while
a++;
or
a = a+1;
is correct.
Fix those two, and you will have fixed your problem.
Let me address some of the problems that seem to stand out. First of all, you might want to enlarge your Float[] since it has a size of 25 and there are 26 letters in the alphabet, meaning you would want to do Float[] freq = new Float[26]instead. Also, you use str.replaceAll(), but str.replace() will suffice - they both replace all matches in the string.
To count the number of occurrences, you may want to use str.charAt(index) or break it up into a char array (str.toCharArray()) to compare the character with the values stored in the array. Since they are all single characters, you might also want to store the values as the primitive char instead of as a String.
The two while loops are completely unnecessary, as it can be done with the one forloop. Also, use str.length() instead of creating your own variable and using a for loop to increment strCount, especially when you specify to loop through it str.length() times...
Related
This question already has answers here:
How to join Array to String (Java)?
(6 answers)
Closed 3 months ago.
I was working on a project, and thought, Couldn't there be an easier way to write a list without having to waste 3 minutes and one line of code? I'm probably wasting even more time here, but suppose I want to spell out "Hello, world!":
class Main {
public static void main(String[] args) {
String[] array = {"H", "E", "L", "L", "O", ", ", "W", "O", "R", "L", "D", "!"};
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + "-"); // prints "H-E-L-L-O-, -W-O-R-L-D-!-"
}
}
}
As you can see there's a nagging dash hanging over the edge at the end of the line. One idea I had was doing this:
class Main {
public static void main(String[] args) {
String[] array = {"H", "E", "L", "L", "O", ", ", "W", "O", "R", "L", "D", "!"};
System.out.print(array[0]); // enter "H" early
for (int i = 1; i < array.length; i++) { // int i = 0 -> int i = 1
System.out.print("-" + array[i]); // switched order, prints "H-E-L-L-O-, -W-O-R-L-D-!"
}
}
}
Yes, this does complete the job, but I feel like the extra line is clunky and awkward in my code. Also, I don't feel it's exactly flexible?
If there's something inside the documentary junk or a trick I need, please let me know. :)
You can print the dash before the list element and if the list element is the first one, you don't print anything.
class Main {
public static void main(String[] args) {
String[] array = {"H", "E", "L", "L", "O", ", ", "W", "O", "R", "L", "D", "!"};
for (int i = 0; i < array.length; i++) {
System.out.print((i == 0 ? "" : "-") + array[i]); // prints "H-E-L-L-O-, -W-O-R-L-D-!"
}
}
}
You can use the iterator i in a ternary expression (i == array.length - 1 ? "" : "-") as a substitute for the constant "-". This way, whether or not there is a dash is dynamic, based on whatever you want. This is adaptable to lots of different scenarios.
I'm a bit stuck on how I should replace each element in char array to a number.
Here's the code I have so far:
public static void main(String []args){
String[] dialTwo = {"a", "b", "c"};
String[] dialThree = {"d", "e", "f"};
String[] dialFour = {"g", "h", "i"};
String[] dialFive = {"j", "k", "l"};
String[] dialSix = {"m", "n", "o"};
String[] dialSeven = {"p", "q", "r", "s"};
String[] dialEight = {"t", "u", "v"};
String[] dialNine = {"w", "x", "y", "z"};
Scanner in = new Scanner(System.in);
System.out.print("Enter a phone number: ");
String phoneInput = in.next();
char[] inputToArray = phoneInput.toCharArray();
while (!phoneInput.matches("^[a-pA-P0-9]*$")) {
System.out.println("Not a valid number. Try agian.");
phoneInput = in.next();
}
I was able to successfully verify the string in case someone wanted to enter ;;';';.
Thank you for your help guys.
My teacher also wants me to use method classes, but I'm slightly confused on it so I'm doing it a bit differently.
So the output I want, if someone were to input "CFG" it would print 123.
My solution would be a bit simpler.
First, I would not use those arrays but one 2D array like :
static char[][] keyboard = {
{'a','b','c'}, //2
{'d','e','f'}, //3
{'g','h','i'}, //4
{'j','k','l'}, //5
{'m','n','o'}, //6
{'p','q','r','s'}, //7
{'t','u','v'}, //8
{'w','x','y','z'} //9
};
Then, from this, I would loop on every character of the input you have. For each character, I would search on which array it is. The value you need is the index + 2. So using a simple for-loop on keyboard, you can find where is the character and print the value you want. There is exception for numeric, space and symbol of course.
for each character in input
if character is numeric
output ( toNumeric ( character ) )
else
index = 0
while character not found
if character in array[index]
output ( index + 2 )
index++
For more code, well, you need to give more information because you need to work a bit too ;)
You can use Collections instead of String[]. Probably map would be good. But, since you are using String[] following code should help:
for (int i = 0; i < inputToArray.length; i++) {
if (Arrays.asList(dialTwo).contains(inputToArray[i]))
inputToArray[i]=2;
...
}
You need to fill the ... part with other if else conditions where you check for inputToArray[i] with other arrays and replace accordingly.
A simple way to do that is to map a function to use map
inputToArray.stream().map(/*some function*/).toArray();
private void int /*your function*/(char c){...}
A little rusty on Java so can't claim the syntax is correct but basically map a function that takes a char and returns your desired int to your array. After that all you have to do is write the actual function you are mapping.
There's also a number of ways you could just parse the string returned by next as there doesn't seem to be any particular reason in your code for the conversion to a char array
It should also be mentioned that it is rather inefficient to have arrays of 1 length strings for no specific reason. You could easily use strings instead
public static void main(String[] args) {
String[] dialTwo = { "a", "b", "c" };
String[] dialThree = { "d", "e", "f" };
String[] dialFour = { "g", "h", "i" };
String[] dialFive = { "j", "k", "l" };
String[] dialSix = { "m", "n", "o" };
String[] dialSeven = { "p", "q", "r", "s" };
String[] dialEight = { "t", "u", "v" };
String[] dialNine = { "w", "x", "y", "z" };
Scanner in = new Scanner(System.in);
System.out.print("Enter a phone number: ");
String phoneInput = in.next();
char[] inputToArray = phoneInput.toCharArray();
int i = 0;
while (!phoneInput.matches("^[a-zA-Z0-9]*$")) { // Used to check if any
// special character is
// enter in phone number
System.out.println("Not a valid number. Try agian.");
phoneInput = in.next();
}
List<String> one = (List) Arrays.asList(dialTwo);
// for converting array into list so that we can use contains method
// which is not //available in array
List<String> two = (List) Arrays.asList(dialThree);
List<String> three = (List) Arrays.asList(dialFour);
List<String> four = (List) Arrays.asList(dialFive);
List<String> five = (List) Arrays.asList(dialSix);
List<String> six = (List) Arrays.asList(dialSeven);
List<String> seven = (List) Arrays.asList(dialEight);
List<String> eight = (List) Arrays.asList(dialNine);
while (i < inputToArray.length) {
if (inputToArray[i] >= 48 && inputToArray[i] <= 57) {
// for numeric characters
System.out.print(inputToArray[i]);
} else if (one.contains(String.valueOf(inputToArray[i]).toLowerCase()))
/*
* searches given character by converting it into lower case in case
* of capital letters
*/
{
System.out.print(1);
} else if (two.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(2);
} else if (three.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(3);
} else if (four.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(4);
} else if (five.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(5);
} else if (six.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(6);
} else if (seven.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(7);
} else if (eight.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(8);
}
i++;// counter variable for counting number of chars entered
}
}
We can use Regular Expression(regex) here to find alphabets in the input and replace each with corresponding integer till entire value contains integers.
Add the following code:
/*Search and replace all alphabets till only numbers are left in the string*/
while(phoneInput.matches("^[a-zA-Z0-9]*$") && !phoneInput.matches("^[0-9]*$")){
/*
* Scenario 1:
* The regex used will search for one occurrence of alphabets a, b & c(both upper and lower case)
* and replace with "1".
* Same goes down for other values as well.
*/
phoneInput = phoneInput.replaceFirst("[a-cA-C]", "2");
phoneInput = phoneInput.replaceFirst("[d-fD-F]", "3");
phoneInput = phoneInput.replaceFirst("[g-iG-I]", "4");
phoneInput = phoneInput.replaceFirst("[j-lJ-L]", "5");
phoneInput = phoneInput.replaceFirst("[m-oM-O]", "6");
phoneInput = phoneInput.replaceFirst("[p-sP-S]", "7");
phoneInput = phoneInput.replaceFirst("[t-vT-V]", "8");
phoneInput = phoneInput.replaceFirst("[w-zW-Z]", "9");
}
System.out.println("The formatted phone number is: " + phoneInput);
This should serve the purpose.
I am writing a program to check wether the given sentence is a panagram or not, but I am not able to compare each character with the characters in a string.
Can anyone suggest me a method to get the desired output?
Scanner scan = new Scanner(System.in);
String panagram = scan.nextLine();
String word = panagram.toLowerCase();
System.out.println(word);
String a[] = { "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" };
int count = 1;
System.out.println("a=" + a.length);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < word.length(); j++) {
if ((a[i]).equals(word.charAt(j)))// problem occurs here {
count++;
break;
}
}
}
if (count == 26) {
System.out.println("pangram");
} else {
System.out.println("not pangram");
}
You can use:
(a[i]).equals(String.valueOf(word.charAt(j)))
or change your a array from String[] to char[] and compare the character using the == operator.
You can convert it to a String and then compare it.
String s = Character.toString('c');
if(s.equals(s2)){..}
Or you could make it a String by adding it to an empty string.
String s = 'c' + "";
if(s.equals(s2)){..}
Or you could compare it's ascii value.
As there are only single characters, why don't you use a character array.
char []a = {'a', 'b', 'c'....};
if(a[i] == 'a')//you could use == in this case.
{..}
Also you don't need to check it that way.
You could create a boolean array of 26 size, as there are only 26 characters and check if every character is present atleast once or not
boolean []arr = new boolean[26];
for(int i = 0; i < word.length(); ++i)
{
arr[word.charAt(i) - 'a'] = true;
}
isPan(arr);
public boolean isPan(boolean[] arr)
{
for(int i = 0; i < arr.length; ++i)
if(!arr[i])
return false;
return true;
}
A simple O(n) solution.
Or you could use a Set and check it's size.
HashSet<Character> set = new HashSet();
for(int i = 0; i < word.length(); ++i)
set.add(word.charAt(i));
System.out.println(set.size() == 26 ? "Pangram" : "Not Pangram");
//A 2 liner would be
HashSet<Character> set = new HashSet<Character>(Arrays.asList(word.toCharArray()));
System.out.println(set.size() == 26 ? "Pangram" : "Not Pangram");
A point added by spookieCookie. These approaches apply only when the string has only lower case alphabets.
String s = "sdgosdgoih3208ABDDu23pouqwpofjew##$%^&".repalceAll("[^A-Za-z]+", "");
String s = s.toLowerCase();
//do the computation then
Convert the array into an arraylist
List<Character> alphabet = Arrays.asList(a);
Make a list to hold the characters that are read:
Set<Character> chars = new HashSet<>();
Then check whether every character in the sentence is part of the alphabet. Duplicates are not added due to the characteristics of Set
for (Character c : word.toCharArray()) {
chars.add(c);
}
Then check whether the size of the Set is equal to the given alphabet:
return (chars.size() == alphabet.size());
Try this instead:
public void checkPanagram() {
boolean isPanagram = false;
String word = "The quick brown fox jumps over the lazy dog";
String a[] = { "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" };
for (int i = 0; i < a.length; i++) {
if (word.toLowerCase().contains(a[i])) {
isPanagram = true;
} else {
isPanagram = false;
break;
}
}
if (isPanagram) System.out.println("Yes, panagram");
else System.out.println("No, not panagram");
}
You can use String.contains(String) as every letter in a already is a String.
for (int i = 0; i < a.length; i++) {
if (word.contains(a[i])) {
count++;
// } else { break;
}
}
A remark: better use String[] a which is a more regular syntax instead of String a[] whose Syntax was added for C/C++ compatibility.
To check equality of a string with a char you could change your code minimally
if ((a[i]).equals(word.charAt(j)) to if ((a[i]).equals("" + word.charAt(j))
This gives you an equality check between two strings.
Alternatively you can change the line if ((a[i]).equals(word.charAt(j))
to if ((a[i]).equals(word.substring(j,j+1))
I'm making a program that will take an input string and decode it using the Rot13 encryption method. This takes the alphabet, and rotates it by 13.
I'm having a hard time getting the index of a letter in the list, and every time I run it it gives me -1 as if the item is not in the list. I looked in the java documentation, and indexOf() asks for an object. I tried explicitly typing my input as an object but that didn't work either.
This is the code I have so far:
package rot13;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
/**
*
* #author andrewjohnson
*/
public class CipherKey {
List<String> alpha = Arrays.asList("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", " ");
List<String> alphaRev = Arrays.asList("Z", "Y", "X", "W", "V", "U", "T", "S", "R", "Q", "P", "O", "N", "M", "L", "K", "J", "I", "H", "G", "F", "E", "D", "C", "B", "A", " ");
public String codeDecode(String s) {
System.out.println(s);
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
//System.out.println(ch);
int x = alpha.indexOf(ch);
//System.out.println(x);
String y = alphaRev.get(x);
System.out.print(y);
}
return null;
}
public static String readInput() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter message to be encoded or decoded");
String s = br.readLine().toUpperCase();
//System.out.println(s);
return s;
}
}
And my main():
/**
*
* #author andrewjohnson
*/
public class Rot13 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
CipherKey x = new CipherKey();
x.codeDecode(x.readInput());
}
}
I'm not sure why it is not working, but I've narrowed it down to the line:
int x = alpha.indexOf(ch);
Not being able to find ch in alpha. I'm new to Java and I've tried everything that I can think of. Thanks for your suggestions!
The problem is here:
char ch = s.charAt(i);
int x = alpha.indexOf(ch); // <-------- HERE
You are searching for a char in a String array. Which of course doesn't exist. Hense the -1
Change it to int x = alpha.indexOf("" + ch);
or int x = alpha.indexOf(Character.toString(ch));
or int x = alpha.indexOf(String.valueOf(ch));
Any of these will do.
ch is of type char and your list contains String. List may accept Object for indexOf, but the type still counts.
Change int x = alpha.indexOf(ch); to int x = alpha.indexOf(String.valueOf(ch)); to fix it.
Example:
System.out.println(alpha.indexOf('D'));
System.out.println(alpha.indexOf(String.valueOf('D')));
will print
-1
3
That is not the rot13 algorithm - you just appear to be reversing the alphabet. rot13 maps the range A - M to N - Z, and vice versa. Two invocations of rot13 give you back the original text.
ASCII letters follow a numerical sequence. Instead of performing a linear search through a list to find the matching index, it's far faster to just calculate the difference between the current letter and A, and then use that difference to offset into a second array of characters (or a string).
i.e.
static String map = "NOPQRSTUVWXYZABCDEFGHIJKLM"; // for rot13
function rot13(String input) {
StringBuffer output;
for (char ch : input) {
int index = ch - 'A';
if (ch >= 0 && ch < 26) {
output.append(map.charAt(index));
} else {
output.append(ch);
}
}
return output.toString();
}
NB: untested, may not compile, E&OE etc
The program allows the user to enter a phrase and converts it to ROT13, where each English letter entered, becomes the letter 13 places after it(A becomes N). My current code works when 1 character is entered, however I need it to run through the code the number of times there are characters. I've tried to put in a while loop at the beginning, but it doesn't seem to be working. Why is this?
import java.io.*;
public class J4_1_EncryptionErasetestCNewTry
{
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed
String key [] = {"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"};
String keyA [] = {"N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"};
System.out.println("Enter a phrase: ");
String phrase = myInput.readLine();
int length = phrase.length();
int y = 0, i = 0, num = 0;
while (y <= length) {
String letter = Character.toString(phrase.charAt(y));
y++;
while(!(letter.equals(key[i]))){
i++;
}
num = i;
System.out.println(keyA[num]);
y++;
}
}
}
See comments on code.
public static void main(String[] args) {
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed
String key [] = {"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"};
String keyA [] = {"N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"};
System.out.println("Enter a phrase: ");
String phrase = "";
try {
phrase = myInput.readLine();
} catch (IOException e) {
e.printStackTrace();
}
int length = phrase.length();
int y = 0, i = 0, num = 0;
while (y < length) { // This should be y < length. Otherwise, it would throw a StringIndexOutOfBoundsException.
i=0; // Re-initialize
String letter = Character.toString(phrase.charAt(y));
// y++; // Unecessary incremental
while(!(letter.equalsIgnoreCase(key[i]))){
i++;
}
num = i;
System.out.print(keyA[num]);
y++;
}
}
Although this doesn't answer your problem, it answers your intention:
public static String rot13(String s) {
String r = "";
for (byte b : s.getBytes())
r += (char)((b + 13 - 'A') % 26 + 'A');
return r;
}
Your code is far too complicated for what it's doing. Really, all the work can be done in one line. Use byte arithmetic rather than array lookups etc. Simple/less code is always the best approach.
Please no comments about inefficiencies etc. This is a basic implementation that works (tested). The reader is free to improve on it as an exercise.
You're code will most likely break in your inner while loop as you are not resetting the value of i. By not doing so your gonna hit StringIndexOutOfBounds. I would recommend initialising i in your outer while loop or better yet just move int i = 0; inside the outer while loop.
I have implemented it in a different way, but it works as you expect, only for uppercase as in your example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class WhileLoopIssue {
public static void main( String[] args ) throws IOException {
BufferedReader myInput = new BufferedReader( new InputStreamReader(
System.in ) );// Buffered Reader reads the
// number inputed
final List<String> letterList = Arrays.asList( "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" );
System.out.println( "Enter a phrase: " );
String phrase = myInput.readLine();
final String[] letters = phrase.split( "" ); // Split input phrase
final StringBuffer buffer = new StringBuffer(); // Variable to save letters. Could be a String as well.
for ( int i = 0; i < letters.length; i++ ) {
final int letterIndex = letterList.indexOf( letters[i] ); // Get the numeric value of the letter
if ( letterIndex < 0 ) // Skip iteration if not found. Maybe a lowercase, or an empty String
continue;
final int nextLetterIndex = 13 + letterIndex; // Actual value of the letter + 13
if ( nextLetterIndex > letterList.size() ) {
buffer.append( nextLetterIndex % letterList.size() ); // Actual value greater than the total number of letters in the alphabet, so we get the modulus for the letter
} else {
buffer.append( letterList.get( nextLetterIndex ) ); // Letter in the range, get it
}
}
System.out.println( buffer.toString() );
}
}
You need to reset i in each iteration. It may happen that first letter found toward the end of the array "key". Your code will find next input char there onward, I guess this is not what you want, and will not find that char and will throw SIOBException. I have changed the while loop, removed twice increment in variable y as well. Have a look
while (y < length) {
i = 0; //Every Time you want to search from start of the array
//so just reset the i.
String letter = Character.toString(phrase.charAt(y));
while(!(letter.equals(key[i]))){
i++;
}
num = i;
System.out.println(keyA[num]);
y++;
}
I am assuming what ever you enter as input is a phrase of ONLY upper-case alphabets, else you will come across the SIOBException as you you will not be able to locate that letter in your array.
Just on side note, instead of those arrays you should use some other data structures which are efficient for searching like hashmap. Your linear search across the array is not optimized.