I cannot figure out the startsWith(str) in the while loop below have the error
The method startsWith(String) is undefined for the type InfoProcessor.
I want to get the String that follows the line that starts with the given String (str).
It is great pleasure to have your help.
import java.util.*;
public class InfoProcessor {
private ArrayList<String> lines = new ArrayList<String>();
public InfoProcessor(ArrayList<String> lines) {
this.lines = lines;
}
String getNextStringStartsWith(String str) {
for (int i = 0 ; i < lines.size(); i++){
Scanner scanner = new Scanner(lines.get(i));
while (startsWith(str)){
String hobby = scanner.nextLine();
String[] tokens = hobby.split("\\s+");
return tokens[1];
}
}
return null;
}
You are trying to invoke a String method but you are not invoking it on a String. Therefore, the compiler interprets your attempt as invoking the method on this class. This class does not implement that method so the method is undefined. In your case, you want to invoke that method on an individual line to see if it contains the prefix.
public String findWordAfterPrefix(String prefix) {
for (String line : lines) { // iterate over the lines
if (line.startsWith(prefix)) { // does the line start with the prefix?
/// find the next word and return it - that is a separate issue! ;)
}
}
return null; // return null if we never found the prefix
}
p.s. You may find some other String method useful as you pull out the next word (e.g. trim(), substring(int).
The error means exactly what it says: there is no startsWith() method in your InfoProcessor class.
You may have intended str.startsWith(...) instead of startsWith(str).
Related
I am trying to store the contents from a file into an array String retval[] , copy that array to String[] fed() and pass the array into main. So far, the array stores and copies but the array method returns null in main String []feed; feed=uio.fed();.
UserIO.java
package fileio;
import classes.*;
import java.util.*;
import java.lang.*;
import java.io.*;
public class UserIO
{
public String search (String line0)
{
String line;
try
{
FileInputStream ufin = new FileInputStream("E:\\3rd sem\\OOP\\Projects\\New folder (2)\\BOOK LIBRARY\\fileio\\user.txt");
Scanner sc = new Scanner(ufin);
while (sc.hasNextLine())
{
line=sc.nextLine();
if(line.contains(line0))
{
String retval[]= line.split(" ");
feed= new String[retval.length];
for (String s: retval)
{
System.out.println("\t\t\tFrom retval:"+s);
}
for (int n=0;n<retval.length;n++)
{
feed[n]=retval[n];
System.out.println("\tFrom feed:"+feed[n]);
}
}
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
return line0;
}
public static String [] feed;
public static String[] fed()
{
String [] fd;
fd= new String[feed.length];
for (int n=0;n<feed.length;n++)
{
fd[n]=feed[n];
System.out.println("From fd:"+fd[n]);
}
return fd;
}
}
Down below is the main method
Execute.java
import java.lang.*;
import java.util.*;
import classes.*;
import fileio.*;
public class Execute
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String adminusername = "a";
String adminpassword = "p";
String readerusername = "r";
String readerpassword = "p";
String nreaderusername;
String nreaderpassword;
Library b = new Library();
UserFileReadWriteDemo ufrwd = new UserFileReadWriteDemo();
UserIO uio = new UserIO();
System.out.println("enter id ");
String id = sc.next();
uio.search(id);
try
{
String []feed;
feed=uio.fed();
//uio.fed()=feed.clone;
for(int s=0;s<feed.length;s+=5)
{
String nid00= null;
feed[0+s]= nid00;
String name00=null;
feed[1+s]= name00;
String age00= null;
feed[2+s]= age00;
String uname00= null;
feed[3+s]= uname00;
String upassword00= null;
feed[4+s]= upassword00;
Reader c00 = new Reader(nid00, name00, age00,uname00,upassword00);
b.insertReader(c00);
System.out.println(" In main"+feed[s]);
}
}
catch (NullPointerException n)
{
n.printStackTrace();
}
}
Your code is a little bit difficult to read and also has a lot of unnecessary repetitions, for example method fed has no role, why not call search and make search return an array with the found elements? You are making search return the line you are searching for which you already know when you gave search that argument in the first place, it is just returning a useless value.
Also it is difficult to understand what search actually does, from what i see it finds the last occurrence of line0 in the file, because it continues to iterate over lines and every time it finds line0 it will create new feed array in UserIO and eliminate all the previous array it found, and will return when all file has been read. If this is your intention then this is not the right way to do it as it is inefficient, because you keep creating arrays that will be discarded. If your intention is the last occurrence of line0 then you can just assign a found line to a String variable and when the iteration finishes just split and return that array as it will be the last occurrence of line0 in the file.
As i see it the only way that fed will return null is if there is no line with line0 in the file because search initializes the array if it finds line0 at least once in the file, this way feed will be an uninitialized array which will be a null pointer.
These lines has no meaning:
String nid00= null;
feed[0+s]= nid00;
String name00=null;
feed[1+s]= name00;
String age00= null;
feed[2+s]= age00;
String uname00= null;
feed[3+s]= uname00;
String upassword00= null;
feed[4+s]= upassword00;
I think you meant nid00 = feed[0+s] and so on, because the way you wrote the assignment to nid00 and the other variables will be always null which will be useless.
Also when you copy arrays try to use Arrays.copyOf methods or System.arraycopy they save you writing several lines and also they are more efficient, read about them in the documentation.
And the last thing, it is not useful to catch nullpointer exception if you wrote your code, in general you must know what your methods do and if there is a nullpointer exception in something you wrote then there is something wrong in your code, if for example a method you wrote returns null then you must know about the possibility of a null return and handle that possible return, this way it will be easier for you to read your code and use it and also for others who use your code.
The nullpointer you are getting is because you trying to get the length of an uninitialized feed inside fed method, you must be very careful.
my professor gave me an exercise to find how many time the characters of string called "filter" are to be found in a second string called "query".
before I begin I am java noob and English isnt my native language.
example:
String filter="kjasd";
String query="kjg4t";
Output:2
getting how many times a char has been found in another string isnt my problem but the problem that the professor gave us some rules to stick with:
class filter. The class must be the following public
Provide interfaces:
public Filter (String letters) (→ Constructor of class)
The string representing the filter should be stored in the letters string
public boolean contains (char character)
Returns true if the passed character is contained in the query string, otherwise false
-public String toString ()
Returns an appropriate string representation of the class (just to be clear I have no clue about what does he means with this one!)
To actually determine the occurrences of the filter in the query, another class QueryResolver is to be created.
The class should be able to be used as follows:
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
the filter and the query are given by the user.
(i couldnt understand this one! )The methods "where" and "matches" configure the "QueryResolver" to include a subsequent call of "count" the calculation based on the previously passed variables
"query" and "filter" performs.
The count method should use the filter's previously-created method.
The modifier static is not allowed to use!
I dunno if he means that we cant use static {} or we cant use public (static) boolean contains (char character){}
we are not allowed to use void
so the problems that encountered me
- I can not pass a char to the method contains as long as it is not static.
error "Non-static variable can not be referenced from a static context"
i did not understand what i should do with the method toStirng!
what I've done so far:
Approach Nr 1:
so I just wrote everything in the main method to check whether the principle of my code works or not and then I wanted to create that whole with constructor and other methods but unfortunately I did not succeed.
Approach Nr 2:
then I tried to write the code in small mthoden as in the exercise but I did not succeed !.
in both aprroaches i violated the exercise rules but i cant seem to be able to do it alone thats why i posted the question here.
FIRST APPROACH:
public class filter{
public filter(String letters) {
//constructor of the class
String filter;
int count;
}
public boolean contains (char character){
/*Subprogram without static!
*the problem that I can't pass any char to this method if it wasn't static
*and I will get the following error"Non-static variable cannot be referenced from a static context"
*I understand why I'm getting the error but I don't know how to get around it X( */
return true ;
}
public String toString (){
/*he told us to include it in the program but honestly, I don't know what shall I write in it -_-
*I make it to null because you have to return something and I don't know what to do yet
*so, for now, I let it null. */
return null;
}
public static void main(String[] args) {
Scanner in =new Scanner (System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
int count=0;
// I initialized it temporarily because I wanted to print it!
//later I need to use it with the boolean contains as a public method
boolean contains=false;
//to convert each the query and the filter strings to chars
char [] tempArray=query.toCharArray();
char [] tempArray1=filter.toCharArray();
//to iterate for each char in the query string!
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
//to iterate for each char in the filter string!
for (int j = 0; j < tempArray1.length; j++) {
// if the value in the filter string matches the value in the temp array then increment the counter by one!
if(tempArray1[j] == cc){
count++;
contains=true;
}
}
}
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
System.out.println("the boolean value : "+ contains);
in.close();
}
}
SECOND APPROACH
- But here too I violated the rules of the task quite brutally :(
- First, I used void and did not use the tostring method.
- Second, I did not use a constructor.
- I did not add comments because that's just the same principal as my first attempt.
public class filter2 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("enter the filter string:");
String filterStr=in.next();
System.out.println("enter the query string:");
String querystr =in.next();
Filter(filterStr, querystr);
in.close();
}
public static void Filter(String filterstr , String querystr){
char [] tempArray1 = filterstr.toCharArray();
contains(tempArray1, querystr);
}
public static void contains(char[]tempArray1, String querystr){
boolean isThere= false ;
int counter=0;
char [] tempArray = querystr.toCharArray();
for (int i = 0; i < tempArray.length; i++) {
char cc = tempArray[i];
for (int j = 0; j < tempArray1.length; j++) {
if(tempArray1[j] == cc){
counter++;
isThere=true;
}
}
}
System.out.println("the letters of the filter string has been found in the query string exactly "+counter+" times!\nthus the boolean value is "+isThere);
}
/*
* sadly enough i still have no clue what is meant with this one nor whatshall i do
* public String toString (){
* return null;
* }
*
*/
}
Few hints and advice would be very useful to me but please demonstrate your suggestions in code because sometimes it can be difficult for me to understand what you mean by the given advice. ;)
Thank you in advance.
(sorry for the gramatical and the type mistakes; english is not my native language)
As already mentioned, it is important to learn to solve those problems yourself. The homework is not for punishment, but to teach you how to learn new stuff on your own, which is an important trait of a computer scientist.
Nonetheless, because it seems like you really made some effort to solve it yourself already, here is my solution, followed by some explanation.
General concepts
The first thing that I feel like you didn't understand is the concept of classes and objects. A class is like a 'blueprint' of an object, and the object is once you instanciated it.
Compared with something like a car, the class would be the description how to build a car, and the object would be a car.
You describe what a class is with public class Car { ... }, and instanciate an object of it with Car myCar = new Car();.
A class can have methods(=functions) and member variables(=data).
I just repeat those concepts because the code that you wrote looks like you didn't fully understand that concept yet. Please ask some other student who understood it to help you with that.
The Filter class
public class Filter{
String letters;
public Filter(String letters) {
this.letters = letters;
}
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
public String toString (){
return "Filter(" + letters + ")";
}
}
Ok, let's brake that down.
public class Filter{
...
}
I guess you already got that part. This is where you describe your class structure.
String letters;
This is a class member variable. It is unique for every object that you create of that class. Again, for details, ask other students that understood it.
public Filter(String letters) {
this.letters = letters;
}
This is the constructor. When you create your object, this is the function that gets called.
In this case, all it does is to take an argument letters and stores it in the class-variable letters. Because they have the same name, you need to explicitely tell java that the left one is the class variable. You do this by adding this..
public boolean contains (char character){
for(int i = 0; i < letters.length(); i++) {
if(letters.charAt(i) == character)
return true;
}
return false;
}
This takes a character and looks whether it is contained in this.letters or not.
Because there is no name collision here, you can ommit the this..
If I understood right, the missing static here was one of your problems. If you have static, the function is class-bound and not object-bound, meaning you can call it without having an object. Again, it is important that you understand the difference, and if you don't, ask someone. (To be precise, ask the difference between class, object, static and non-static) It would take too long to explain that in detail here.
But in a nutshell, if the function is not static, it needs to be called on an object to work. Look further down in the other class for details how that looks like.
public String toString (){
return "Filter(" + letters + ")";
}
This function is also non-static. It is used whenever the object needs to be converted to a String, like in a System.out.println() call. Again, it is important here that you understand the difference between class and object.
The QueryResolver class
public class QueryResolver {
Filter filter;
String query;
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
}
Again, let's break that down.
public class QueryResolver {
...
}
Our class body.
Note that we don't have a constructor here. It is advisable to have one, but in this case it would be an empty function with no arguments that does nothing, so we can just leave it and the compiler will auto-generate it.
public QueryResolver where(String queryStr) {
this.query = queryStr;
return this;
}
This is an interesting function. It returns a this pointer. Therefore you can use the result of the function to do another call, allowing you to 'chain' multiple function calls together, like resolver.where(query).matches(filter).count().
To understand how that works requires you to understand both the class-object difference and what exactly the this pointer does.
The short version is that the this pointer is the pointer to the object that our function currently lives in.
public QueryResolver matches(String filterStr) {
this.filter = new Filter(filterStr);
return this;
}
This is almost the same as the where function.
The interesting part is the new Filter(...). This creates the previously discussed Filter-object from the class description and puts it in the QueryResolver object's this.filter variable.
public int count() {
int result = 0;
for(int i = 0; i < query.length(); i++) {
if(filter.contains(query.charAt(i))){
result++;
}
}
return result;
}
Iterates through the object's query variable and checks for every letter if it is contained in filter. It keeps count of how many times this happens and returns the count.
This function requires that filter and query are set. Therefore it is important that before someone calls count(), they previously call where(..) and matches(..).
In our case, all of that happens in one line, resolver.where(query).matches(filter).count().
The main function
I wrote two different main functions. You want to test your code as much as possible during development, therefore the first one I wrote was a fixed one, where you don't have to enter something manually, just click run and it works:
public static void main(String[] args) {
String filter="kjasd";
String query="kjg4t";
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println(count);
}
Once you understand the class-object difference, this should be straight forward.
But to repeat:
QueryResolver resolver = new QueryResolver();
This creates your QueryResolver object and stores it in the variable resolver.
int count = resolver.where(query).matches(filter).count();
Then, this line uses the resolver object to first call where, matches, and finally count. Again, this chaining only works because we return this in the where and matches functions.
Now finally the interactive version that you created:
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.println("please enter the query string! ");
String query= in.next();
System.out.println("please enter the filter stirng!");
String filter= in.next();
System.out.println("the query string is : [" + query+ "]");
System.out.println("the filter string is : [" + filter+ "]");
QueryResolver resolver = new QueryResolver();
int count = resolver.where(query).matches(filter).count();
System.out.println("the characters of the String ["+filter+"] has been found in the forworded string ["+query+"] exactly "+count+" times!" );
in.close();
}
So basically I have to print out the worker's name in reverse, and loop through the string character by character. This is what I have for that method under Worker.java:
public String printRev(String fName) {
for (int i = 0; i < fName.length(); i++) {
fName = fName.charAt(i) + fName;
}
return fName;
}
And for UseWorker.java I have:
anil.printRev();
jasmin.printRev();
fred.printRev();
But it's giving me the error message: "The method printRev(String) in the type Worker isn't applicable for the arguments ()."
It's also worth mentioning that I am not allowed to modify UseWorker, only Worker.
How can I go about fixing the problem?
Well, by declaring function like this public String printRev(String fName) you are saying "I want a function with a name printRev which returns instance of String and takes one argument of type String (and has public access, but that is irrelevant for now).
Statement anil.printRev(); means "Take object from variable anil and call function with name printRev and zero arguments on it. The thing is, there is no such method defined, as you defined it as a method with one argument.
What you probably meant to do is printRev("Anil"); which means "Take a method with name printRev and one argument of type String, feed the "Anil" object (string) to its first argument and execute it."
Also, the rev function won't work as you expect it to. You are adding a char to fName all the time and then reading from it as if it was unchanged. You need to make a copy and add characters to the copy. Like this
public String printRev(String fName) {
String reversed = "";
for (int i = 0; i < fName.length(); i++) {
reversed = fName.charAt(i) + reversed;
}
return reversed;
}
(Please note that this method could be optimized further, but is out of scope of this question)
I see several issues:
When you call printRev you give no argument and it expects a String
The string you create will certainly not be the one you expect. You need the concatenate the characters from the end to the beginning without keeping your old value.
The naming is incorrect: you don't print anything. Rename it to revert() or getReverted()
Here is a fix proposal:
public String getReverted(String fName) {
StringBuilder revName = new StringBuilder(fName.length());
for (int i = fName.length(); i >0; i--) {
revName.append(fName.charAt(i - 1));
}
return revName.toString();
}
...and you call it this way :
System.out.println(anil.printRev("string to revert"));
I see that you can't modify UseWorker.java, so you will have to make changes to your other class. Currently your method expects a String to be passed as an argument but clearly the Useworker class does not want you passing any arguments.
For this, you will have to create an fName in the class that you can modify.
For example,if your class is say Person, try:
public class Person{
String fName;
public Person(String fName){
this.fName = fName;
}
public String printRev(){
String result = "";
for (int i = 0; i < fName.length(); i++) {
result = fName.charAt(i) + result;
}
return result;
}
}
I am a newbie in Java. I am trying to create a Class named Database that will read a text file to create an array. There is no main method in this code since I have another java file that acts as a main application, and it has the main method.
Here is my code:
public class Database {
public static String[][] items = new String[20][3];
public static String[][] fillArray(String myFile)
{
TextFileInput in = new TextFileInput(myFile);
for(int i=0; i<20; i++)
{
String line =in.readLine();
StringTokenizer token = new StringTokenizer(line, ",");
for(int j=0; j<3; j++)
{
items[i][j] = token.nextToken();
}
}
in.close();
return items;
}
public static String getName(String code)
{
for(int i=0; i<20; i++)
{
if (code.equals(items[i][0]))
return items[i][1];
}
}
public static String getPrice(String code)
{
for(int i=0; i<20; i++)
{
if(code.equals(items[i][0]))
return items[i][2];
}
}
}
Question 1: Eclipse shows errors by indicating on both methods (getName and getPrice). It says: " This method must return a result of type String". Can anyone please explain and fix this?
Question 2: This Database class includes methods and an array created by reading in the text files. And I have another java file which is the main application file that includes the main method. The main application file is the file where I would like to create object and call the methods in. I understand the concept, but I keep getting errors when I try to create a database object and call the methods on this object. Can anyone please show me an example by using this class?
Answer 1: Your return statement in getName & getPrice method is inside if block which might be executed or not based upon the condition satisfied in if hence compiler will give error.
You need to have return statement before the method returns.
Answer 2: Since all the methods in your database class are static you don't need to create object, you can invoke it directly using classname e.g.Database.getName("code")
Eclipse shows errors by indicating on both methods (getName and
getPrice). It says: " This method must return a result of type
String". Can anyone please explain and fix this?
The method signature states that the return type is String:
public static String getName(String code)
So you must return it. For example:
public static String getName(String code) {
String result = null;
// Perform work and update value in result.
return result;
}
Can anyone please show me an example by using this class?
You need to instantiate the class before invoking any instance method but not for static methods. For example:
String result = Database.getName("code"); //pass some string as input argument and get result.
On a side note why have you declared all methods static? You need to understand why you really need static methods.
Java and Eclipse cannot know if code will ever be equal to items[i][0]. That's why, there might not be a return value for getName.
public static String getName(String code)
{
for(int i=0; i<20; i++)
{
if (code.equals(items[i][0]))
return items[i][1];
}
return "";// or null
}
With This method must return a result of type String the eclipse is saying your method return type is String so you must return a String in any case but your return statement is inside if() what if the condition inside if is never true then there is no return statement so add a default return statement to your method where you are return type String.
public static String getPrice(String code) {
for (int i = 0; i < 20; i++) {
if (code.equals(items[i][0])) return items[i][2];
}
return null;
}
In your method getName and getPrice you have put the if condition, and method only return when your condition in true that is why you have the compilation issue.
To fix that add the else condition in which you should return or add return after completion of if block.
Your method declarations are
public static String getName(){...}
public static String getPrice(){...}
let's analyse this, static keyword means it's a static method.
String means this method returns a object type of String.
However you return a String array object, not a String object.
Also return is inside a if statement and it the if condition not met, it won't return anything, but you must always return a object type of String.
therefore add a return after the if statement, incase if the code never enters your if block
if(YOUR CONDITION) {
//do stuff
//return stuff
}
//if never enters if block returns null
return null;
Your deletions must be
public static String[][] getName(){...}
public static String[][] getPrice(){...}
I'm very new at Java and I have a question about a summer assignment. These are the instructions:
Write a class called SpecialToken that has a static method called thirdToken. This
method should return as a String, the third token of a String that you pass as a parameter.
You may assume that spaces will serve as delimiters.
This is what I have so far but honestly I am stumped at what the parameter should be and how to return the third token! I was thinking I could do something like nextToken() until the third.
public class SpecialToken {
public static String thirdToken() {
}
}
Try something like
public class SpecialToken {
public static String thirdToken(String str) {
String[] splited = str.split(" ");
return splited[2];
}
}
Also see this tutorial or try searching google for "java split string into array by space"
Also note, as Betlista said this does not have any error checking, so if the passed string only has two tokens delimited by one space, you will get an Array out of bounds exception.
Or an other way would be to "Use StringTokenizer to tokenize the string. Import java.util.StringTokenizer. Then create a new instance of a StringTokenizer with the string to tokenize and the delimiter as parameters. If you do not enter the delimiter as a parameter, the delimiter will automatically default to white space. After you have the StringTokenizer, you can use the nextToken() method to get each token. " via Wikihow
With this method, your code should look something like this:
public class SpecialToken {
public static String thirdToken(String str) {
StringTokenizer tok = new StringTokenizer(str); // If you do not enter the delimiter as a parameter, the delimiter will automatically default to white space
int n = tok.countTokens();
if (n < 3) {return "";}
tok.nextToken();
tok.nextToken();
return tok.nextToken();
}
}
However keep in mind Wikihow's warning "now, the use of StringTokenizer is discouraged and the use of the split() method in the String class or the use of the java.util.regex package is encouraged."