NumberFormatException Spring - java

Below code...
#GetMapping("/brian/{number}")
public String getBrianMessage(#PathVariable int number) throws NumberFormatException {
try {
logList.add(number);
String stringList = logList.toString();
return "List is " + stringList;
} catch (NumberFormatException e){
int newCount= 999;
logList.add(newCount);
String stringList = logList.toString();
return "List is " + stringList;
}
}
When going to the url i would like the integer stored in a list. This works fine when you use a valid integer value. I want the ability to default the value to 999 when a string is supplied. So, if i go to /brian/string it should add 999 to the list and return it. This is not working and I'm getting the same error as before I added the exception handling

Related

How to return properly in if else and avoid "void" for errors about return

I am having a hard time how to return into specific variable or how to return without getting any error base on my program.
class Facebook {
public static void main(String[]args){
String user = JOptionPane.showInputDialog(null,"Enter Username: ");
String pass = JOptionPane.showInputDialog(null,"Enter Password: ");
if(user.equals("jas")&&(pass.equals("bsit"))){
JOptionPane.showMessageDialog(null,"Welcome "+ user);
Selection Class = new Selection();
Selection.Selection1();
}
else if (!user.equals("jas")||(!pass.equals("bsit"))) {
JOptionPane.showMessageDialog(null,
"Invalid Username or Password",
"Wrong Authentication",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
class Selection{
public Selection1(){
try{
String select = JOptionPane.showInputDialog("[1]Home\n[2]Profile\n[3]Logout");
int numbers = Integer.parseInt(select);
if (numbers == 1){
JOptionPane.showMessageDialog(null,"Mang Tani: Lumakas ang hanging amihan halos nilipad ang mga bubong ng mga bahay\n\nJessica Soho: Isang sikat na pagkain sa davao inubos ng kabataan \n\n Boying Remulla: Walang pasok dahil sa malakas na ulan\n#WalangPasok.");
return select;
}
else if (numbers == 2){
JOptionPane.showMessageDialog(null,"Name: Ralph Jasper \n\n Age: 17 \n\n Address: Tierra Nevada, General Trias, Cavite");
}
else if (numbers == 3){
}
}
catch (NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please input only numbers","Invalid Input",JOptionPane.ERROR_MESSAGE);
}
}
}
1) you want a method with a return value of a string
Replace
public Selection1(){
with
public String select()
2) all "paths" of a non-void method must result in a return statement. This does not mean a return statement needs to be inside any if else's, but you do need to return something within the method.
Suggestion: declare a String result = ""; outside of the try catch, return it after, outside of the catch, and assign it to your JOptionPane value in between like result = JOptionPane...
3) I'm assuming you actually want that value that's returned?
Selection selector = new Selection();
String selected = selector.select();
// TODO use that value
Notice: Java naming conventions -- methods are lowerCase, classes are UpperCase.

Adding a class to an ArrayList, but got NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So, I was trying to add a class to an ArrayList, but when I do it gives me a Null Pointer Exception. I'm sure I am just overlooking a variable that I thought was initialized, but I can't figure it out.
This is the class:
enum WebType { GoogleResult, Webpage };
public class Webpage {
WebType type;
String pageName;
String content;
String url;
String MLA = "";
public Webpage(String pageName, String content, String url, WebType type){
this.type = type;
this.pageName = pageName;
this.content = content;
this.url = url;
this.MLA = ""; // Temp
}
// TODO: Make Citation Maker
}
This is where I add the class to the ArrayList:
public void Start(){
for(Integer i = 0; i < tags.size(); i++){
if(tags.get(i) == null)
return;
Webpage page = Google(tags.get(i));
parseList.add(page); // The Error is on this line!
log.append("Added " + page.url + " to parse list");
}
for(Integer i = 0; i < parseList.size(); i++){
ParsePageCode(parseList.get(i));
}
}
Here is the Google function, it googles whatever you tell it to and returns the page information:
public Webpage Google(String search){
String url = "https://www.google.com/search?q=" + search;
String content = "";
try {
URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.append("\n Unsupported Encoding Contacting Google");
}
try {
content = GetPageCode(url);
} catch (IOException e) {
log.append("\n Unable To Reach Google");
log.append(e.getMessage());
}
Webpage w = new Webpage("Google Result For " + search, content, url, WebType.GoogleResult);
// System.out.println(search + url + WebType.GoogleResult);
return w;
}
Any Ideas?
On the line that is throwing the exception, parseList is the only variable being dereferenced. The only other variable on that line is page, and it doesn't matter if page is null because you can add null elements to a List. So, it must be parseList causing the NPE.
Actually there is no problem adding null to a collection of Objects. Retrieving the object and invoking its members later may cause NPE.
You have told is that the problem is on the line where you do add the object. The only way there to cause NPE is calling add() upon null. So that's your collection parseList that is not initialized yet. Maybe it's a field in the class and was never initialized to an actual object of type ArrayList, but it's only declared.

Java Null pointer exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
We are trying to display information in a textarea from a database table.
public void displayEmployees()
{
String sqlDisplayQuery ="";
sqlDisplayQuery+= "Select * from JAVAUSER.Employee";
System.out.println(sqlDisplayQuery);
Driver.sendDBCommand(sqlDisplayQuery);
try
{
while (dbResults.next())
{
int employeeID= dbResults.getInt(1);
String employeeFName = dbResults.getString(2);
String employeeLName = dbResults.getString(3);
System.out.println("Employee " +employeeID + employeeFName + employeeLName);
txtaOutput.appendText("Employee" +employeeID + employeeFName + employeeLName);
}
}
catch (SQLException e)
{
System.out.println(e.toString());
}
}
public static boolean isNumeric(String string)
{
try
{
double num = Double.parseDouble(string);
}
catch(NumberFormatException e)
{
return false;
}
return true;
}
public static void sendDBCommand(String sqlQuery)
{
String URL = "jdbc:oracle:thin:#localhost:1521:XE";
String userID = "javauser";
String userPASS = "javapass";
OracleDataSource ds;
try
{
ds = new OracleDataSource();
ds.setURL(URL);
dbConn= ds.getConnection(userID, userPASS);
commStmt = dbConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
dbResults= commStmt.executeQuery(sqlQuery);
}
catch (SQLException e)
{
System.out.println(e.toString());
}
}
We are getting an null pointer exception at the while loop within the try statement. The SQL does not have any errors. Any help would be appreciated
Looks like the dbResults field is static on the Driver class - this could cause serious problems with multi-threading, and does not utilize proper object-orientation - but that's beyond the scope of the question i guess.
Looking at the loop:
int employeeID= dbResults.getInt(1);
This is fine-ish, even though getInt() won't throw an NPE, you might want to check if the value was SQL null with ResultSet.wasNull().
String employeeFName = dbResults.getString(2);
String employeeLName = dbResults.getString(3);
These can be null, but won't throw NPE either.
System.out.println("Employee " +employeeID + employeeFName + employeeLName);
txtaOutput.appendText("Employee" +employeeID + employeeFName + employeeLName);
Here, in both lines, you concat strings that could be null, so these two are potential sources of NullPointerExceptions. I am just wondering if you got line numbers in your stacktrace that could help identifying the exact location...?
If you want to check what can/cannot return null from an SQL ResultSet, check this.

Convert String to Int with Integer.parseInt don't works

I'm working with JavaEE i need to convert this: request.getParameter("id") to int. The value of request.getParameter("id") is "9" (String).
When I'm trying to convert to int I have
java.lang.NumberFormatException
I've tried java.lang.Integer.parseInt(request.getParameter("id")) and request.getParameter("id",10) but it donsen't works...
Any solutions? Thank you.
A complete full proof code would be
String idString = request.getParameter("id");
if(idString != null) {
try {
System.out.println(idString.trim()); // print to verify
int idInt = Integer.parseInt(idString.trim());
}
catch(NumberFormatException nbe) {
nbe.printStackTrace();
}
}
First you need to check whether String returned by getParameter() is null or not then check whether it is empty ("") String or not then use Integer.parseInt().
String id = request.getParameter("id");
if(null != id && !("".equals(id))) {
try {
int number = Integer.parseInt(id.trim());
}
catch(NumberFormatException e) {
e.printStackTrace();
}
}

Better handling of number format exception in android

I've got the following code snippet that I'm thinking of refactoring to a more abstract application exception handler but I want to make sure I've got it as tidy as possible first
Any suggestions on how to improve this code or make it more resuable
int id = -1;
final StringBuilder errorMessage = new StringBuilder("Bad Input Value: ");
try {
id = Integer.parseInt(edtId.getText().toString());
} catch (final NumberFormatException e) {
errorMessage.append("Failed to parse id " + e.getMessage());
}
if (id < 0) {
errorToast(errorMessage.toString());
} else {
//go ahead an retreive values from database knowing the id has been parsed
//correctly to a positive int.
}
Why pre-assign id to a magic number?
try {
int id=Integer.parseInt(edtId.getText().toString());
//go on as normal
} catch (NumberFormatException e) {
//handle error
}

Categories