I am a beginner with weak understanding of java. Please could you help me correct the error saying:
// [line 45] Syntax error on token " (", ; expected
On the line:
private static int countWords(String str) {
This error appears twice on this line. I've tried experimenting with adding and deleting brackets and I've tried adding ';' to my code but it only makes the code display more errors. Underneath there is my code to help identify the error better:
import java.util.*;
public class HDtest9 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) { // have created infinite loop
System.out.print("Enter text: ");
String sentence = in.nextLine();
System.out.println("You have entered: " + sentence); // to Print string
System.out.println("The total number of characters is " + sentence.length()); // to print Entered string's length
System.out.println("This piece of text has " + countWords(sentence) + " words.");
if (sentence.equals("quit")) { // if enterd value is "quit" than it comes out of loop
break;
} else {
String[] words = sentence.split(" "); // get the individual words
int maxWordLength = 0;
int wordLength = 0;
for (int i = 0; i < array.length; i++) {
wordLength = array[i].length();
if (wordLength > maxWordLength) {
maxWordLength = wordLength;
}
int[] intArray = new int[maxWordLength + 1];
for (int i = 0; i < array.length; i++) {
intArray[array[i].length()]++;
for (int i = 1; i < intArray.length; i++) {
out.printf("%d word(s) of length %d<br>", intArray[i], i);
}
}
for (int i = 0; i < words.length; i++)
System.out.println( "word " + i + ": " + words[i] + " = " + words[i].length() + " characters");
}
}
in.close();
}
private static int countWords(String str) {
String words[] = str.split(" ");
int count = words.length;
return count;
}
}
}
Thank you very much for any help, it's much appreciated!
You are trying to declare your countWords() method inside your main() method, which isn't legal in Java, so the compiler is choking trying to parse your method signature.
If you move it outside where it belongs, you will only have the other 8 or so undeclared and duplicate variable errors left to deal with.
Please use proper indentation and naming in your code. It will help you (and others) read it, and prevent this sort of mistake.
On the line:
for (int i = 0; i < words.length; i++)
You have no opening curly brace
Change to:
for (int i = 0; i < words.length; i++) {
Also, please fix your indentation, it is very hard to read and see if there are any more bugs.
Corrected and working code
import java.util.*;
public class HDtest9 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) { // have created infinite loop
System.out.print("Enter text: ");
String sentence = in.nextLine();
System.out.println("You have entered: " + sentence); // to Print string
System.out.println("The total number of characters is " + sentence.length()); // to print Entered string's length
System.out.println("This piece of text has " + countWords(sentence) + " words.");
if (sentence.equals("quit")) { // if enterd value is "quit" than it comes out of loop
break;
} else {
String[] words = sentence.split(" "); // get the individual words
int maxWordLength = 0;
int wordLength = 0;
for (int i = 0; i < words.length; i++) {
wordLength = words[i].length();
if (wordLength > maxWordLength) {
maxWordLength = wordLength;
}
}
int[] intArray = new int[maxWordLength + 1];
for (int i = 0; i < words.length; i++) {
intArray[words[i].length()]++;
}
for (int i = 1; i < intArray.length; i++) {
System.out.printf("%d word(s) of length %d<br>", intArray[i], i);
}
for (int i = 0; i < words.length; i++) {
System.out.println("word " + i + ": " + words[i] + " = " + words[i].length() + " characters");
}
}
}
in.close();
}
private static int countWords(String str) {
String words[] = str.split(" ");
int count = words.length;
return count;
}
}
Related
So there is a logic error inside my simple java counting words, first of in cmd, it's asking me to type the string twice, when it should show once
I run this in cmd, here is the output:
C:\Users\Me\Documents>java count
shapeshifting
shapeshifting
Number of Occurrence of s is 2 in string shapeshifting
s
2
import java.util.Scanner;
public class count5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char key = input.nextLine().charAt(0);
countString(str, key);
}
public static void countString(String str, char key) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == key)
count++;
}
System.out.println("Number of Occurrence of "
+ key + " is " + count + " in string " + str);
for (int i = 0; i < count; i++) {
System.out.println(key);
}
if (count > 0) {
System.out.println(count);
}
}
}
So here some thing that confuses me:
why is there 3 lines needed allow user to type an input. I thought the previous line already let me enter the input. What is char key = input.nextLine().charAt(0); needed for, and the previous line? Shouldn't there be only input entering line?
Why is there 2 for loops inside the code, don't they do same thing?
Try this solution which should ask for one time input and traverse the complete input string entered for the match
import java.util.Scanner;
public class stringCompair {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
for(int i=0 ; i < str.length();i++) {
char key = str.charAt(i);
countString(str, key);
}
}
public static void countString(String str, char key) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == key)
count++;
}
System.out.println("Number of Occurrence of "
+ key + " is " + count + " in string " + str);
}
}
So I recently got an this assignment in class and need help, I've checked out other questions but couldn't find one that was similar to what my teacher was asking for. She is pretty strict and want's things exactly how they're asked for.
"Create a class called MultiplicationTable and MultiplicationTableTester. A multiplication table has a max.
The Multiplication table should have method called String createMultiplcationTable() that creates a multiplication table.
Use “\n” to obtain a new line, the program should use the string “\t” to tab to the next tab position, so that the information is displayed neatly
in the columns. The MultiplicationTableTester class should prompt the user for the max (don’t allow the user to enter negative number,
if they do continue prompting them for a valid value until one is entered)."
This is my horrible attempt at doing this
/* MultiplicationTable.java*/
public class MultiplacationTable {
private int maxNum;
private int i = 1;
public MultiplacationTable(int n) {
Scanner in = new Scanner(System.in);
maxNum = in.nextInt();
n = maxNum;
}
public String createMultiplacationTable() {
String row = "";
String col = "";
String tmpRow= "";
String tmpCol = "";
String table = "";
while (i < maxNum) {
tmpRow = "" + i;
i++;
row += tmpRow + "\t";
tmpCol = "" + i;
i++;
col += tmpCol + "/n";
for (int j = 1; j < maxNum; j++) {
System.out.print(" " + i * j);
}
table = row + col;
}
return table;
}
}
Didn't know what to do with the tester besides print out the method
/*MultiplicationTableTester*/
public class MultiplacationTableTester {
public static void main (String[] args) {
System.out.print("Please input a number: ");
MultiplacationTable mT = new MultiplacationTable(0);
System.out.print(mT.createMultiplacationTable());
}
}
My output using 5 as input is
Please input a number: 5
3 6 9 12 5 10 15 201 3 2/n4/n
So obviously really wrong. I have a feeling what I'm doing wrong has to do with the "/n" and "\t". Any help?
I didn't test it but it should work. Don't hesitate to ask if you don't understand anything. I hope it's clean and nice enough.
Multiplication Table Tester
public class MultiplicationTableTester {
public static void main (String[] args) {
int maxNum;
System.out.println("Please enter a number: ");
Scanner in = new Scanner(System.in);
maxNum = in.nextInt();
MultiplicationTable mT = new MultiplicationTable(maxNum);
System.out.print(mT.createMultiplicationTable());
}
}
MultiplicationTable.java
public class MultiplicationTable {
private int maxNum;
public MultiplicationTable(int maxNum) {
this.maxNum = maxNum;
}
public String createMultiplicationTable() {
StringBuilder table = new StringBuilder();
for(int i = 1; i<=maxNum;i++){
for(int j = 1; j<=10; j++){
table.append(i*j);
table.append("\t");
}
table.append("\n");
}
return table.toString();
}
}
change "/n" with "\n"
public String createMultiplacationTable() {
String row = "";
String col = "";
String tmpRow= "";
String tmpCol = "";
String table = "";
while (i < maxNum) {
tmpRow = "" + i;
i++;
row += tmpRow + "\t";
tmpCol = "" + i;
i++;
col += tmpCol + "\n";
for (int j = 1; j < maxNum; j++) {
System.out.print(" " + i * j);
}
table = row + col;
}
return table;
}
}
I want to read a number from the user and then sum the last seven digits of the entered number. What is the best way to do this? This is my code, but unfortunately it does not work:
class ersteAufgabe {
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
double [] a = new double[10];
for (int i = 0;i<10;i++)
{
a[i]=s.nextInt();
}
s.close();
System.out.println(a[0]);
}
}
I wanted only one number to be read and used as an array. Only now he expects 10 inputs from me.
public static int lastDigitsSum(int total) {
try (Scanner scan = new Scanner(System.in)) {
String str = scan.next();
int count = 0;
for (int i = str.length() - 1, j = 0; i >= 0 && j < total; i--, j++) {
if (Character.isDigit(str.charAt(i)))
count += str.charAt(i) - '0';
else
throw new RuntimeException("Input is not a number: " + str);
}
return count;
}
}
First you have to recognize if the entered value is a number and has at least 7 digits. Unless you have to output an error message. Convert the entered value to String and use the class Character.isDigit(); to check if the characters are numbers. Then you can use some methods from the String class like substring(..). At the end do a Unit-Test with erroneous/valid values to see if your code is robust. Close the BufferedReader and Resources when you are done by using finally { br.close() }. Push your code in methods and use an instance class erste-Aufgabe (first exercise).. When you are really really done use JFrame for a GUI-Application.
private static final int SUM_LAST_DIGITS = 7;
public void minimalSolution() {
String enteredValue = "";
showInfoMessage("Please enter your number with at least " + SUM_LAST_DIGITS + " digits!");
try (Scanner scan = new Scanner(System.in)) {
enteredValue = scan.next();
if (enteredValue.matches("^[0-9]{" + SUM_LAST_DIGITS + ",}$")) {
showInfoMessage(enteredValue, lastDigitsSum(enteredValue));
} else {
showErrorMessage(enteredValue);
}
} catch(Exception e) {
showErrorMessage(e.toString());
}
}
public int lastDigitsSum(String value) {
int count = 0;
for (int i = value.length() - 1, j = 0; i >= 0 && j < SUM_LAST_DIGITS; i--, j++)
count += value.charAt(i) - '0';
return count;
}
public void showInfoMessage(String parMessage) {
System.out.println(parMessage);
}
public void showInfoMessage(String parValue, int parSum) {
System.out.println("Your entered value: [" + parValue + "]");
System.out.println("The summed value of the last 7 digits are: [" + parSum + "]");
}
public void showErrorMessage(String parValue) {
System.err.println("Your entered value: [" + parValue + "] is not a valid number!");
}
package assignment2;
import java.util.Random;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
int wordAmount = wordAmount();
String[] words = wordArray(wordAmount);
displayWords(words, wordAmount);
char[][] puzzleGrid = generatePuzzleGrid(words, wordAmount);
//System.out.println(Arrays.deepToString(puzzleGrid)); //just using this to test
printPuzzleGrid(puzzleGrid, wordAmount);
}
public static int wordAmount(){
Scanner input = new Scanner(System.in);
System.out.print("How many words would you like in the word search(5-15): ");
int wordAmount = input.nextInt();
while(wordAmount < 5 || wordAmount > 20){
System.out.println("The number you've requested is either to large or to small.");
System.out.print("How many words would you like in the word search(5-20): ");
wordAmount = input.nextInt();
}
return wordAmount;
}
public static String[] wordArray(int wordAmount){
String[] words = new String[wordAmount];
Scanner input = new Scanner(System.in);
for(int i = 0; i < wordAmount; i++){
System.out.print("Enter a word: ");
words[i] = (input.nextLine().toUpperCase());
for(int j = 0; j < wordAmount; j++){
if(j == i) break;
while(words[i].contains(words[j])){
System.out.print("The word you entered has already been entered, enter a new word: ");
words[i] = (input.nextLine().toUpperCase());
}
}
while(words[i].length() > 10 || words[i].length() <= 2 || words[i].contains(" ")){
System.out.print("The word you entered has been rejected, enter a new word: ");
words[i] = (input.nextLine().toUpperCase());
}
}
return words;
}
public static void displayWords(String[] words, int wordAmount){
System.out.print("The words you must find are: ");
for(int w = 0; w < wordAmount; w++){
System.out.print(words[w] + " ");
}
System.out.println("");
}
public static char[][] generatePuzzleGrid(String[] words, int wordAmount){
char[][] puzzleGrid = new char[wordAmount][wordAmount];
Random rand = new Random();
for(int across = 0; across < wordAmount; across++){
for(int down = 0; down < words[across].length(); down++){
puzzleGrid[across][down] = words[across].charAt(down);
for(int filler = wordAmount; filler >= words[across].length(); filler--){
puzzleGrid[across][filler] = (char)(rand.nextInt(26) + 'A'); //this is the line with the problem
}
}
}
return puzzleGrid;
}
public static void printPuzzleGrid(char[][] puzzleGrid, int wordAmount){
for(int across = 0; across < wordAmount; across++){
for(int down = 0; down < wordAmount; down++){
System.out.print(" " + puzzleGrid[down][across]);
}
System.out.println("");
}
}
}
It seems my last problem has worked itself out, but now I face a new problem.
Error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at assignment2.test2.generatePuzzleGrid(test2.java:63)
at assignment2.test2.main(test2.java:10)
C:\Users\Higle\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 9 seconds)
It seams application runs without any issue only concern is that what will happen if the user provide wordAmount( number of characters in grid ) greater than the word he provided. So it's better to add validation on wordAmount with word length as show on below.
public static char[][] generatePuzzleGrid(String[] words, int wordAmount) {
if(wordAmount>words.length){
wordAmount = words.length;
}
char[][] puzzleGrid = new char[wordAmount][wordAmount];
for (int across = 0; across < wordAmount; across++) {
for (int down = 0; down < words[across].length(); down++) {
puzzleGrid[across][down] = words[across].charAt(down);/////////////////
}
}
return puzzleGrid;
}
It looks like you're calling charAt(5) on a string of less than 5 characters. You can do something like
if(words[across].length() < (down-1)){
continue;
}
to make sure you don't get that particular error... Also, you may like to know charAt() returns the index of a char from 0->length()-1
//Calculating term frequency
System.out.println("The number of files is this folder is : " + numDoc);
System.out.println("Please enter the required word :");
Scanner scan = new Scanner(System.in);
String word = scan.nextLine();
String[] array = word.split(" ");
int filename = 11;
String[] fileName = new String[filename];
int a = 0;
for (a = 0; a < filename; a++) {
try {
System.out.println("The word inputted is " + word);
File file = new File(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + a
+ ".txt");
System.out.println(" _________________");
System.out.print("| File = abc" + a + ".txt | \t\t \n");
for (int i = 0; i < array.length; i++) {
int totalCount = 0;
int wordCount = 0;
Scanner s = new Scanner(file);
{
while (s.hasNext()) {
totalCount++;
if (s.next().equals(array[i]))
wordCount++;
}
System.out.print(array[i] + " ---> Word count = "
+ "\t\t " + "|" + wordCount + "|");
System.out.print(" Total count = " + "\t\t " + "|"
+ totalCount + "|");
System.out.printf(" Term Frequency = | %8.4f |",
(double) wordCount / totalCount);
System.out.println("\t ");
}
}
} catch (FileNotFoundException e) {
System.out.println("File is not found");
}
}
// Count inverse document frequency
System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan2.nextLine();
String[] array2 = word2.split(" ");
for (int b = 0; b < array2.length; b++) {
int numofDoc = 0;
for (int i = 0; i < filename; i++) {
try {
BufferedReader in = new BufferedReader(new FileReader(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc"
+ i + ".txt"));
int matchedWord = 0;
Scanner s2 = new Scanner(in);
{
while (s2.hasNext()) {
if (s2.next().equals(array2[b]))
matchedWord++;
}
}
if (matchedWord > 0)
numofDoc++;
} catch (IOException e) {
System.out.println("File not found.");
}
}
System.out.println(array2[b] + " --> This number of files that contain the term " + numofDoc);
double inverseTF = Math.log10 ( (float)numDoc/ numofDoc );
System.out.println(array2[b] + " --> IDF " + inverseTF);
double TFIDF = ((double) wordCount / totalCount)) * inverseTF);
}
}
I could not calculate the TFIDF because the compiler says that wordCount does not initialize to a variable. I could not call it from above code. Any guidance ? Thank you.
wordCount is a local variable that is declared in for loop. Once the loop is over, it goes out of scope and cannot be used. Same is the problem with totalCount too. Place it before for loop, instead;
int wordCount = 0;
int totalCount = 0;
for (a = 0; a < filename; a++) {
// ....
}
for (int i = 0; i < array.length; i++) {
int totalCount = 0;
int wordCount = 0;
This defines totalCount and wordCount in the scope of that for-loop. You are trying to access these variables from outside the for-loop (down below). What you can do is more these declarations to the top, e.g. where you write String word = scan.nextLine();.
Because you initilialize the wordCount varibale in the location unreachbale to
double TFIDF = ((double) wordCount / totalCount)) * inverseTF);
wordCount is defined inside of your for loop and you're trying to access the variable outside of the said loop, this can't work.
You must move the variable definition somewhere else, for example at the beginning of your method.