import static java.lang.System.*;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
public class Experiment
{
private int periodCount = 0;
private String para = "";
public static void main( String args[] ) throws IOException
{
Scanner file = new Scanner(new File("example.dat"));
public int getNumberString()
{
String vowels = " ";
int count = 0;
String para = file("example.dat");
for(int index = 0; index < para.length(); index++)
{
if(vowels.indexOf(para.charAt(index)) >= 0)
{
count++;
}
return count;
}
}
//file.nextLine();
public int periodCounter()
{
int size = getNumberString();
for(int i = 0; i < size; i++)
{
if(para.charAt(i + 1) == '.')
periodCount++;
}
return periodCount;
}
public String Decider()
{
if(periodCount() <= 30)
return "Average";
if (periodCount() >= 30)
return "high";
}
System.out.println("This paragragh is a reading level" + Decider());
}
Hi! to be clear I was just messing around with this but now I want to see if it will work. The goal is to take count of the number of spaces in a paragraph on a dat file document and use that as a stopping point for a method to find the number of periods in a paragraph and determine the reading level from there.
I'm pretty new to java so this is just me throwing things around that I think will work
The issue is that it says both
my getNumberString and periodCounter functions are Experiment.java:18: error: illegal start of expression and that my print command is Experiment.java:45: error: <identifier> expected and Experiment.java:45: error: illegal start of type
additionally, if you find any thing you might want to comment on feel free to!!
Look where your { and } match up. You've defined getNumberString() inside the body of your main() method. You're probably missing a closing } after your Scanner declaration line (and some other code that calls your other methods.
"Experiment.java:18: error: illegal start of expression" is telling you that you can't start a method declaration at this location, this is not valid syntax.
Related
Hi I have this code to get shortest word in a string:-
import java.util.Arrays;
public class Kata {
public static int findShort(String s) {
int shortestLocation = null;
String[] words = s.split("");
int shortestLength=(words[0]).length();
for(int i=1;i<words.length;i++){
if ((words[i]).length() < shortestLength) {
shortestLength=(words[i]).length();
shortestLocation=shortestLength;
}
}
int p = shortestLocation;
return p;
}
}
It returns error that variable shortestLocation cannot be converted to int:-
java:6: error: incompatible types: <null> cannot be converted to int
int shortestLocation = null;
My question is how do you access the scope of a variable,like in this case I know what is wrong. The variable shortest location is defined outside the scope of if statement,hence it considers only the value with which it was initialized.
How do i make it so that the initial value is changed to the if-statement value. It is a scope problem,please help i am beginner.
import java.util.Arrays;
public class Kata {
public static int findShort(String s) {
int shortestLocation = null;
this ^^ line needs to be initialized to an integer... not 'null' 0 is fine
String[] words = s.split("");
int shortestLength=(words[0]).length();
for(int i=1;i<words.length;i++){
your problem starts here ^^ you never iterate through all of the words as you stop at i<words.length the problem with that is you begin at i=1. for loops work like this for (begin here; until this is not met; do this each time) when i=words.length the condition is no longer met.
if ((words[i]).length() < shortestLength) {
shortestLength=(words[i]).length();
shortestLocation=shortestLength;
}
}
int p= shortestLocation;
No need to initialize p here... just return shortest location.
return p;
}
}
that leaves the final code like this
import java.util.Arrays;
public class Kata {
public static int findShort(String s) {
int shortestLocation = 0;
String[] words = s.split("");
int shortestLength=(words[0]).length();
for(int i=0;i<words.length;i++){
if ((words[i]).length() < shortestLength) {
shortestLength=(words[i]).length();
shortestLocation=shortestLength;
}
}
return shortestLocation;
}
}
Keep in mind, to get a 'good' result it HEAVILY weighs on the words list
As pointed out in the comments initializing your original 'int p' could help with debugging.
I have the following error when I run my parser program,
Error: Main method not found in class TfIdfMain, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Also in my main method, there is a error like this, but I already created the parserfile error in parser class,
Multiple markers at this line
- Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit
constructor
- Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an
explicit constructor
Also in my parser class, there is an error around the array list line, it says array cannot be resolved, how should I fix this? Create a new variable.
Here are my two main classes involved the errors:
import java.io.FileNotFoundException;
import java.io.IOException;
public class TfIdfMain {
}
// public static void main(String args[]) throws FileNotFoundException, IOException {
// DocumentParser dp = new DocumentParser();
// dp.parseFiles("C:\\Users\\Sarah\\Documents");
// dp.getCosineMatrix();
// }
}
}
My document parser class:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
public class DocumentParser {
private void doSomething(){
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
if (f.getName().endsWith(".txt")) {
in = new BufferedReader(new FileReader(f));
StringBuilder sb = new StringBuilder();
String s = null;
while ((s = in.readLine()) != null) {
sb.append(s);
}
String[] tokenizedTerms = sb.toString().replaceAll("[\\W&&[^\\s]]", "").split("\\W+"); //to get individual terms
for (String term : tokenizedTerms) {
if (!allTerms.contains(term)) {
allTerms.add(term);
}
}
termsDocsArray.add(tokenizedTerms);
}
}
}
public void tfIdfCalculator() {
double tf;
double idf;
double tfidf;
for (String[] docTermsArray : termsDocsArray) {
double[] tfidfvectors = new double[allTerms.size()];
int count = 0;
for (String terms : allTerms) {
tf = new TfIdf().getTf(docTermsArray, terms);
idf = new TfIdf().idfCalculation(termsDocsArray, terms);
tfidf = tf * idf;
tfidfvectors[count] = tfidf;
count++;
}
tfidfDocsVector.add(tfidfvectors);
}
}
public void getCosineMatrix() {
for (int i = 0; i < tfidfDocsVector.size(); i++) {
for (int j = 0; j < tfidfDocsVector.size(); j++) {
System.out.println("between " + i + " and " + j + " = "
+ new CosineSimilarity().getCosine
(
tfidfDocsVector.get(i),
tfidfDocsVector.get(j)
)
);
}
}
}
}
read your error-message and then check your code:
Error: Main method not found in class TfIdfMain, please define the main method as:
public static void main(String[] args)
what could be the problem? the main-method was not found. In your code it is commented out.
And in your TfIdfMain-class:
at least your for-loop has to be in a method / constructor.
Do something like
public class TfIdfMain
public TfIdfMain(){
for(String file : files) {
DocumentParser dp = new DocumentParser();
dp.parseFiles(file);
dp.getCosineMatrix();
}
}
}
your main method is commented out, that is why it isn't found by the compiler.
The for loop isn't inside a method and only in the class body. This is wrong in java.
The error messages from the compiler tell you exactly what to do, you have to provide an special constructor which can handle the exceptions.
I have a program that reads from a csv file full of peoples last names, first names, and birth years, assigns them into a special class array, and then gets sorted according to their last name. I believe that my code is working, so all I have to do to verify this is output the list and see if indeed all of the people were sorted by their last name. However, I am having trouble finding the right syntax to do this.
Here is the code of my Main.java, where I think the issue must be.
package project_1_sorting;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
// open file input stream
BufferedReader reader = new BufferedReader(new FileReader(
"C:\\Users\\Owner\\Desktop\\Data 18k.csv")); // double check where this is trying to read it from
// read file line by line
String line = null;
Scanner scanner = null;
int index = 0;
Human[] pplArray = new Human[18000];
int i = 0;
while ((line = reader.readLine()) != null) {
Human ppl = new Human();
scanner = new Scanner(line);
scanner.useDelimiter(",");
while (scanner.hasNext()) {
String data = scanner.next();
if (index == 0)
ppl.setLastName(data);
else if (index == 1)
ppl.setFirstName(data);
else if (index == 2)
ppl.setBirthYear(data);
else
System.out.println("invalid data::" + data);
index++;
}
ppl.setKey(0); //change this for later things, you can use loop
ppl.setOrder(0); //change this to 1 if you want to invert the list of people
index = 0;
pplArray[i] = ppl;
i++;
System.out.println(pplArray);
}
//close reader
reader.close();
System.out.println(pplArray); // create
Selection_Sort selection = new Selection_Sort();
for (int j = 0; j < 18000; j++)
{
System.out.println(pplArray[j]);
}
}
}
So I was expecting this to output a giant list of all of my people from the csv file(ordered), with all of their info in the same format as they originally were, right. (one person per row, with 3 collumns for their 3 strings). However this is what I got instead:
run:
Test
17
true
0.142857
BUILD SUCCESSFUL (total time: 0 seconds)
The one thing that I have noticed is that one of the last lines that reads
Selection_Sort selection = new Selection_Sort();
It says that "Variable selection is not used."
I think that it is saying that I am not properly using my selection sort. I am creating an object of that class, but not using it.
here is my Selection_Sort.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package project_1_sorting;
public class Selection_Sort
{
public static void sort(Comparable[] a)
{ // Sort a[] into increasing order.
int N = a.length; // array length
for (int i = 0; i < N; i++)
{ // Exchange a[i] with smallest entry in a[i+1...N).
int min = i; // index of minimal entr.
for (int j = i+1; j < N; j++)
if (less(a[j], a[min])) min = j;
exch(a, i, min);
}
}
// See page 245 for less(), exch(), isSorted(), and main()
private static boolean less(Comparable v, Comparable w)
{
return v.compareTo(w) < 0;
}
private static void exch(Comparable[] a, int i, int j)
{
Comparable t = a[i]; a[i] = a[j]; a[j] = t;
}
}
I think that, in order to actually sort my data from the csv file in the right order. I have to do something to the affect of
Selection_Sort selection = new Selection_Sort();
selection.sort(pplArray[]);
However, the second line of code creates an error message:
'.class' expected
cannot find symbol
symbol: class pplArray
location : class main
If I remove the brackets on pplArray:
Selection_Sort selection = new Selection_Sort();
selection.sort(pplArray);
The error message changes to
incompatible types: Human[] cannot be converted to Comparable
This makes me wonder if there is something at fault with my Human class, so here is my Human.java:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package project_1_sorting;
class Human{
String firstName;
String lastName;
String birthYear;
int Key;
int Order;
public Human() // A constructor
{
}
public int compareTo(Human person)
{
if (Order == 0)
{
if (Key == 0)
return lastName.compareTo(person.lastName );
else if (Key == 1)
return firstName.compareTo(person.firstName );
else
return birthYear.compareTo(person.birthYear );
}
else
{
if (Key == 0)
return (lastName.compareTo(person.lastName ) ) * -1;
else if (Key == 1)
return ( firstName.compareTo(person.firstName ) ) * -1;
else
return ( birthYear.compareTo(person.birthYear ) ) * -1;
}
}
public void printHuman ()
{
StdOut.print(lastName + " " + firstName + " " + birthYear);
}
public void setKey (int k)
{
Key = k;
}
public void setOrder (int o)
{
Order = o;
}
public void setFirstName(String fName)
{
firstName = fName;
}
public void setLastName(String lName)
{
lastName = lName;
}
public void setBirthYear(String bYear)
{
birthYear = bYear;
}
}
In case it is relevant, int key is supposed to allow me to pick by what variable I want to sort (first name, last name , or birth year), and int order is supposed to allow me to reverse the order in which people are ordered (least to greatest, greatest to least).
If I can't use comparable, does that mean I have to use a comparator? If so, could someone show me how to do this?
If anyone knows what this is all about, please let me know. If there is nothing else wrong with this Main.java, I can post my other .java files.
One thing I did notice was that, even when I commented out my selection sort function call, and all of the printline commands in this .java file, the same output was displayed on my screen.
Please let me know what you think, and thank you for your time.
You're on the right track. However, how will the compiler know that your Human class is Comparable? You must not only provide the method compareTo(), but also put implements Comparable at the beginning.
Your Human class seems ok - but though you've implemented the compareTo() function, you haven't stated your class implements the Comparable interface (which is the compilation error you're getting):
class Human implements Comparable<Human> {
You'll probably then need to annotate the compareTo() function:
#Override
public int compareTo(Human person)
I need help with this code
Problem
Write a Java class having a String array, with global visibility.
Add a method that adds a given sting to the string array.
Add a method that searches for a given string in the string array.
Add a method that searches for a given character in the string array. The method should count and returns the occurrence of the given character.
Write an appropriate main method to test these class methods.
and this is the code. First, I created a class for method I create scound class for TestString array
my question is i have error in scound class ,and i try to fix it but it dose not work
this the first class:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ooplab3;
public class StringArray {
String[] sTA = null;
int index = 0; //last added sring position in the string array
public StringArray() {
}
public String[] getsTA() {
return sTA;
}
public String getsTAindex(int i) {
return sTA[i];
}
public int getcounter() {
return index;
}
public void setCounter(int counter) {
this.index = counter;
}
public void addStrinToArray(String st) {
if (this.index < sTA.length) {
sTA[this.index] = st;
this.index++;
}
}
public int searchStringInArray(String sT) {
int n = 0;
for (int i = 0; i < this.index; i++) {
for (int j = 0; j < 10; j++) {
int indexOf = sTA[i].indexOf(sT);
n += searchStringInArray(sTA[i]);
return n;
}
}
return n;
}
public int searchcharInArray(String sT) {
int n = 0;
int Startindex = 0;
do {
n += sT.indexOf(Startindex);
} while (n > Startindex);
return n;
}
public boolean containsChar(String s, char search) {
if (s.length() == 0) {
return false;
} else {
return s.charAt(0) == search || containsChar(s.substring(1), search);
}
}
public void containsChar(Object object, String search) {
}
}
Sound class :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ooplab3;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class testStringarray {
public static void main(String[] args) throws FileNotFoundException {
String[] testArray = new String[30];
Scanner infile = new Scanner(new FileReader("input_txt"));
// System.out.println("contents of testArray");
int i = 0;
while (infile.hasNext()) {
String j = infile.next();
addString(j, i);
System.out.println(testArray[i] + "\n");
i++;
}
}
}
the input file contain: hello this is my java program
As near as I can tell, you have a class named StringArray, and a second class which is intended to test the capabilities of StringArray. But that second class doesn't actually use StringArray at all; instead, it creates its own array, and calls a method addString() which has a similar, but not identical, name as a method in StringArray.
One significant problem with StringArray is that it never creates an actual array -- its array member variable remains null. You need a "new" expression to create the actual array. Then your test class should be doing something like
StringArray sa = new StringArray();
sa.addStringToArray("Hello, world");
String[] array = sa.getsTA();
for (String s: array)
System.out.println(s);
A number of problems exist.
Here's one of them:
In your StringArray.addStrinToArray() method, you attempt to assign a string to an element of a null array:
String[] sTA = null;
sTA[index] = st; //this will throw NullPointerException
You need to initialise the array:
String[] sTA = new String[initialSize];
Where initialSize is an integer containing the initial size of the array.
I'm working on a project for school and am stumped at where I am at the moment. When I run my project, the VM seems to be stuck in a loop and will not load (A console should pop up allowing me to input characters for the CombinationLock class setDigit() method). I believe it has something to do with my for loop in my Interface.java class. If anyone could take a look and lead me in the right direction, that'd be much appreciated. Thanks a bunch!
Interface.java
import java.util.*;
public class Interface
{
public static void main() {
Scanner in = new Scanner(System.in);
CombinationLock combo = new CombinationLock();
for(int i = 0; i < 3; i++) {
String ltr = in.nextLine();
combo.setDigit(ltr.charAt(0), i);
System.out.println("Digit " + i + " has been set to " + ltr);
}
}
}
CombinationLock.java
public class CombinationLock
{
String[] combo = new String[3];
public CombinationLock() { }
public boolean setDigit(char letter, int index) {
if (Character.isDigit(letter)) {
return false;
}
combo[index] = String.valueOf(letter);
return true;
}
public boolean unlock(String combo) {
if (combo.length() > 3) {
return false; //Longer then it can be, not valid
}
char[] comboArray = combo.toCharArray();
for (char c : comboArray) {
if (Character.isDigit(c)) {
return false; //Contains numbers, not valid
}
}
boolean valid = true;
for (int i = 0; i < 3; i++) {
if (combo.charAt(i) != comboArray[i] && valid == true) {
valid = false;
break;
}
}
return valid;
}
}
You have initialized combo array in CombinationLock class with length 0 as String[] combo = {};. This is cause ArrayIndexOutOfBoundsException when you are calling combo.setDigit(ltr.charAt(0), i);. Please correct the initialization. I beleive you want to capture 3 inputs, in that case, please initialize combo in CombinationLock with length 3 as below:
String[] combo = new String[3];
Your problem is (the signature of the main method is wrong)
public static void main() {
it should be
public static void main(String[] args) {
I've found where my error was, using the BlueJ IDE one must output something to the console before it shows up and allows you to input data, therefore it never popped up as I never used System.out.println or System.out.print. After doing so, the console popped up and allowed me to input my data. Thanks you for all your suggestions and help!