Creating a Infinite While Loop Errors in Java - java

I'm trying to implement a infinite while loop into my word frequency java code. The goal of this code was to create a program using main method java to analysis a piece text which has been entered from a user.
They do this by entering the text into a scanner which is then analysed by the program.
import java.util.Scanner;
public class WordFreq {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
input.close();}
}
The user then can re enter a piece of text to be analysed over and over again.
I have this piece of code, which has a infinite while already in, but when I try to merge the two I keep getting errors.
import java.util.Scanner;
public class WhileLoop {
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
String line="";
while((line=scan.nextLine())!=null)
{
String tokens [] = line.split(" ");
for(int i=0;i<tokens.length;i++)
{
System.out.println(tokens[i]);
}
}
}
I'm not the Best at java and I'm not expecting anyone to just hand me code, but if someone could give me a hint in what I should do or just point me the right direction it would be greatly appreciated.

You have not clarified how do you actually merged your code and what kinds of errors ar eyou getting but your while loop is not good. You need to wait for user input INSIDE an "infinite" loop.
while(true){ //Infinite loop
Scanner in = new Scanner(System.in);
while(in.hasNextLine())//Check for input
System.out.println(in.nextLine()); //Process input
}
This way every time the user pressed 'Enter' you process his input.Of course you can do anything you like with in.nextLine()' orin.next()` and your while loop could have an ending condition cause i doubt you want an 100% infinite loop, but the structure should be the same. Hope this helps.
EDIT: Try the following code:
while(true){
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
}
Although its quite unlikely you need a true infinite loop, so consider putting some stopping condition in your while loop.

This is a bit confusing, but let me try anyway.
If you merge the two blocks of code then you should try printing count[i] instead of token[i] in the while loop. And the limit of the loop should be count.Length not token.Length.
Now, if I am not wrong, this would print the frequency of 1 to 5 lettered words infinitely taking in your inputs from the first block of the code.

Related

Not a Statement Error - Where did I go wrong?

So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.

Write a program that will read a line of text, and will display all letters in the text along with the number of times the letter appears in the text

I have the basics, but I need to make it so that my program will work without printing the unused letters of the alphabet at the end, say my sentence is "dog" I would want the output to be: D-1
O-1
G-1, instead of A-0 B-0 D-1, and so on. Thanks for any help provided, it is greatly appreciated.
what I have so far is:
package as10;
import java.util.*;
public class as
{
private static void countLetters(String sentenceString)
{
int[] array = new int[26];
sentenceString = sentenceString.toUpperCase();
for (int i = 0; i < sentenceString.length(); ++i)
{
if (sentenceString.charAt(i) >= 'A' && sentenceString.charAt(i) <= 'Z')
{
++array[sentenceString.charAt(i) - 'A'];
}
}
for (int i = 0; i < 26; ++i)
{
System.out.println((char) ('A' + i) + " - " + array[i]);
}
}
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
String letterString;
while (true)
{
System.out.println("Enter a line of text: ");
letterString = kbd.nextLine();
System.out.println("Letter Frequencies: ");
countLetters(letterString);
break;
}
kbd.close();
}
}
so, basically, you want to opt out all chars if counter is 0.
In other words, you will need an if statement around print line and only perform system output if relevant array value is non-zero.
Above statement is in pure English. It is again your assignment to convert that sentence into java, as I refuse to do your homework on your behalf.
Does it sound fair ? :)

Why is this simple program not working

So I'm doing some random practice for an upcoming exam, and I don't know if it's the fact that I've been reviewing for hours and my brain isn't functioning, or something in this code is wrong.
I'm attempting to make a very simple java program that asks the user for the amount of numbers they wish to enter (totalNum), create an array that long, and then ask the user for each individual value. After it asks the user for each value in the array, it prints the array.
Here is my code:
import java.util.Scanner;
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i>totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++;
}
numbers.toString();
System.out.println(numbers);
}
}
When I run it it asks the user for the numbers I want to store, then prints [I#33909752 and stops. I've done dozens of programs like this and for the life of me I can't figure out where I went wrong.
Any help would be appreciated, thanks!
Your loop test is backwards. This
for (int i = 0; i>totalNum; i++) {
should be
for (int i = 0; i < totalNum; i++) {
as is, the test evaluates to false and the loop isn't entered. And, don't increment i in the loop body (that's what i++ does in the for). Finally,
System.out.println(numbers);
isn't going to print the array correctly, because arrays don't override Object.toString(). You can use Arrays.toString like
System.out.println(Arrays.toString(numbers));
i>totalNum is the problem. The for loop will not execute even once.
The for loop has three parts:
The action to perform before starting the loop
The condition
The action to perform after each loop
Your condition is i>totalNum, which is false for i=0 and totalNum=1. The loop won't execute even once.
The i++ is already mentioned in the loop, you do not need to include it in the loop body anymore.
The unexpected output is the caused by the default toString()-method of Array. Use Arrays.toString() for a readable output.
Your loop condition should be
for (int i = 0; i<totalNum; i++) {
and within loop don't increment variable i
use below for your desired result.
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i<totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++; //remove this
}
numbers.toString();
System.out.println(Arrays.toString(numbers));
}
}

How to reverse a string that has already been reversed?

I made a program that lets a user enter in a word or a phrase or a sentence and reverse it and display the result.
My issue is that when I run it it does reverse it but it reverses the words when all I want to do is keep the words as they were inputted and just reverse them.
Here is what I have currently
//import statements
import java.util.*; //for scanner class
// class beginning
class WordReverser {
public static void main(String[] args ) {
//Declare variables area
String original, reverse = "";
Scanner in = new Scanner(System.in);
boolean blankString = false;
public StringBuilder reverse();
// beginning message to user to explain the program
System.out.println("Welcome to my reverse word program!");
System.out.println("Please enter in a word or a phrase and see it reversed: ");
//main code and calculations to do
while (!blankString){
System.out.println("Enter a string to reverse");//Collect inputs from user.
original = in.nextLine();
if (original.equals(""))
{
blankString = true ;
}
else {
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);//Output results here
}
}
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
Clearly a homework question, so I'll give you a shove in the right direction, but I won't give the full answer. You need to reverse one word at a time and not the whole string.
You need something that implements this pseudo code:
original = getStringFromUser();
words[] = breakIntoWords(original);
foreach word in words {
reversed = reverse(word);
print reversed;
}
reverse(string word)
{
return reversed version of the input
}
breakIntoWords(sting sentence)
{
return array with each word as a sep.element
}
If you read the docs, you may find reverse and breakIntoWords are already there for you, so you just need to call the right methods.
The key to solving problems is learning how to break them down into smaller pieces that are easier to solve. This is a good problem solving technique and is at the heart of programming.
You know how to reverse the letters in a sentence. You want to reverse the letters in each word, but leave the words in their original order. Or, to say it another way, you want to:
Split the sentence into separate words.
Reverse each word one by one.
Combine the words back together into a sentence.
Hopefully each of these steps is more manageable. If not, think about how you can break them into even smaller steps. For instance, for #2 maybe you need a loop and then something inside that loop.
Do you want to reverse the word order? In this case you'll have to split the input string at " ".
To do this, your else-block should be
String[] words = original.split(" ");
for(int i = words.length-1; i>=0; i--)
reverse += words[i] + " ";
System.out.println("Reverse of entered string is: "+reverse);
I see 2 ways of dealing with this quickly if not too elegantly
easiest thing to do would be to create a 3rd variable called something like String originalWords that gets appended to from stdin in the loop.
Reuse the existing 'original' String to do the same as above and then loop it in reverse in a second loop.
You can split the input string into separate array of words and then reverse each word in the array separately.
Refer this for code.
I have refactored your code a little bit to solve your issue. First I put your reverse logic in a separate method
public static String reverse(String strToReverse) {
String original = strToReverse, reverse = "";
boolean blankString = false;
if (original.equals(""))
{
blankString = true ;
}
else {
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
}
return reverse;
}
Second I splitted your string into words (assuming the words are separated by simple spaces)
public static void main(String[] args ) {
//Declare variables area
String original, reverse = "";
Scanner in = new Scanner(System.in);
boolean blankString = false;
//public StringBuilder reverse();
// beginning message to user to explain the program
System.out.println("Welcome to my reverse word program!");
System.out.println("Please enter in a word or a phrase and see it reversed: ");
//main code and calculations to do
while (!blankString){
System.out.println("Enter a string to reverse");//Collect inputs from user.
original = in.nextLine();
if (original.equals(""))
{
blankString = true ;
}
else {
String[] words = original.split(" ");
String[] reversedWords = new String[words.length];
StringBuilder reverseBuilder = new StringBuilder();
for (int index = 0; index < words.length; index++) {
reversedWords[index] = reverse(words[index]);
reverseBuilder.append(reversedWords[index] + " ");
}
System.out.println("Reverse of entered string is: "+reverseBuilder.toString());//Output results here
}
}
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
Here is an execution example:

Stuck on Mean word length

The goal of this code was to create a program using main method java to analysis a piece text which has been entered from a user.
They do this by entering the text into a scanner which is then analysed by the program. The analysis is to produce word frequency, for example " This is a test" produces this results:
This is a test
1 letter words: 1
2 letter words: 1
3 letter words: 0
4 letter words: 2
5 letter words: 0
The bit that I'm stuck on is producing a mean/average, My guts telling to divide
counts.length by str.length but I'm not the Best at java and I've tried to implement this but all I get are errors. I'm not expecting anyone to just hand me code, but if someone could give me a hint in what I should do or just point me the right direction it would be greatly appreciated.
Code:
import java.util.Scanner;
public class Text_AD {
public static void main (String[] args) {
while(true){
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
}}}
By average, I am assuming that you mean the mean length. I am also assuming you want to get a floating point mean. In which case you just need to divide the total of all the lengths in strings by the length of the array itself.
You could do something like the following;
int total = 0;
for(String s : strings) total += s.length();
System.out.println((double)total/strings.length);
I hope this helps.
Without breaking up your code much, you could run a for loop through your counts[] array, adding up all the values, and then dividing by counts.length to get the average.
Be aware of type casting though. You may want to do Double division instead of integer.
It this what you are looking for?
import java.util.Scanner;
public class While_Loop {
public static void main (String[] args) {
int lengthSum, wordCount;
lengthSum = wordCount = 0;
while(true){
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
wordCount++;
lengthSum += str.length();
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
System.out.println("Average: " + lengthSum/wordCount);
}}}
NOTE: I only added stuff to your code. The way it is written is pretty messy. I'd clean up some of the for loops and the brackets at the end for practice making the code more readable.
When I understand you correct you should have one variable int totalCount = 0; where you add
totalCount += i*counts[i]; in your last for loop.
After the loop you can simply divide through the size-1 (because 0 does not count)
double average = totalCount/(counts.length-1);
Alternative way
You take the inputstring length without the spaces and divide it by the number of spaces + 1 (which is equal to the number of words)
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
System.out.println("Enter text: ");
String s = "This is a sample text";
System.out.println("" + s);
String[] strings = s.split(" ");
for(String str : strings) {
Integer counter = map.get(str.length())==null?0:map.get(str.length());
map.put(str.length(),counter++);
}
Integer sum=0;
Integer counter=0;
for(Integer len : map.keySet()) {
sum+=len*map.get(len);
counter+=map.get(len);
}
Double average = Double.valueOf(sum/counter);
Or you can combine the loops
Few suggestions which might help you (not related to the specific question).
Choose a meaningful class name rather than While_Loop .
Do, Scanner input = new Scanner(System.in); before the start of the loop.
As soon as you read each line, do the following.
Split the line using "\\s+" .
Create a HashMap with Key as Count (Integer) and Value as a list of Words with that count. Create this outside the loop.
For each split word,,get the length . and check if the map already contains the count, get the list (value), add he current word to it. else, add a new entry with the word as the single entry in the list.
Get the keySet of the map, add values of all keys i.e, *count * number of elements in the list*. then divide by total number of elements.
And yes, I know this is a very big change (something you might as well ignore..). But this is the right way to go.

Categories