So our teacher gave us this homework, we had to write a program that went something along the lines of
Write an application that reads a line of text from the keyboard and prints a table indicating the number of occurrences of each letter
of the alphabet in the text, For example, the phrase
To be, or not to be: that is the question:
Contains one “a,” two “b’s,” no “c’s,” and so on.
Well I've written the code, but I've ran into one small problem when I enter the to be or not to be part the code continually loops forever. I've looked at this program forever, I even tried asking some folks at Yahoo (but I think I confused them). So I am hoping someone here will spot something I missed or have some advice to give me.
public class occurances {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
String str;
char ch;
int count = 0;
System.out.println("Enter the string:");
str = inp.nextLine();
while (str.length() > 0) {
ch = str.charAt(0);
int i = 0;
while (i < str.length() && str.charAt(i) == ch) {
count = count++;
i++;
}
str = str.substring(count);
System.out.println(ch);
System.out.println(count);
}
}
}
There are many problems with your code, but start with count = count++. It will always have its initial values (0 in your case). That causes the infinite loop. If you manage this one you'll be good to go with debugging your code further. Learn how to use debugger and/or print for checking your code. Good luck.
It seems your approach is not necessarily the one the teacher wants. Your approach (if it worked at all) would display the character counts in the order the characters appear in the string. So, for example, for "To be, or not to be: that is the question" you would show the character count for "T" first, whereas the teacher probably wants you to show the character count for "a" first. Your approach also doesn't show the character counts for the characters that are missing in the answer.
It has been suggested in the other two answers to use a Map. I recommend that approach, although you could use a simple int[] array where the index is (ch - 'a') assuming that it is between 0 and 25. See Character.toLowerCase() for how to convert a character into a lowercase one, because the correct answer would probably treat "T" and "t" as the same.
You need only one loop through the array, incrementing the counts for the characters that appear. Obviously all of the counts should be initialized to 0 prior to the loop.
I've not done JAVA in a while i came here to help someone with Javascript... but i'll give it go
while(str.length()>0)
This will obviously enter an endless loop because you have no breakout terms... i'd probably use a for loop instead... also you need something to store your counts inside of for each unique letter you find.
-- EDIT based on the comment below i find myself agreeing that answering your homework is not a good thing but here is what i'd suggest you look at...
Look at Hashtables or Maps and thing about "storing the dictionary counts as you find them"
Bare in mind upper and lower case letter, i'd just cast to lowercase and count
use a for loop instead of the while loop, use the strings length as the limit e.g. count from 0 to string.length()
This should get you on the right path :http://www.java2s.com/Tutorial/Java/0140__Collections/GettingelementskeyvaluepairsfromaHashtabletheentrySetmethod.htm
Some things to resolve in your code:
while(str.length()>0) : Infinite loop here. You could go through the string, with a for (int index = 0; index < str.length(); index++).
ch = str.charAt(0); : Here you are always taking the first letter of the String, you should take each letters with ch = str.charAt(index);.
count = count++; : count++; would be enough or count = count + 1;.
count = count++; : count should be re-initialized for each letter count = 0; before your while inner loop.
str = str.substring(count); : No need to substring here. You would loose letters for next computation.
Your code should work with one disavantages. The letters and their count will be written as many times as their is their occurence. If a is 3 times in the String, a : 3 will be written 3 times.
So you should whether you had already print the letter (maybe an array), but performance would be bad. For a String of n letters, you would have n * n computations (Complexity O(n^2)). If you take an HashMap between letter and their count, you will just of to go through the String one time, incrementing your counter while iterating on the loop. Then you would have only n computations. (Complexity O(n)).
HashMap<Char, Integer> letters = new HashMap<Char, Integer>();
for (int i = 0; i < str.length(); i++) {
char letter = str.charAt(i);
if (!letters.contains(letter)) {
letters.put(letter, 1);
} else {
letters.put(letter, letters.get(letter) + 1);
}
}
Then you go through the map to display the count.
Here is your corrected code for the problem you asked..Try this..
import java.util.*;
public class Occurence {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
String str;
char ch;
int count = 0;
System.out.println("Enter the string:");
str = inp.nextLine();
int length = str.length();
int i = 0, j = 0;
for (i = 0; i < length; i++) {
j = 0;
count=0;
for (j = 0; j < length; j++) {
if (str.charAt(j) == str.charAt(i)) {
count++;
}
System.out.println(str.charAt(i)+" "+count);
}
}
}
}
Related
I have a task where I need to print words from an array in reverse(the word itself). This is what the task states :
Create an array of words called ‘wordList’ and assign the values ‘Stressed’, ‘Parts’, ‘Straw’, ‘Keep’, ‘Wolf’
Create a string called ‘reversedWord’ and do not assign it a value.
Similar to the above challenge, however, instead of reversing a sentence, reverse the order of the letters
within each string.
a. You will need to create a for-loop to access each word in turn. Immediately within the loop set
‘reversedWord = “”;’
b. Then create another for-loop inside of the first one to iterate backwards through the current
word. Update the value of ‘reversedWord’ on each iteration.
c. Print the reversed word on the screen.
STRETCH CHALLENGE: Handle the word so that it reads properly backwards. (Stressed becomes Dessert)
I don't know wether I'm just not understanding the wording of the task or not, but this is the code I have at the moment:
String[] wordList = {"Stressed", "Parts", "Straw", "Keep", "Wolf"};
String reversedWord;
for (int i = wordList.length; i >= 0; i++) {
reversedWord = "";
for (int j = wordList[i].length() - 1; i >= 0; j--) {
reversedWord += wordList[i].charAt(j);
System.out.println(reversedWord);
}
}
It gives me this error when i run it:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at Main.main(Main.java:22)
Any help explanation would be helpful.
There are a few issues here. In the line
for (int i = wordList.length; i >= 0; i++) {
you are setting i to be the length of the wordList, which is 5. Remember, though, that array indexes start at 0. So the valid indexes of wordList are 0, 1, 2, 3, and 4, but not 5. To fix this, you can just subtract 1 from the length.
for (int i = wordList.length - 1; i >= 0; i++) {
The next problem is that you are increasing i at the end of each loop. Since it seems like you're trying to iterate backwards, you're gonna want to decrease i, not increase it.
for (int i = wordList.length - 1; i >= 0; i--) {
There is a simpler solution using Java's StringBuilder class:
public static void main(String[] args) {
String[] wordList = {"Stressed", "Parts", "Straw", "Keep", "Wolf"};
for (int i = 0; i < wordList.length; i++) {
String word = wordList[i]; // Get the word from array
word = new StringBuilder(word).reverse().toString(); // use StringBuilder to reverse the word
wordList[i] = word; // put word back in the array
}
System.out.println(Arrays.asList(wordList));
}
This outputs
[dessertS, straP, wartS, peeK, floW]
UPDATE:
For the words to read properly (first character in uppercase), You could do something like this:
word = word.toLowerCase();
word = word.replace(word.substring(0,1), word.substring(0,1).toUpperCase());
wordList[i] = word; // put word back in the array
There are more effective ways to do this, but is simpler for you to understand. This obviously outputs:
[Desserts, Strap, Warts, Peek, Flow]
substring(0,1) returns the first character (substring from index 0 to index 1; where the last index is not inclusive) as a String. Then, you are replacing the same substring with the uppercase substring.
I created a simple program using the acm library that takes a user inputted string and prints it out in morse. This is the program:
import acm.program.*;
public class morse extends Program{
public void run(){
String[] 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"};
String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
String word = readLine("Give the word(s) to transcribe: ").toUpperCase();
println("Morse: ");
int j = 0;
for(int i = 0; i < word.length(); i++){
int k = 0;
boolean flag = true;
if(Character.toString(word.charAt(j)).equals(" ")){
println();
}else {
while(!Character.toString(word.charAt(j)).equals(alphabet[k])){
if(k < 25){
k += 1;
}else{
println("Letter was not found.");
flag = false;
break;
}
}
if(flag){
println(morse[k] + " ");
}
j += 1;
}
}
}
}
However, every time the string contains a space, everything after the space is not printed. I seriously cant find the reason behind this. Can anyone help me or even point me somewhere ? Thanks
(The letters after the space are all printed as spaces)
I do not know why you define i in the for loop but never use it. Your main problem is that when you encounter an space you do not increment j. I think you have two options:
increment j after you call println(); inside the if
drop j completely and simply use i wherever j previously was used (probably the better idea)
General recommendation for your code: You are performing too much weird Character and String logic. You could do
drop the alphabet
get the char from the String the same way you currently do
subtract 'A' from it
use the resulting char as index to access the morse array
drop k and the entire while loop.
This is the version I'm working right now, where the loop does end but it just doesn't loop through each letter, instead it only repeats the first occurrence of the first letter.
For example, if sourcetext was the ugly and password was ugly it would repeat 4 (the position of u) four times (the length of ugly). Where as what I want it to do is repeat the loop four times (the length of ugly) but give back each position, not just the first (instead of 4444, I'm getting 4 5 6 7).
Am I using the wrong kind of loop to achieve this? I've tried a few different ways and at this point I am stuck. Also if the answer is really obvious please don't burn me at the stake, I've only been programming for three months and have really given it a go on my own.
import java.util.Scanner;
public static void main(String[] args) {
String letter, sourcetext;
Scanner sc;
int temp;
sc = new Scanner(System.in);
sourcetext = sc.nextLine();
letter = sc.nextLine();
for (int i= 0; i < letter.length(); i++) {
temp = sourcetext.indexOf(letter);
System.out.print(temp);
}
}
You always use the same index: indexOf(letter). I guest what you want is:
for (int i= 0; i < letter.length(); i++) {
temp = sourcetext.indexOf(letter.charAt(i));
System.out.print(temp);
}
My NEW sample text i was testing: My mom is a good cook. Although sometimes at around noon she will leave and forget to make me lunch and some pop. #Old homework become relevant again
my problem is just that i am not getting the correct output, as my method only prints *Mom a noon i
This is all GUI based.I am reading in a file and checking for palindromes and printing them out in my JTextArea afterwards using Stacks and Queue's.
Issue is, all of this is working and when i start the program and attach the text file, i only get the first palindrome. SO it will print "mom" which is my first testcase, but it won't go to any of the other palindromes following it?
I thought i might have got bogged down in my code blocking at some point but after tinkering with it for a day now i'm sort of stuck.
EDIT 1: I am now getting more results
my method is,
public void fileDecode() throws FileNotFoundException
{
if (fileChoice.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
file = fileChoice.getSelectedFile();
scanInput = new Scanner(file);
while(scanInput.hasNext())
{
int nextPalindrome = 0;
int counter = 0;
String token = scanInput.next();
Stack<Character> stk = new Stack<Character>();
Queue<Character> que = new LinkedList<Character>();
for (int i = 0; i < token.length(); ++i)
{
stk.push(token.charAt(i)); //pushing all char's onto the stack/queue
que.add(token.charAt(i));
}
for (int j = 0; j < token.length(); ++j)
{
char tempStk = stk.pop(); //removing them one at a time and checking if they are equal and incrementing counter
char tempQue = que.remove();
if (tempStk == tempQue)
{
counter++;
}
}
if (counter == token.length())
{
build.append(token + " "); //if the counter # was the same as the token's length, than it is indeed a palindrome and we append it into our StringBuilder that we pass to the JTextArea
nextPalindrome = token.length();
}
}
}
}
You set counter to 0 outside your while loop, so the count of the second word is going to start at the count of the first word. Move counter = 0 inside the while loop and it should work.
Also, nextPalindrome doesn't appear to be used, and even if it is, if you set it at the bottom of the loop, it's immediately set to 0 at the top, so it will only remain non-zero if the last word is a palindrome.
Also, think about what's happening in the second for loop. You're looping over all the characters and comparing the one from the stack and the one from the queue. If ever those are different, you know you don't have a palindrome, so once you find a difference, it's pointless to continue with the loop. You also already have a loop counter, j, so you don't need another one. So I'd rewrite the second loop and following condition as follows:
for (int j = 0; j < token.length(); ++j)
{
char tempStk = stk.pop(); //removing them one at a time and checking if they are equal and incrementing counter
char tempQue = que.remove();
if (tempStk != tempQue)
break;
}
if (j == token.length())
That works because the only way j can equal token.length() after the loop is done is if the loop completed, which can only happen if no pairs of characters aren't equal (in other words, all pairs of characters are equal, which is what you want).
I have a four letter string of letters, such as ASDF and I want to find all 3 (three) letter combinations using these letters and the three letter combination does not need to form a real word.Ex.
AAA AAS AAD AAF
ADA ADS ADD ADF
...............
SSA SSD SSF SSS
I am relatively new to Java, having just learned how to use the String class and using loops and conditional statements. The only way that I know how to do this is by a massive and very tedious set of for loops and if statements that account for every possibility that could arise. This would look like:
public static void main(String[] args)
{
String combo = "";
for(int counter = 1; counter <= 16; counter++){
combo = "A";
if(counter == 1){
combo = combo + "AA";
}
// This would continue on for all the possibilities starting with "A" and
// then move on to "S" as the lead character
}
}
I know that this is one of the worst ways to go about this problem, but I am really stuck as to how to do it another way. It would be easier if I had 3 letters and made the 3 letter combos, as then I could just get each letter from the array and just rearrange them, but as I'm only using 3 of the 4 letters it is more difficult. Any advice on how to get this done in an more efficient manner?
Use a recursive function.
Like this (not tested, don't have a Java compiler on my laptop).
Performance could probably be boosted by using StringBuilder.
static void printAllPossibilities(String charSet, int length) {
printAllPossibilities_(charSet, length, "");
}
static void printAllPossibilities_(String charSet, int length, String temp) {
if (length == 0) {
System.out.println(temp);
return;
}
for (int i = 0; i < charSet.length(); i++)
printAllPossibilities_(charSet, length - 1, temp + charSet.charAt(i));
}
Usage:
printAllPossibilities("ASDF", 4); // Print all 4-letter combinations out of "ASDF"
printAllPossibilities("bar", 2); // Print all 2-letter combinations out of "bar"
For the general case (all combinations of N chars out of M), the solution by #Qntm is exactly what you need... but, use a StringBuilder as he said, and just change the last character instead of constructing strings like 'temp + charSet.charAt(i)'.
If you need exactly 3 chars out of N, it's easier to just do 3 nested loops:
for (int char1 = 0; char1 < charSet.length(); char1++) {
for (int char2 = 0; char2 < charSet.length(); char2++) {
for (int char3 = 0; char3 < charSet.length(); char3++) {
System.out.println(""+charSet.charAt(char1)+charSet.charAt(char2)+charSet.charAt(char3));
}
}
}