//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.
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 4 years ago.
I have an array of strings - name[]. When I try to take an input from the user using the Scanner class the program seems to ignore the statement and go on to the next.
import java.util.Scanner;
class Student { //start of class
public static void main(String[] args) { //start of method main
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + totalmarks[i]; //calculating total marks
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++) {
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
} //end of method main
} //end of class
That's because the sc.nextInt() method does not read the newline character in your input and so you need to call sc.nextLine()
From the docs
Advances this scanner past the current line and returns the input that
was skipped.
This method returns the rest of the current line, excluding any line
separator at the end. The position is set to the beginning of the next
line.
Since this method continues to search through the input looking for
a line separator, it may buffer all of the input searching for the
line to skip if no line separators are present.
You code will now look like :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
sc.nextLine(); // <----- observe this
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
sc.nextLine(); // <----- observe this
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + totalmarks[i];
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++) {
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
}
Try this.. Your sc.nextLine() is reading empty String after you input integer value
import java.util.Scanner;
class Student
{//start of class
public static void main(String[] args)
{//start of method main
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
String emp = sc.nextLine();
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i=0;i<n;i++)
{
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
emp = sc.nextLine();
}
int sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + totalmarks[i];//calculating total marks
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++)
{
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
}//end of method main
}//end of class
I have this code where I'm able to calculate the average of marks but unable to calculate the sum and percentage.
And I want to print the name of the student under student name but I'm getting only the student number.
I tried understand more about these, but was unable to get through.
Could you please help me out?
package cube;
import java.io.*;
import java.util.Scanner;
public class ReportCard {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int DB[][], nos = 0;
String arrayOfNames[] = new String[nos];
String S = "";
Scanner s = new Scanner(System.in);
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
DB = new int[nos + 1][6];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter " + arrayOfNames[i] + "'s English Score : ");
DB[i][0] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Science Score : ");
DB[i][1] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Maths Score : ");
DB[i][2] = Integer.parseInt(br.readLine());
DB[i][3] = (int) (DB[i][0] + DB[i][1] + DB[i][2] / 3); //calculating the Average Marks of Each Student
DB[i][4] = (int) (DB[i][0] + DB[i][1] + DB[i][2]);
}
}
void PrintReport() {
System.out.println("\nGenerated Report Card :\n\nStudent Name. English Science Maths Average Total\n");
for (int i = 0; i < nos; i++) {
Padd("Student Name. ", (i + 1));
Padd("English ", DB[i][0]);
Padd("Science ", DB[i][1]);
Padd("Maths ", DB[i][2]);
Padd("Average", DB[i][3]);
Padd("Total", DB[i][4]);
System.out.println(S);
S = "";
}
}
void Padd(String S, int n) {
int N = n, Pad = 0, size = S.length();
while (n != 0) {
n /= 10;
Pad++;
}
System.out.print(" " + N);
for (int i = 0; i < size - Pad - 5; i++)
System.out.print(" ");
}
public static void main(String args[]) throws Exception {
ReportCard obj = new ReportCard();
obj.Input();
obj.PrintReport();
}
}
You are initializing your arrayOfNames array to a length of zero always. You should be initializing it once you get the value of the variable nos ( similar to your initialization of 2d array DB)
You are creating the array of names, i.e, arrayOfNames as an array of length 0 because nos is initially zero.
Observe this:
int DB[][],nos=0; //nos is initialized to 0
String arrayOfNames[] = new String[nos]; //arrayOfNames is of size = nos,which is in turn equal to 0, hence arrayOfNames is basically an array which can't hold anything.
instead do this: just declare arrayOfNames and don't initialize it. ==> String arrayOfNames[];
define the string size after you accept the size, i.e, nos. So it should be as follows:
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
arrayOfNames[] = new String[nos]; //now define the size
...
This would ensure that the string is accessible outside the Input() function as well as is defined with a valid size.
Following corrections can make your code run..
package testProgram;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ReportCard {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int DB[][], nos = 0;
//here initaialise reference will null
String arrayOfNames[] = null;
String S = "";
Scanner s = new Scanner(System.in);
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
DB = new int[nos + 1][6];
//create string array object here
arrayOfNames = new String[nos];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter " + arrayOfNames[i] + "'s English Score : ");
DB[i][0] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Science Score : ");
DB[i][1] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Maths Score : ");
DB[i][2] = Integer.parseInt(br.readLine());
//take extra variable that holds total, it increases the readability of the code
int total = DB[i][0] + DB[i][1] + DB[i][2];
DB[i][3] = (total) / 3; //calculating the Average Marks of Each Student
DB[i][4] = total;
}
}
void PrintReport() {
System.out.println("\nGenerated Report Card :\n\nStudent Name. English Science Maths Average Total\n");
for (int i = 0; i < nos; i++) {
Padd("Student Name. ", (i + 1));
Padd("English ", DB[i][0]);
Padd("Science ", DB[i][1]);
Padd("Maths ", DB[i][2]);
Padd("Average", DB[i][3]);
Padd("Total", DB[i][4]);
System.out.println(S);
S = "";
}
}
void Padd(String S, int n) {
int N = n, Pad = 0, size = S.length();
while (n != 0) {
n /= 10;
Pad++;
}
System.out.print(" " + N);
for (int i = 0; i < size - Pad - 5; i++)
System.out.print(" ");
}
public static void main(String args[]) throws Exception {
ReportCard obj = new ReportCard();
obj.Input();
obj.PrintReport();
}
}
Arrays are not dynamic. either you declare its size before hand or you use Arraylist..
boolean loopNaming = true;
int i = 0;
//you are creating array of zero size, use ArrayList instead
// String[] name = new String[i];
ArrayList<String> nameList = new ArrayList<>();
while (loopNaming == true) {
System.out.printf("Enter name of student or done to finish: ");
String name = keyboard.nextLine();
//check if name is 'done'
if (name.equals("done")) {
loopNaming = false;
} else {
nameList.add(name);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
//nextLine positions cursor to next line
keyboard.nextLine();
}
i = i + 1;
}
System.out.println(nameList);
I have this code:
When I launch it, I am able to get numbers i = 0 to i = 10. However I know this is not the objective of the code as the objective is to reach into the Scanner. But the scanner does not seem to work? Am I making an error importing a file or is this to do with the code? I'm noob.
package buggyProgram;
import java.util.Scanner;
public class BuggyProgram {
/**
* The main method of the program. This is where it all starts.
*/
public static void main(String[] args) {
String[] saNames = new String[5];
String[] saNumbers = new String[5];
Scanner scIn = new Scanner(System.in);
for (int i = 0; i <= 4; i++) {
System.out.print("Enter name: ");
saNames[i] = scIn.nextLine();
System.out.print("Enter number: ");
saNumbers[i] = scIn.nextLine();
}
System.out.println();
for (int i = 1; i < 4; i++) {
System.out.println("The number of " + saNames[i] + " is "
+ saNames[i] + ".");
}
}
}
Java arrays start at 0 (not 1), and you're printing the same array element twice (in your second for-loop). Finally, you could always use a debugger to help you determine where things are no longer working as you expect.
// for (int i = 1; i < 4; i++) {
for (int i = 0; i <= 4; i++) { // <-- to match your first loop.
System.out.println("The number of " + saNames[i] + " is "
+ saNumbers[i] + ".");
}
You might also use formatted output (the formatter syntax) like
for (int i = 0; i <= 4; i++) {
System.out.printf("The number of %s is %s.%n", saNames[i], saNumbers[i]);
}
One of the first things you can do to make it easier to debug is to make the input fixed between runs. If you change Scanner scIn = new Scanner(System.in); to this:
Scanner scIn = new Scanner(new BufferedReader(new FileReader("some-file.txt")));
Assuming that some-file.txt is populated with the appropriate input, then you can run the program multiple times without having to manually re-enter the input. In addition, the input is fixed, so comparing the output of different runs becomes more useful.
I can confirm, that your code works, as long as you change your final output:
String[] saNames = new String[5];
String[] saNumbers = new String[5];
Scanner scIn = new Scanner(System.in);
for (int i = 0; i <= 4; i++) {
System.out.print("Enter name: ");
saNames[i] = scIn.nextLine();
System.out.print("Enter number: ");
saNumbers[i] = scIn.nextLine();
}
System.out.println();
for (int i = 1; i < 4; i++) {
System.out.println("The number of " + saNames[i] + " is "
+ saNumbers[i] + ".");
}
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;
}
}
I have two scanner that scans for currency and weight from external text file. 1st scanner for Currency and 2nd scanner for Weight. The problem here is, only the top scanner works, second scanner does not provide any output. How can i reset the 2nd scanner to start reading from top of file once 1st scanner have finish scanning and give output. Below are the 2 scanners
Scanner for Currency
String sc[]= {myTextCount};
String value, currency;
for(String ssc : sc){
Scanner scan = new Scanner(ssc);
while (scan.hasNextLine()) {
value = scan.findInLine("\\d+(\\.\\d+)?");
currency = scan.next();//scan.next("\\w+");
try {
float f = Float.valueOf(value.trim()).floatValue();
for(int j = 0; j < currencyWords.length; j++) {
if ((currency).equals(currencyWords[j])) {
jTextArea2.append(f + currencyWords[j] + "-" +currencyFile + "\n");
currency = scan.next();//scan.next("\\w+");
}
}
}catch (NumberFormatException e){
//System.err.println("NumberFormatExceptionsssss: " + nfe.getMessage());
}
}
}
Scanner for Weight
String s[]= {myTextCount};
String weight, unit;
for(String ss : s){
Scanner scanC = new Scanner(ss);
while (scanC.hasNextLine()) {
weight = scanC.findInLine("\\d+(\\.\\d+)?");
unit = scanC.next();//scan.next("\\w+");
try {
float f = Float.valueOf(weight.trim()).floatValue();
for(int j = 0; j < weightWords.length; j++) {
if ((unit).equals(weightWords[j])) {
jTextArea2.append(f + weightWords[j] + "-" +weightFile + "\n");
unit = scanC.next();//scan.next("\\w+");
}
}
}catch (NumberFormatException e){
//System.err.println("NumberFormatExceptionsssss: " + nfe.getMessage());
}
}
}
I have tried using break but still does not work. Only 1st scanner runs and second scanner does not run. Help me to show algorithm on how i can reset the scanners
I solved it by joining both scanners.
String s[]= {myTextCount};
String weight, unit;
for(String ss : s){
Scanner scanC = new Scanner(ss);
while (scanC.hasNextLine()) {
weight = scanC.findInLine("\\d+(\\.\\d+)?");
unit = scanC.next();//scan.next("\\w+");
try {
float f = Float.valueOf(weight.trim()).floatValue();
for(int j = 0; j < weightWords.length; j++) {
for(int g = 0; g < currencyWords.length; g++) {
if ((unit).equals(weightWords[j])) {
jTextArea2.append(f + weightWords[j] + "-" +weightFile + "\n");
unit = scanC.next();//scan.next("\\w+");
} scanC.reset();
if ((unit).equals(currencyWords[g])) {
jTextArea2.append(f + currencyWords[g] + "-" +currencyFile + "\n");
unit = scanC.next();//scan.next("\\w+");
}scanC.reset();
}
}
}catch (NumberFormatException e){
//System.err.println("NumberFormatExceptionsssss: " + nfe.getMessage());
}
} scanC.close();
}