What variable needs to be identified? - java

I am a beginner in java. There is an error which appears 15 times in lines 24, 27, 29, 30, 35, 36, 37, 42, 43 and 46, saying:
//Tokens cannot be resolved to a variable
And:
// i cannot be resolved to a variable
What variables do these errors want to identify? Because I thought I identified everything and I don't understand what variables my code still needs.
Here is my code:
import java.util.Scanner;
public class Jo_code {
public static int wordFrequency(String s) {
String tokens[] = s.split(" ");// splits the words
int count = tokens.length;
return count;
}
public static void main(String args[]) {
System.out.println("Write your sentence or type END to quit the program:");// prints out the first instruction.
Scanner scan = new Scanner(System.in); //object initialisation.
String line = " ";//declaration for letters(String) characters.
int max = 20; //declaration for number(int) characters.
while ((line = scan.nextLine()) != null) { //scanner instruction, get a line from the key board.
if (line.equals("END")) {
break;// if you are happy with the code, then type "END", and the code will stop running.
} else { // if you decide not to type "END" the program will continue to allow you to type sentences.
String[] array = line.split(" ");// splits the words
System.out.println("your sentence is " + line);//prints out what you have typed.
System.out.println("The total of words for the line is " + tokens.length);// prints out the total of words that you have typed.
int maxTokensLength = 0;
int tokensLength = 0;
for (int i = 0; i < tokens.length; i++) {// this line of code checks for what must be true to carry on.
array[i] = array[i].replaceAll("a-zA-Z]", "");
}
tokensLength = array[i].length();
tokensLength = tokens[i].length();
if (tokensLength > maxTokensLength) {
maxTokensLength = tokensLength;
}
}
}
int[] intArray = new int[maxTokensLength + 1];
for (int i = 0; i < tokens.length; i++) { // this line of code checks for what must be true to carry on.
intArray[array[i].length()]++;
}
for (int i = 1; i < intArray.length; i++) { // this line of code checks for what must be true to carry on.
System.out.printf("%word(s) of length %d<br>", intArray[i], i);
}
for (int i = 0; i < tokens.length; i++) { // this line of code checks for what must be true to carry on.
System.out.println("word " + i + ": " + tokens[i] + " = " + tokens[i].length() + " characters");
}
System.out.println("The length for the word " + tokens[i] + " is = " + tokens[i].length());//This line of code prints out the word frequency for each word.
System.out.println("The word frequency of the whole sentence is =");//results
System.out.println("type END to quit");//instructions
}
}
Thank you very much for any help, its much appreciated!

For one thing, your very first for loop has no open and close brackets. This means only the first statement is considered part of the for loop. so the statement 'tokensLength = array[i].length();' can't reach the variable i because it is not in the for loop. I believe adding open and close brackets around everything you want in the first for loop should fix it

Related

Printing the i'th character of each i'th word instead of just one

I am working on a simple program where the goal is to print the i'th character of each i'th word that the user inputs. I have the number of words set to 5 as an example, and so the user needs to enter 5 words. However, the program returns the i'th character of just one of the i'th words (I have "i" set to 2). How would I fix this so that it prints the i'th character for each i'th word, instead of just one of the i'th words?
Here is my code for reference:
import java.util.Scanner;
public class Words {
public static void main(String[] args) {
int numWords = 5;
Scanner keyboard = new Scanner(System.in);
String[] words = new String[numWords];
System.out.print("Enter " + numWords + " words: ");
for (int i = 0;i<numWords;i++) {
String word = keyboard.next();
words[i] = word;
}
keyboard.close();
int iVal = 2;
int length = words[iVal].length();
if (iVal >= (length - 1)) {
System.out.print(words[iVal].charAt(length-1));
}
else {
System.out.print(words[iVal].charAt(iVal));
}
}
}
This is the output I get as an example:
Enter 5 words: one two three four five
r
The loop may be implemented similar to what has already been implemented:
for (int i = 0; i < numWords; i++) {
String word = words[i];
if (i < word.length()) {
System.out.println("char #" + i + " = " + word.charAt(i));
} else {
System.out.println("Word + " + word + " is too short to get char #" + i);
}
}
This simply splits the string on spaces and the prints the ith-1 character of the ith word (so the first word would be character at 0, the second word would be character at 1 and so forth). If the word is too short, it is skipped.
String str = "A is for apple and E is for Encyclopedia";
int i = 0;
for (String s : str.split("\\s+")) {
if (i < s.length()) {
System.out.println(s + " --> " + s.charAt(i));
}
i++;
}
Prints
A --> A
is --> s
for --> r
apple --> l
Encyclopedia --> e

Having problems when comparing two arrays

The program is supposed to translate a word from American to British version. It only works for the first word but it doesn't work for the other words because it gives the else statement instead.
My code:
import java.util.Scanner;
public class BritishTranslator {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String word;
String [] america = new String[8];
String [] british = new String[8];
america[0] = "attic";
america[1] = "business suit";
america[2] = "elevator";
america[3] = "frenc fries";
america[4] = "ice cream";
america[5] = "sneakers";
america[6] = "truck";
america[7] = "zero";
british[0] = "loft";
british[1] = "lounge suit";
british[2] = "lift";
british[3] = "chips";
british[4] = "ice";
british[5] = "plimsolls";
british[6] = "lorry";
british[7] = "nough";
System.out.println("Please enter an American word: ");
word = input.nextLine();
for (int i = 0; i < america.length; i++)
{
for(int j = 0; j < british.length; j++)
{
if (word.equals(america[i]))
{
System.out.println(america[i] + " in british is: " + british[j]);
System.exit(0);
}
else
{
System.out.println("Word not found in the dictionary.");
System.exit(0);
}
}
}
}
}
I need help learning how to debug this code.
you just need to iterate over the america array, if you find the word look at the same index in the british array.
and the else out of the loop
for (int i = 0; i < america.length; i++){
if (word.equals(america[i])) {
System.out.println(america[i] + " in british is: " + british[i]);
System.exit(0);
}
}
System.out.println("Word not found in the dictionary.");
System.exit(0); // you dont need this as well
}
Since the 2 arrays contain the word-translation in the same index, you don't have to iterate through the 2nd table. Just find the index of word in the 1st table and use this index to get the translation in the 2nd table. Also use a boolean flag found to check after the loop if the word is not found:
System.out.println("Please enter an American word: ");
word = input.nextLine();
boolean found = false;
for (int i = 0; i < america.length; i++) {
found = word.equals(america[i]);
if (found) {
System.out.println(america[i] + " in british is: " + british[i]);
break;
}
}
if (!found)
System.out.println("Word not found in the dictionary.");
With the use of break the loop stops as soon as the word is found.
Since you are pairing your american words to your french words, you only need to loop the arrays once and if the word equals your american word then you want to print the string at the same index in both your french array and american array.
for (int i = 0; i < america.length && i < british.length; i++)
{
if (word.equals(america[i]))
{
System.out.println(america[i] + " in british is: " + british[i]);
System.exit(0);
}
}
System.out.println("Word not found in the dictionary.");
I believe you have a couple things going on here.
First, I think you don't want to do your else statement until after you have gone through the loop. As it is currently written, it will terminate as soon as your first 'if' statement fails due to the nature of your if/else and the System.exit(0) call.
System.out.println("Please enter an American word: ");
word = input.nextLine();
for (int i = 0; i < america.length; i++)
{
for(int j = 0; j < british.length; j++)
{
if (word.equals(america[i]))
{
System.out.println(america[i] + " in british is: " + british[j]);
System.exit(0);
}
}
}
System.out.println("Word not found in the dictionary.");
System.exit(0);
However, you don't actually need the second loop, since you have the index that you've found when you are iterating through your first loop, so you can further simplify your answer to.
System.out.println("Please enter an American word: ");
word = input.nextLine();
for (int i = 0; i < america.length; i++)
{
if (word.equals(america[i]))
{
System.out.println(america[i] + " in british is: " + british[i]);
System.exit(0);
}
}
System.out.println("Word not found in the dictionary.");
System.exit(0);
Since the values are mapped via index, you're able to directly access the thing you wish to translate without having a second loop, making your program faster and less complex!

Program counts dots(.) as alphabetic characters

So my task was to create a program that takes a file as input and counts the occurrences of each alphabetic character in it. Then I shall print the letter, the amount of times it occurs and the frequency of it.
And I get it to work almost as planned. The only problem I have is that when I print, it also prints the number of dots(.) in the file. And I can't stop it from doing that. Help please..
public class CountOccurences {
private static Scanner input;
public static void main(String [] args) throws FileNotFoundException {
DecimalFormat dec = new DecimalFormat("#.000");
input = new Scanner(new File("story.txt"));
int[] ltrCtr = new int[127]; // This array counts the number of occurences for every letter / symbol on the ascii table.
String str = "";
// Puts the textfile as a String
while(input.hasNext()) {
str += input.next();
}
char[] text = str.toCharArray();
char temp; int tempInt;
int ctr = 0;
for(int i = 0; i < text.length; i++) { // Loops through the text
temp = text[i]; // Gets the char at i
tempInt = (int)temp; // Get the ascii value of the char at i
ltrCtr[tempInt]++;
if(Character.isAlphabetic(text[i])) {
ctr++;
}
}
System.out.println("Letter" + " Amount" + " Freq");
for(int i = 0; i < ltrCtr.length; i++) {
if(ltrCtr[i] >= 1 && (int)ltrCtr[i] != 46) {
System.out.println(" " + (char)i + " " +
ltrCtr[i] + " " +
dec.format((double)ltrCtr[i]/ctr) + "%");
}
}
input.close();
}
}
I believe you meant to use isLetter, not isAlphabetic.
Mureinik is right, isLetter solves your problem. Here's a post explaining the differences between isLetter and isAlphabetic to make it clearer: What is the difference between Character.isAlphabetic and Character.isLetter in Java?

Java program keeps exiting program prematurely

I need to build a simple automaton for my Automata class. I am using Java and I cannot figure out for the life of me why my program keeps exiting prematurely. I've tried debugging it, having print statements everywhere to figure out where it's stopping, and although I know where it stops, I do not see anything that would make the program stop working. The stoppage happens on line 27 (Right where I SOP "Enter a string of digits...".
Knowing me it's probably something simple, but I cannot figure this one out.
import java.util.*;
public class hw1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please indicate the number of states");
int numState = input.nextInt();
int[] state = new int[numState];
boolean[] accept = new boolean[numState];
for (int i = 0; i < numState; i++) {
System.out.println("Is the state q" + (i + 1) + " a final state? (Answer 1 for yes; 0 for no)");
int finalState = input.nextInt();
if (finalState == 1)
accept[i] = true;
} // for
System.out.println("Enter the number of symbols s: ");
int numSym = input.nextInt();
int[][] next = new int[numState][numSym];
for (int i = 0; i < numState; i++) {
for (int j = 0; j < numSym; j++) {
System.out.println("What is the number for the next state for q" + i + " when it gets symbol " + j);
next[i][j] = input.nextInt();
}//nested for
}//for
String digits = input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
int[] digitArray = new int[digits.length()];
for (int i = 0; i < digits.length(); i++) {
digitArray[i] = digits.charAt(i);
}
for (int i = 0; i < digits.length(); i++) {
System.out.print(digitArray[i] + " ,");
}
System.out.println("end of program");
}// main;
}// class
Change your code to :
input.nextLine();
System.out.print("Enter a string of digits (0-9) without spaces to test:");
String digits = input.nextLine();
This will get and ignore the newline character left in the stream after call to nextInt()

out of bounds error with word count

I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}

Categories

Resources