Missing Return Statement - java

i am attempting to take the value of a textfield and make apply it to a method in order to search a textfile for that value. But in my method i am shown a Missing Return Value error and cannot seem to make it work. below is my code:
submitsearch.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
whatToSearch = searchfield.getText();
result = SearchString(whatToSearch);
}
});
}
public String SearchString(String result)
{
String input;
try{
String details, id, line;
int count;
Scanner housenumber = new Scanner(new File("writeto.txt"));
while(housenumber.hasNext())
{
id = housenumber.next();
line = housenumber.nextLine();
{
if(!housenumber.hasNext())
JOptionPane.showMessageDialog(null,"No Properties with this criteria");
}
if(result.equals(id));
{
JOptionPane.showMessageDialog(null,id + line );
}
}
}
catch(IOException e)
{
System.out.print("File failure");
}
}
}
Addendum:
In SearchString i am hoping to search my textfile for the value entered in my textfield display it in a JOptionPane. Although i now have the return statement when i click search i am shown all of the records in JOptionPanes one by one regardless of whether they match my search

You have declared the function with a return type of String, so it must return a String on all code paths. If you don't need it to return anything, use void instead.

Add a return null; after catch block.
The method signature says that it returns a String. That implies no matter what flow your code takes, the method should return a value. But when an exception happens, there is no return. Hence you must specify a return value in the case when an exception happens

Related

Struggling with exceptions, try/catch block and singleton in Java

I am trying to learn to work with error handling/throwing exceptions in Java.
I have a class, UserDatabase, holding a collection of students, and it should also save the collection to a file.
What I'm fairly sure that I haven't done correctly, is the methods for file handling. Method public boolean saveDatabase should not throw exceptions and be handled in a try-catch, and use the encode method from the student class on Student objects, to write every object as a line in the file. This one is compiling, but it looks off to me. In the book it says write the method public boolean saveDatabase(); and as you can see I changed the header for it to make sense to me. This, mainly because I don't know how to write a method with the header ending with ();
Method public boolean loadDatabase should also handle possible IO errors and return false if one occurs. For every line in the field it should create a student object by the constructor public Student(String encodedStudent) from the sudent class. If a line in the file cannot be decoded as a student it should throw a new exception, DatabaseFormatException (this is a seperate class). This one is also listed as public boolean loadDatabase(); in the book. Let's face it, this one is completely off. I have no idea what to do and I have been working with it for hours and hours, reading books, reading online, I am lost.
Here's my code:
/**
* This method should not throw exceptions.
* By using a try/catch block, we anticipate possible failures.
* We recognize that these actions might fail and throw errors.
*/
public boolean saveDatabase() throws IOException {
//This method is using the encode method on student objects and should
//write each object as a line in the file.
String encode = null;
boolean saved;
try {
encode = null;
userdatabase.saveDatabase();
saved = false;
}
catch (IOException e) {
System.out.println("Error");
saved = false;
}
finally {
if(encode.equals(students)) {
//System.out.println("Students" + students)?;
saved = true;
}
}
return saved;
}
/**
* Method loadDatabase should handle possible IO errors, and return false
* if one occurs. Otherwise, it should return true and create a new
Student object
* by using the constructor public Student(String encodedStudent).
* If a line cannot be decoded as a student, the method should throw a
new
* exception "DatabaseFormatException".
*
*/
public boolean loadDatabase() throws IOException,DatabaseFormatException {
//Attempting to use the String encodedStudent constructor from Student class
String encodedStudent = null;
boolean loaded;
try {
//Attempting to create possible IO errors returning false if they occur
enco dedStudent = null;
//UserDatabase.loadDatabase(encodedStudent);
loaded = false;
}
catch(IOException e) {
if (encodedStudent == null) {
System.out.println("Error");
loaded = false;
}
}
//Trying a for each loop to throw a DatabaseFormatException
for(Student student : students) {
//This is supposed to throw a DatabaseFormatException if a
//line in the file cannot be decoded as a student!
if(student.getName.isEmpty() && this.course.isEmpty()) {
throw new DatabaseFormatException(
"No student found");
}
}
Your code should be
public boolean saveDatabase() {
try {
// maybe do some more work...
userdatabase.saveDatabase();
return true;
} catch (IOException e) {
return false;
}
}
Simply return true/false depending on wether an exception occurred or not. Drop the saved since you no longer need it. And drop the encode since you did not need it in the first place and never assigned a value to it.

alter dictionary object in local variable

I'm trying to both remove the method from the method ArrayList and check to see if the ArrayList is empty in one lookup.
This uses two look ups.
private Map<String, List<Method>> events;
public void removeEvent(String eventName, Method method){
try{
events.get(eventName).remove(method);
if(events.get(eventName).size() == 0){
events.remove(eventName);
}
}
catch (Exception e){
}
}
As you can see it looks up the ArrayList of methods to remove a method then looks it up again to see if its length is zero then looks it up again to remove the HashMap entry. Is their a way to combine at least the first two look ups?
You may change it to this way:
List<Method> methods = events.get(eventName);
if (methods == null) {
return;
}
methods.remove(method);
if (methods.isEmpty()) {
events.remove(eventName);
}
Below code might be helpful in your case.
It does not require to lookup second times to check the size of list.
public void removeEvent(String eventName, Method method){
try{
List<Method> methods = events.get(eventName);
methods.remove(method);
if(methods.size() == 0){
events.remove(eventName);
}
}
catch (Exception e){
}
}

"Cannot return a value with void result type" error

The following code comes from this answer
try {
// get all the interfaces
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
//find network interface wlan0
for (NetworkInterface networkInterface : all) {
if (!networkInterface.getName().equalsIgnoreCase("wlan0")) continue;
//get the hardware address (MAC) of the interface
byte[] macBytes = networkInterface.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
//gets the last byte of b
res1.append(Integer.toHexString(b & 0xFF) + ":");
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
ex.printStackTrace();
}
I get error Cannot return a value with void result type on those 2 lines: return ""; and return res1.toString(); I put the code inside public void onStart() How do I fix this, and can you tell me the cause of this problem?
Instead of returning an empty String, just return;
Methods that are void do not return anything but you can use return statement to terminate an operation if some condition is not met!
I hope this helps!
You need to change the line
public void onStart()
To
public String onStart()
This is because you are returning a String, whereas a void function does not return any data.
If the method cannot be changed to a String return type then you could just put the string into a variable that you declare earlier in the program and then use
return;
To exit the method.
Issue is clear, you are returning a value for a function public void onStart(). You are declaring the return type as void and yet you have return statements.
Try different ways to return the value, like put it in request/session or static variable(not recommanded) etc

Evaluating user input using StringTokenizer while utilizing custom checked exceptions

I've been working on a java project for the last couple days, and while things have gone smoothly to this point, I have hit a bit of a snag.
The point of the project is to create a query of sorts, where the user searches for a report using a GUI interface and the app spits out all related data.
Ex: report all where quality > 3
I use a StringTokenizer object to break the String down and evaluate each token. The first token MUST be report, the second token MUST be all, third token MUST be where, the fourth token MUST be either quality, basePrice or numInStock, the fifth token MUST be a relational operator(> < <= >= ==). We were instructed to throw custom checked exceptions if any of the tokens do not match what they should be. So far I have evaluated each token, and throw an Exception if the expected token is not what it should be.
Now once I reach the relational operator, i'm supposed to dump it into a new String called optok. The problem is, I can't seem to get my program to do this and i'm having a hard time figuring out how to do so. I've tried many different things and nothing seems to work.
The final goal is, once all the tokens have been evaluated and checked, to call a method to print the correct query and all data that goes along with said query. If one of the tokens doesn't match, an Exception is thrown.
Here is my code for evaluating each token, to check that it is in the correct format:
public void detectUserInput(String input) throws MissingInputException
{
if (input.equals(""))
{
System.out.println("Null input");
throw new MissingInputException();
}
else
{
System.out.println("Input is not null");
}
}//end detectUserInput
public void countTokens(String input) throws IncorrectFormatException
{
StringTokenizer tokenLength = new StringTokenizer(input, " ,");
if (tokenLength.countTokens() < 6)
{
throw new IncorrectFormatException();
}
}//end countTokens
public void evaluateTokens(String input) throws IllegalStartOfQueryException,
InvalidSelectorException,
InvalidQualifierException,
InvalidLValueException,
InvalidOperatorException
{
StringTokenizer testTokens = new StringTokenizer(input, " ,");
if (!testTokens.nextToken().equalsIgnoreCase("report"))
{
throw new IllegalStartOfQueryException();
}
else if (!testTokens.nextToken().equalsIgnoreCase("all"))
{
throw new InvalidSelectorException();
}
else if (!testTokens.nextToken().equalsIgnoreCase("where"))
{
throw new InvalidQualifierException();
}
else if (!testTokens.nextToken().matches("quality|numInStock|basePrice"))
{
throw new InvalidLValueException();
}
else if (!testTokens.nextToken().matches(">|<|>=|<=|=="))
{
throw new InvalidOperatorException();
}
//here is where I try to take the relational operator
//and dump it into optok, after all the previous input
//has been validated, but it doesnt work :(
while (testTokens.hasMoreTokens())
{
tok = testTokens.nextToken();
if (tok.matches("<|>|>=|<=|=="))
{
optok = tok;
}
}
}//end evaluateTokens
And here is the actionPerformed() of my program that reacts when the user types their query into the TextField and presses the GO! JButton :
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
if (ev.getSource() == goBtn)
{
input = queryFld.getText();
try
{
detectUserInput(input);
countTokens(input);
evaluateTokens(input);
}
catch (MissingInputException mie)
{
errorFld.setText("Enter an expression");
queryFld.setText("");
System.err.println(mie);
mie.printStackTrace();
}
catch (IncorrectFormatException ife)
{
errorFld.setText("Too few terms");
queryFld.setText("");
System.err.println(ife);
ife.printStackTrace();
}
catch (IllegalStartOfQueryException isqe)
{
errorFld.setText("Word REPORT expected");
queryFld.setText("");
System.err.println(isqe);
isqe.printStackTrace();
}
catch (InvalidSelectorException ise)
{
errorFld.setText("Selector must be ALL");
queryFld.setText("");
System.err.println(ise);
ise.printStackTrace();
}
catch (InvalidQualifierException iqe)
{
errorFld.setText("Qualifier error - keyword WHERE missing");
queryFld.setText("");
System.err.println(iqe);
iqe.printStackTrace();
}
catch (InvalidLValueException ilve)
{
errorFld.setText("Invalid query. quality, numInStock, "
+ "or basePrice expected");
queryFld.setText("");
System.err.println(ilve);
ilve.printStackTrace();
}
catch (InvalidOperatorException ioe)
{
errorFld.setText("InvalidOperatorException. < <= > >= == expected");
queryFld.setText("");
System.err.println(ioe);
ioe.printStackTrace();
}
}
}//end actionPerformed
}//end ButtonHandler
I apologize if this seems trivial, but i'm having a really hard time figuring it out for some reason. I appreciate any input or suggestions. If i'm missing any info needed please let me know and i'll add it asap. Also, here are the instructions for this segment:
11) Now, focus on the evaluateAll method. Get the next token. It should be any one of 3 words:
“basePrice” or “quality” or “numInStock” . If it is not, place the message “Invalid query, quality, numInStock or basePrice expected. If is one of those 3 words, you expect a relational operator, so get the next token, but save it in a new String, call it optok. If it is not a correct operator, place the message “invalid query,
You now have two Strings: token which is either “basePrice” or “quality” or “numInStock” and an optok which is one of the 5 relational operators listed above.
Thanks in advance :)
You didn't post a stacktrace, so I'm guessing you're not having an exception, and reading from your code I'm trying to understand what could be happening .. so I might be wrong.
It seems to me that you are using a tokenizer. A tokenizer is like a stream, once you call nextToken() it returns the token, and unless you save it somewhere the next call to nextToken() will make the previous one not accessible.
So, where you make :
else if (!testTokens.nextToken().matches("quality|numInStock|basePrice"))
{
throw new InvalidLValueException();
}
else if (!testTokens.nextToken().matches(">|<|>=|<=|=="))
{
throw new InvalidOperatorException();
}
You are consuming the tokens. As a result, when you get to the while :
while (testTokens.hasMoreTokens()) {
All the tokens are consumed, so it will not iterate here.
You should instead save your tokens in variables, so that you can both check and the use them :
StringTokenizer testTokens = new StringTokenizer(input, " ,");
if (!testTokens.nextToken().equalsIgnoreCase("report"))
{
throw new IllegalStartOfQueryException();
}
else if (!testTokens.nextToken().equalsIgnoreCase("all"))
{
throw new InvalidSelectorException();
}
else if (!testTokens.nextToken().equalsIgnoreCase("where"))
{
throw new InvalidQualifierException();
}
// TODO here i use local variables, since you need to use these outside this method,
// maybe use class fields or whatever else
String subject = testTokens.nextToken();
String opttok = testTokens.nextToken();
if (!subject.matches("quality|numInStock|basePrice"))
{
throw new InvalidLValueException();
}
else if (!opttok.matches(">|<|>=|<=|=="))
{
throw new InvalidOperatorException();
}
// done, now you have opttok and subject

method to validate that amount should be of type integer return type

I am getting an amount in an object through the getter method of pojo
but that amount getter method return type is set as string in pojo
as shown below
//setting need to be done in pojo
private String amount;
public String getAmount() {
return amount;
}
let say below that there is object h and I am retrieving it like
h.getAmount()
now I need to develop a validator that will validate the that amount should
be of type integer and if it is not then it will throw the exception
Please advise how can I develop a seprate method that will check whether
the amount is in integer or not and on the basis of it
will return true or false , as like shown below
// Validate the amount is in integer
private boolean isValidAmount (String Amount) {
boolean valid = false;
//code to check whether the Amount is integer or not, if integer then
//return true else return false
}
I have updated the post as it throws number format exception , please advise
You could just try to parse it, and return true iff the parse succeeds.
try {
Integer.parseInt(amount);
return true;
} catch (NumberFormatException e) {
return false;
}
Edit
I just re-read the question and noticed that it seems the only thing you want to do with this true/false value is to possibly raise an exception if the string couldn't be parsed. In that case, you can get rid of that boolean middleman:
try {
Integer.parseInt(amount);
} catch (NumberFormatException e) {
throw new MyWhateverException(amount);
}
Why don't you try and use Integer.parseInt(someString);
This will throw a NumberFormatException if it fails.
boolean flag = false;
try{
int amount = Integer.parseInt(amount);
flag = true;
} catch(NumberFormatException e) {
flag = flase;
}
return flag;
if the amount is in integer format then it will not through any exception
otherwise it will through NumberFormatException.
Get nmore details of parseInt() here.
public boolean isValidAmount (Object h){
try {
Integer.parseInt(h.amount);
return true;
} catch (NumberFormatException e) {
return false;
}
}
try this out, may work for u

Categories

Resources