String Testing For Null / Empty?

Oct 13, 2014

I've been beavering away with Java for a few months. But as with all languages the String implementation looks designed to trip up even experienced programmers.

My current development gets data from various sources outside my control. When I get a string I want to test if it is empty/null/or whatever. Simple enough one thinks.

But if you search the internet you see everone seems to have a slightly different approach. So what is the best way of determining that a string is not useful to you?

I've had success with this

if(string == null || string.length() == 0)

But I've seen people using methods - not necessarily of String (e.g equals, empty) and regular expressions.

What is the best approach to this considering coding efficiency and/or processing efficiency (accepting you'd have to be processing a lot of strings for the latter to be an issue).

View Replies


ADVERTISEMENT

Testing Double Null

May 2, 2014

how to execute a particular class. I've created a Kinematics class that will execute and calculate all the functions pertaining to kinematic equations. In the main class, I will have the user provide the data in JTextField. Now I need to test which JTextfields (variables) were left empty. I plan to use a number of if/else statements :

if(distanceI != null && distanceF != null)

The problem with this is that these variables are double and therefore cannot be tested as null. I read a few things about Double but I really don't see how I'm supposed convert each double variable to Double, is that even possible?

public class Kinematics {
double distanceI, distanceF, velocityI, velocityF,
velocityAverage, acceleration;
public Kinematics(){
//v2 = v1 + a*dt
if(distanceI != null && distanceF != null){
 
[code]...

View Replies View Related

Compile Error - Empty String?

Jul 1, 2014

I'm writing basically my first program for school. I've written small ones, following instructions, but this is the most vague. I'm having issues. I can't figure out what the error means. I'm not done with the code, but I think the ArrayList is throwing me off. I'm trying to gather user input and sum the total. Here's the code:

package graduationplanner;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.Double;
 public class GraduationPlanner {
public static void main(String[] args) {

[Code] ....

View Replies View Related

How To Compare Int To Empty String To Input Error

Apr 16, 2015

I am having issues with the program below everything works but I can't figure out a way to add code that if a user just hits enter without inputting anything it says "entering in nothing is not a valid choice" I am stuck on how to compare a int to a string ...

//import statements
import java.util.*; //for scanner class
// class beginning
public class Guess {
public static void main(String[] args ) {
//Declare variables area

[Code] ....

View Replies View Related

Swing/AWT/SWT :: Number Format Exception - Empty String

Mar 8, 2014

This is the exception message I am getting when I run the program and I select a job from the check box and enter an hour amount.

import javax.swing.*;
import java.awt.*;
public class HourPanel extends JPanel {
private double hours;
String textField;

[Code] .....

View Replies View Related

Continuously Get User Input Until Empty String Entered

Jul 26, 2014

I have the code below that just keeps getting the user's name and displaying it until the user enter's an empty string. Well, to simulate that, I just hit the keyboard instead of entering any name but for some reasons I am not seeing in my code, the programme just keeps looping.
 
System.out.println("Enter your name :
");
Scanner st = new Scanner(System.in);
while(st.hasNext()){
System.out.println("Enter your name :
");
String name = st.nextLine();
System.out.println(name);
if(name==" ") break;
}
System.out.println("you are out of the while loop now!!");

View Replies View Related

Servlets :: JSessionID Cookie Value - It Always Returns Empty String

Feb 6, 2014

I'm trying to get the jsessionid cookie value using the following line in my jsp. It always returns empty string. Is this correct behaviour?

response.encodeURL("")

View Replies View Related

How To Compare Int To A Empty String To Input Error Message To User

Apr 16, 2015

I made a guess a number program but I am having issue figuring out a way that when a user enter's in nothing for the program to spit out a message saying "hey entering nothing doesn't work try again" then ask for input. I have done some research and from what I have found is to read the input in as a String rather than int, and use something like Integer.valueOf() to get the integer value but I am completely lost on how to apply that to my program here is my code

//import statements
import java.util.*; //for scanner class
// class beginning
public class Guess {
public static void main(String[] args ) {
//Declare variables area
int guess, secretNumber = (int) (Math.random() * 10 + 1), lowGuess,highGuess;

[Code] ....

View Replies View Related

TicTacToe Game - Adding Crosses And Naughts To Empty String

Jul 5, 2014

I have an empty string and I want to add to it crosses and naughts. I want to simulate a board of TicTacToe game. My goal is print out 5 strings like this : "xox xxx oxo". There are 3 groups of symbols separated with a space. The crosses and naughts are filled randomly.

Random rand = new Random();
char[] characters = new char[] { 'x', 'o' };
int numOfTimes = 0;
while (numOfTimes < 5)
{
String board = "";
String space = " ";
for (int group = 0; group < 3 ; group++)

[Code] .....

Why my code doesn't output the desired result ?

View Replies View Related

Reading Input With Scanner And Checking If User Entered Empty String?

Apr 7, 2015

The project is a program that allows the user to enter students and enter grades for each student. One of the requirements is that if there is already a grade stored for the student that it will display the previous grade. IF the user then enters a new grade the new grade will be stored. IF the user simply presses enter (enters an empty string) nothing is done. I have everything working except for the requirement of doing nothing if the user enters an empty string. If I just press enter at this point I get a NumberFormatException.

The below code is a method "setTestGrades" from the student class. This method iterates through each student object stored in an array list and then checks if there is a previous grade (Requirement# unset grades have to default to -1) before allowing the user to set a new grade.

public void setTestGrades(int testNumber) { //Sets the grade for the specified test number for each student in the arraylist.
testNumber -= 1;
Scanner input = new Scanner(System.in);
for (int i = 0; i < studentList.size(); i++) {
System.out.println("Please enter the grade for Test #" + (testNumber + 1) + " For Student " + studentList.get(i).getStudentName());

[code]....

View Replies View Related

When To Initialize A String Null And When Not

Sep 22, 2014

Trying to make me understand when to initialize a string 'null' and when not..??

View Replies View Related

Can A Null Value Be Concatenated With Existing String

Jan 16, 2014

static public String populateVehicleDetails(Vehicle vehicle){
String returnString = new String()
String existingString = "Chevy Uplander "
String nl = "
"
returnString.concat(existingString+nl).
concat("Color: "+ vehicle.color + nl)
  return returnString
}

In the case that vehicle.color is null what will happens? A null pointer error?

null will be concatenated to the string in vehicle.color place? or will not concatenate anything in the place of vehicle.color I'm asking that because I do not know if I have to check for null in each property of vehicle that I must concatenate (there are a lot of properties in the Vehicle object and some may not been set (they will return null).

View Replies View Related

String Comparison When Both Values Are Null

Aug 5, 2014

In Java is there  a method which  I can use to compare two Strings where in if both the values are null, they should be considered as equal?

View Replies View Related

How To Deal With String Value Of Null In Data File

Feb 24, 2015

I have table data I'm trying to read . However one column is populated with the word "null". I guess java does not like dealing with the word null and throws errors.
 
When I try a block like : if ( rsrow.getString(insCol) = "null") {

I get and error .
 
If I try :
 
cmp = rsrow.getString(insCol);If I try:If I try:
if (cmp = "null") {

I get an error
 
If I try to use a replace function like:
 
System.out.println(cmp.replace("null", "0"));

Just to see if replace works I get and error.
 
What is the BEST way to replace this string value with something like "0"  when I come across it with out jave throwing an error? I want it such that every time I come across the word "null" I can repalce it with "0".
 
Something like:
 
if (rsrow.getString(insCol) = "null") {rowofdata = rowofdata + "'0',";  } else {rowofdata = rowofdata + "'" + rsrow.getString(insCol) + "',";} 

View Replies View Related

Null Detected In String Array Not Saved By Class Constructor

Mar 12, 2014

I've a vertical-bar-delimited file where most elements contain text, some contain whitespace, and some are empty. Examples:

62RG|fe|Pencil Financial Group, LLC||doug@pencil.com|||85637889|Cross, Ben|bcross@godaddy.net|Bernard|Cross|Ben||315 One Tree Hill Terrace|Lafayette|LA

62RG|fe|Pencil Financial Group, LLC||tracy@pencil.com|||13658734|Dustin Cardwright|dcart@motorola.com|Dustin|Cartwright|||| |LA

which I parse and store with

String str_arry = innline.split( "|", 17);
lisst.add( new Contact( str_arry));

and my Contact class has the constructor

public Contact( String[] str_arry) {
for( int ii = 0 ; ii < str_arry.length ; ii++ ) {
if( str_arry[ii].matches("^s+$")) {
str_arry[ii] = null;
System.out.println("hit a null");

[Code]...

I expect the for-loop in the constructor to find any elements containing whitespace characters and set them to null for subsequent assignment.And when the code runs I do see some hit-statements pop up, so the detecting part is working.

But when I then process the list and access a Contact object and test fields for nulls I don't find any ie

if( aContactObj.getfFCity() == null) System.out.println("city is null");

never prints when it should.

What's the trick? Or is my approach wrong and if so what should it be?

View Replies View Related

Java Convert String Of XML To Document Object Is Null All The Time

Apr 14, 2014

I am trying to parse a XML string into `org.w3c.dom.Document` object.

I have looked at solutions provided [here](xml - How to convert String to DOM Document object in java? - Stack Overflow), [here](How to create a XML object from String in Java? - Stack Overflow) and a few other blogs that give a variation of the same solution. But the `Document` object's #Document variable is always null and nothing gets parsed.

Here is the XML

XMLMappingValidator v = new XMLMappingValidator("<?xml version="1.0" encoding="utf-8"?>
" +
"<mapping>
" +
"<container>
" +
"<source-container>c:stem.csv</source-container>

[Code] ....

When I call
**v.getXML().toString()**
I get
`[#document: null]`

Clearly, the parse is failing. But I don't understand why.

View Replies View Related

Java Convert String Of XML To Document Object Is Null All The Time

Apr 15, 2014

I am trying to parse a XML string into `org.w3c.dom.Document` object.

I have looked at solutions provided [here](xml - How to convert String to DOM Document object in java? - Stack Overflow), [here](How to create a XML object from String in Java? - Stack Overflow) and a few other blogs that give a variation of the same solution. But the `Document` object's #Document variable is always null and nothing gets parsed.

Here is the XML

Java Code:

XMLMappingValidator v = new XMLMappingValidator("<?xml version="1.0" encoding="utf-8"?>
" +
"<mapping>
" +
"<container>
" +
"<source-container>c:stem.csv</source-container>

[Code] .....

When I call Java Code: **v.getXML().toString()** mh_sh_highlight_all('java');

I get Java Code: `[#document: null]` mh_sh_highlight_all('java');

Clearly, the parse is failing. But I don't understand why.

View Replies View Related

Removing Item From String Array - Null Pointer Exception Error

Jun 8, 2014

Question 1: I am working on an assignment where I have to remove an item from a String array (see code below). When I try to remove an item after entering it I get the following error "java.lang.NullPointerException." I am not sure how to correct this error.

Question 2: In addition, I am having trouble figuring out how to count the number of occurrences of each string in the array and print the counts. I've been looking at other posts but they are more advanced and I have not yet learned how to use some of the tools they are referring to.

private void removeFlower(String flowerPack[]) {
// TODO: Remove a flower that is specified by the user
Scanner input=new Scanner(System.in);
System.out.println();
System.out.println("Please enter the name of the flower you would like to remove:

[Code] ....

View Replies View Related

Null Pointer Access Variable Can Only Be Null At This Location

Apr 16, 2014

I'm getting an error on line 137 and all it is rsmd = rs.getMetaData();The error happens only after I press a JButton and it is

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerExceptionat softwareDesign.createAccount.actionPerformed(createAccount.java:137)

There is a lot more to it but that has nothing to do with my code it's just the stuff with Eclipse anyway I want to know how do I fix this problem?

View Replies View Related

Why To Get Result Brand Null / Colour Null

Feb 28, 2015

public class Test {
public static void main(String[] args) {
Car c = new Car();
c.setInf("toyota", "red");
System.out.println("name: "+ c.brand + " colour: " + c.colour);

[code]....

Why do I get the result brand null, colour null? I know what null means but what am I missing here?

View Replies View Related

Testing TCP Client And Server

Oct 22, 2014

I am attempting to test a TCP Client and Server for an assignment I am doing in class. The goal here is to "test your client and Server applications by transferring (i) a file having 10,000+ lines (see supplied big-file1.txt having 12000+ lines), (ii) a file having 20,000+ lines (you may create one of your own from big-file1.txt, or obtain a large size file from the Google website at [URL] ...). Then, compute and display the total transfer time of the files at both of the sides separately (your choice in millisecond/second)."

I have created the TCPClient and TCPServer java classes, ran the server first and then the client, and using mathematical formulas to calculate the transfer time. Trouble is, I'm having trouble testing the client and server in the file area and not the area where I had to input a line, let the server print it, and then have the client eliminate the articles from the line. I need testing the file. Here is my code so far:

TCPClient:

package tcpclient;
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
String sentence;

[code] ....

How to fix the code so that the time in seconds does not output as 60 for both files and that the files go through the exchange?

View Replies View Related

Testing Boolean Statement

Mar 30, 2015

I wrote a class for encapsulating coins and I was to do a boolean statement but when I test the statement the results are not showing.Here is the code for my coin class coins.java

package project_3;
/**
*
* @author user a
*/
public class Coins {
private double pennies;
private double nickles ;
private double dimes ;
private double quarters ;
private int dollars ;

[code]...

View Replies View Related

Database Junit Testing

May 28, 2014

I have been designing a music collection application that runs from a database. I now need to develop a junit test to test the application but I am not sure if Junit has anything to work with testing databases. I have been googling on the internet but most of the search results do not really give any good examples that I can easily follow and adapt to my application. I am using only one table and I would like to test INSERT, UPDATE and DELETE actions and I would also like to test a successful connection.

I once found one tutorial which I cannot find any more that had something that retrieves all the data in the database and stores it in a CSV file and the loops through the CSV file to check or update information.

View Replies View Related

Testing Events Within Inner Class Using JUnit?

Apr 17, 2015

How do you test the events within an inner class using JUnit

// File: : events/SomePanel.java
// Purpose: Show use of named inner class listener.
 
import javax.swing.*;
import java.awt.event.*;
class SomePanel extends JPanel {
private JButton myGreetingButton = new JButton("Hello");
private JTextField myGreetingField = new JTextField(20);
 
[Code] .....

Code extract taken from: Java: Inner-class Listeners

Taking the above example, do I need to use myGreetingButton.doClick to trigger this event to test the respective variables/values being used ? Also the Actionlistener inner classes is private so doubt I can access this from JUnit Test class.

View Replies View Related

EJB / EE :: Bean Annotations And Unit Testing?

Mar 6, 2014

I have a bean that represents data been collected from a form on a jsp page. Currently I would like to validate my fields and write some test cases for them. As you can see from my test case example I test a string in the hope that it fails because it contains only one letter. My problem is my unit test is passing. The reason this is from what I can tell is that at runtime it fails when I try to persist my object using my entity manager. During my unit test I just I don’t call my entity manager I just try and set the field.

What I thought would happen was that when I use my bean fields set method the annotations would be checked and fail at that point. Hence why I expected my unit test in this case to fail.

What I would like to know is

1.Are annotations specifically designed to validate when I persist my object and am I using them incorrectly at this point?

2.Is this the best method to use to validate fields, is there a better way, should I write my own code to validate for me when I set my value?

a. Should I throw an exception from the set method of each bean field?

Unit Test:

@Test
public void testName(){
Human h=new Human();
try {
h.setFname("a");
} catch (Exception e) {
// TODO Auto-generated catch block
fail("failed");
e.printStackTrace();

[code]....

View Replies View Related

Syntax Error When Testing Code

Jun 4, 2014

My issue is that when I run the code if I enter anything but 1, 2, or 3 the code breaks. I have spent hours trying to find the error. here is my code

import java.util.Scanner;
public class Tester {
public static void main(String[] args) {
/**
* constructor
* pre: none
* post: inherit values of other classes
*/
Car Car = new Car(); //inherits the properties of the Car class
Truck Truck = new Truck(); //inherits the properties of the Truck class

[code]....

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved