arrays not recognized outside of for loop - java

I am trying to write a program that takes input from an external file, prints it, then calculates total world length and also the frequency of 3 letter words within the file. I'm only supposed to use string methods... I have tried to create an array of lines from the input and then create another array using .split to analyze each word. However, everytime I try to test wordcount or write a code segment to calculate frequency of 3 letter words, I get an error of can not find symbol... I don't know what this means. Can someone help me with what the error means and how to fix it, please?
import java.util.*;
import java.io.*;
public class Program
{
public static void main(String args[])
{
Scanner inFile = null; //adds the data
try {
inFile = new Scanner (new File("prog512h.dat"));}
catch (FileNotFoundException e) {
System.out.println ("File not found!");
System.exit (0);}
String[] line = new String[18]; //there are 18 lines of code in the external file
int wordcount=0;
for (int i=0; i<18; i++){
line[i] = inFile.nextLine();
System.out.println(line[i]);
String word[] = line[i].split(" ");
}
wordcount = word.length();
System.out.println();
System.out.println("Total Wordcount: " +wordcount);
}}
The external data file referenced reads this:
Good morning life and all
Things glad and beautiful
My pockets nothing hold
But he that owns the gold
The sun is my great friend
His spending has no end
Hail to the morning sky
Which bright clouds measure high
Hail to you birds whose throats
Would number leaves by notes
Hail to you shady bowers
And you green fields of flowers
Hail to you women fair
That make a show so rare
In cloth as white as milk
Be it calico or silk
Good morning life and all
Things glad and beautiful

You are creating a local variable inside a loop, so as soon as you leave the loop it goes out of scope.
Read up on variable scoping for more detail. The easiest fix is to declare the variable before you enter the loop - although note that that would overwrite the variable each time so only the last time around the loop would do anything.
You probably actually want to do:
wordCount += word.length;
Inside the loop.

Right now, your code as it is, doesn't make very much sense. Even if word[] was visible outside your for loop, it would only represent the very last line after the loop was done.
But, if you just want to update the wordcount without making any major changes to your code, you can update wordcount inside your loop
int wordcount = 0;
for (int i=0; i<18; i++)
{
line[i] = inFile.nextLine();
System.out.println(line[i]);
String word[] = line[i].split(" ");
wordcount += word.length;
}

Related

Why can't I display contents of file the second time plus jump of lines after counting the total number of lines in Java

I am new to Java.I am stuck in this code.I have two questions.
1:Why my second while statement doesn't run at all?
2:In my first while statement,if i have both statements,it gives me wrong answer.It halves the lenght of my file.While with only one statement,no matter which,the answer is correct.Can anyone explain it to me?
import java.util.Scanner;
import java.io.File;
public class HangMan {
public static void main(String args[])throws Exception{
System.out.println("This is like Hangman(type) game for movies");
System.out.println("You have 10 guesses to make");
File file = new File("movielist.txt");
Scanner filescanner = new Scanner(file);
int count = 0;
while (filescanner.hasNextLine()){
System.out.println(filescanner.nextLine());
count += filescanner.nextLine().split("/n").length;
}
System.out.println(count);
while (filescanner.hasNextLine()){
/*Why it's not being run at all?*/
System.out.println(filescanner.nextLine());
System.out.println("hi");
}
}
}
As soon as you leave the first while loop you can be certain filescanner.hasNextLine() has returned false. That means that the second while loop will not be run even once, how could it? You have the same condition in both loops, when one finishes the other will certainly not start.
Your file length is "halfed" because you actually read two lines from the file each iteration. One when writing System.out.println(filescanner.nextLine()) and a second time when actually counting count += filescanner.nextLine().split("/n").length. You should probably do
String line = filescanner.nextLine();
System.out.println(line);
count += line.split("/n").length;

print even words from string input?

I am in a beginners course but am having difficulty with the approach for the following question: Write a program that asks the user to enter a line of input. The program should then display a line containing only the even numbered words.
For example, if the user entered
I had a dream that Jake ate a blue frog,
The output should be
had dream Jake a frog
I am not sure what method to use to solve this. I began with the following, but I know that will simply return the entire input:
import java.util.Scanner;
public class HW2Q1
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence");
String sentence = keyboard.next();
System.out.println();
System.out.println(sentence);
}
}
I dont want to give away the answer to the question (for the test, not here), but I suggest you look into
String.Split()
From there you would need to iterate through the results and combine in another string for output. Hope that helps.
While there will be more simpler and easier way to do this, I'll use the basic structure- for loop, if block and a while loop to achieve it. I hope you will be able to crack the code. Try running it and let me know if there is an error.
String newsent;
int i;
//declare these 2 variables
sentence.trim(); //this is important as our program runs on space
for(i=0;i<sentence.length;i++) //to skip the odd words
{
if(sentence.charAt(i)=" " && sentence.charAt(i+1)!=" ") //enters when a space is encountered after every odd word
{
i++;
while(i<sentence.length && sentence.charAt(i)!=" ") //adds the even word to the string newsent letter by letter unless a space is encountered
{
newsent=newsent + sentence.charAt(i);
i++;
}
newsent=newsent+" "; //add space at the end of even word added to the newsent
}
}
System.out.println(newsent.trim());
// removes the extra space at the end and prints newsent
you should use sentence.split(regex) the regular expression is going to describe what separate your worlds , in your case it is white space (' ') so the regex is going to be like this:
regex="[ ]+";
the [ ] means that a space will separate your words the + means that it can be a single or multiple successive white space (ie one space or more)
your code might look like this
Scanner sc= new Scanner(System.in);
String line=sc.nextLine();
String[] chunks=line.split("[ ]+");
String finalresult="";
int l=chunks.length/2;
for(int i=0;i<=l;i++){
finalresult+=chunks[i*2]+" ";//means finalresult= finalresult+chunks[i*2]+" "
}
System.out.println(finalresult);
Since you said you are a beginner, I'm going to try and use simple methods.
You could use the indexOf() method to find the indices of spaces. Then, using a while loop for the length of the sentence, go through the sentence adding every even word. To determine an even word, create an integer and add 1 to it for every iteration of the while loop. Use (integer you made)%2==0 to determine whether you are on an even or odd iteration. Concatenate the word on every even iteration (using an if statement).
If you get something like Index out of range -1, manipulate the input string by adding a space to the end.
Remember to structure the loop such that, regardless of the whether it is an even or odd iteration, the counter increases by 1.
You could alternatively remove the odd words instead of concatenation the even words, but that would be more difficult.
Not sure how you want to handle things like multiple spaces between words or weird non-alphabetically characters in the entry but this should take care of the main use case:
import java.util.Scanner;
public class HW2Q1 {
public static void main(String[] args)
{
System.out.println("Enter a sentence");
// get input and convert it to a list
Scanner keyboard = new Scanner(System.in);
String sentence = keyboard.nextLine();
String[] sentenceList = sentence.split(" ");
// iterate through the list and write elements with odd indices to a String
String returnVal = new String();
for (int i = 1; i < sentenceList.length; i+=2) {
returnVal += sentenceList[i] + " ";
}
// print the string to the console, and remove trailing whitespace.
System.out.println(returnVal.trim());
}
}

Read words until user writes 'end', then, order lexicographically(as in a dictionary), show the last word

User will enter words until the last word written is "end", then the code has to order lexicographically, as we have in a dictionary, all the words entered before 'end' and print the last word, the one classified the last.
//.....
Scanner word = new Scanner (System.in);
String keyword="end";
String finalstring;
String[] firststring= new String[1000]; //Don't know how to stablish a //dynamic string[] length, letting the user stablish the string[].length
for(int c=0;c<firststring.length;c++){
firststring[c]=word.next();
if(firststring[c].equals(keyword)){
finalstring=firststring[c].substring(0,c);
c=cadena.length-1; //To jump out of the for.
}
}
for (int c=0;c<finalstring.length();c++) {
for(int i=c+1;i<finalstring.length();i++) {
if (firststring[c].compareTo(firststring[i])>0) {
String change = firststring[c];
firststring[c] = firststring[i];
firststring[i] = change;
}
}
}
System.out.print("\nYou entered "end" and the last word classified is "+finalstring[finalstring.length()-1]); //Of course, error here, just did it to put one System.out.print of how should the result be.
}
}
This is what I tried, though, without any type of success, any help of yours will be a big help, thank you ALL!
Don't know how to stablish a dynamic string[] length, letting the user establish the string[].length
It is not necessary to do that. But here's how.
Approach #1: ask the user to give you a number and then allocate the array like this:
String[] strings = new String[theNumber];
Warning: the requirements don't say you are allowed to do that, and you may lose marks for deviating from the requirements.
Approach #2: use an ArrayList to accumulate a list of words, the use List.toArray to create an array from the list contents. (Read the javadocs for list to work it out.)
Of course, error here, just did it to put one System.out.print of how should the result be.
Yea. One problem is that the length is 1000, but you don't have 1000 actual strings in the array. The same problem affects your earlier code too. Think about is ...
I'm not going to fix your code to make it work. I've given you enough hints for you to do that for yourself. If you are prepared to put in the effort.
One more hint: you can / should use break to break out of the first loop.
I know some words are not in English but in Catalan, but the code can be perfectly understood, yesterday I finally programmed this answer:
public static void main(String[] args) {
Scanner entrada= new Scanner(System.in);
System.out.println("Escriu les paraules que vulguis, per acabar, usa la paraula 'fi'.");
String paraules = "";
int c=0;
do {
String paraula = entrada.next();
if (paraula.equals("fi")) {
c++;
} else {
if (paraula.compareTo(paraules) > 0) {
paraules = paraula;
}
}
} while (c==0);
System.out.println("L'última parala ordenada alfabèticament és "+paraules+".\n");
}
}

Arrays - square-free word

This is what the program should do:
The word, zatabracabrac, is not square free, since it has subword, abrac twice start-
ing at position 4 of the word.
We are not allowed to use strings, breaks or other complex stuff. I get the square and square not part but am unable to find its place. I think I went wrong some place like I can't figure it out.
public static void main(String[] args) {
// part (a) of the main
Scanner keyboard = new Scanner(System.in);
System.out.println("***************************");
System.out.println(" Part (a)");
System.out.println("***************************");
do{
System.out.println("Enter a word and then press enter:");
String str=keyboard.next();
char[] word = str.toCharArray();
isSquareFree(word);
System.out.println("Do you want to test another word? Press y for yes, or another key for no");
}while(keyboard.next().charAt(0)=='y');
public static void isSquareFree(char[] word){
int z = 0;
for(int i=0; i<word.length; i++){
for(int j=0; j<word.length-1;j++){
if (word[j] == word[j+1]){
z = 1;
j = word.length;
}
else{
z = 2;
}
}
}
if (z == 1){
System.out.println();
System.out.println("Not Square Free");
}
else{
System.out.println();
System.out.println("Square Free");
}
}
}
Downvotes on the question: this is not where you solve your homework... we all went through having homeworks and solved them (well, most of us), and that's partly why we're capable of helping you.
You're checking whether the word contains two consecutive characters which are the same.
That's not what you want, try another solution.
Here's why it does what I said above:
The outer for loop doesn't have an effect on the inner one, since i is not used inside
Index j and j+1 in the same iteration as a character and the next one
Other notes:
j = word.length is the same as break here, try using that, it stops your loop like the end condition was satisfied; read more: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
For easier testing, you might want to use another main function containing only calls like isSquareFree("zatabracabrac".toCharArray());, even multiple ones to see multiple test results at once
This will greatly reduce the change-compile-run-check cycle's length.
You can use a debugger in an IDE (Eclipse or IntelliJ) to see what your program does.
Without debugging you can use println/print/printf calls to see how many iterations you have and what your values during those iterations.
Hints on solution:
As I see you're essentially looking for consecutive k-length subword duplicates
You phrased it right in the comment, the arbitrary length is giving it another level
At each position i try to look for a subword with length k which has a corresponding match starting at i + k (this helps the consecutive constraint)
k can be anything between a letter and half of the string (more than that is overkill since it cannot repeat twice)
I didn't code it, but it would be my first try
In your examples:
borborygmus
^=>
i
borborygmus
^=>
i+k
With k = 3 there is a match
zatabracabrac
^===>
i
zatabracabrac
^===>
i+k
With k = 5 there is a match

Java text analysis program

The following requisites are those for the program I'm currently having an issue with:
The program must be able to open any text file specified by the user, and analyze the frequency of verbal ticks in the text. Since there are many different kinds of verbal ticks (such as "like", "uh", "um", "you know", etc) the program must ask the user what ticks to look for. A user can enter multiple ticks, separated by commas.
The program should output:
the total number of tics found in the text
the density of tics (proportion of all words in the text that are tics)
the frequency of each of the verbal tics
the percentage that each tic represents out of all the total number of tics
My program is working very well, but what I basically need to do is that I must use separate methods for each component of the analysis. So I think the idea is that I need to split up the program in a few parts, which I have done by using the comments // because I'm basically having problems determining which type I should return, I know the last part (// public static void output(){)
should definitely be void because it returns nothing and only prints out.
public static void main(String[] args) throws FileNotFoundException {
double totalwords = 0; // double so density (totalwords/totalticks) returned can be double
int totalticks = 0;
System.out.println("What file would you like to open?");
Scanner sc = new Scanner(System.in);
String files = sc.nextLine();
Scanner input = new Scanner(new File(files));
// public static int[] initialise()
System.out.println("What words would you like to search for? (please separate with a comma)");
String ticks = sc.nextLine();
ticks = ticks.toLowerCase();
String[] keys = ticks.split(",");
int[] values = new int[keys.length];
// public static int[] processing(){?
for (int z=0; z<keys.length; z++){
values[z] = 0;
}
while (input.hasNext()){
String next = input.next();
totalwords++;
for (int x = 0; x<keys.length; x++){
if (next.toLowerCase().equals(keys[x])){
values[x]+=1;
}
}
}
for (Integer u : values) {
totalticks += u;
}
//public static void output(){
System.out.println("Total number of tics :"+totalticks);
System.out.printf("Density of tics (in percent): %.2f \n", ((totalticks/totalwords)*100));
System.out.println(".........Tick Breakdown.......");
for (int z = 0; z<keys.length; z++){
System.out.println(keys[z] + " / "+ values[z]+" occurences /" + (values[z]*100/totalticks) + "% of all tics");
}
}
Essentially the problem I'm having is the scope of the variables because Eclipse (my IDE) no longer recognizes the variables within each method once I get them out of comments - I know I need to use some static variables but would really like a hand as to how I could hook my program up together using methods.
Thanks a bunch,
M
You should do an object (class) decomposition. First ask the question "What objects do I have". (At a quick glance you might have "Text" and "Ticks" objects. You then want to see what methods you want to use for each object. For example in Text have countTicks(Ticks). Conotinue in this fashion to decompose your program.
First, please indent your code more consistently, with the first line of a block three spaces farther to the right, such as
for(...) {
//Do stuff
if(...) {
//Do stuff
}
}
It is hard to read what you've posted (luckily someone spruced it up for you!).
Consider re-writing your program from scratch, instead of trying to fix what you already have. Your current knowledge of the problem should allow you to recreate it pretty quickly. You will probably be able to cut and paste bits and pieces from your original code as well.
How about starting small, with something like
Scanner sc = getInputScannerFromUserInput();
private static final Scanner getInputScannerFromUserInput() {
System.out.println("What file would you like to open?");
return new Scanner(System.in);
}
and just go from there. Bit by bit. Good luck!

Categories

Resources