String Comparison When Both Values Are Null
Aug 5, 2014In 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 RepliesIn 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 RepliesI got a task from my teacher and the restriction is we are not able to modify this class (and that is the problem).This is the given class:
public class Jobs {
private intcounter= 0;
private final intnoElements= 20;
private final int[]a= { 11, 28, 31, 42, 49, 66, 67, 75, 89, 100, 102, 103, 114, 125, 130, 135, 140, 145, 150, 155 };
private final int[]s= { 20, 9, 7, 6, 12, 15, 4, 7, 30, 22, 11, 45, 20, 6, 6, 5, 5, 5, 5, 5 };
[code]...
I need to compare some of the values of the given arrays. For example: if(a[4]<a[2])... etc.
How can I do these kind of operations to a private array? I have to compare the values in an new classPS: I have to compare the values in a new class
The value is: ${object1.property1} If the value of the property is null, I want "null" to be printed, like this:
The value is: null But I get an empty string, like: The value is:
I know I can use a ternary operator, but isn't there a simpler/shorter solution? A function (like NVL() in SQL)?
The value is: ${empty object1.property1 ? "null" : object1.property1 }
Not only is this long, but the value expression is typed twice, which is a magnet for bugs.
Any compact if statement or any type of test for checking if atleast ONE out of 4 integers is null. So 1 of all, 2 of all, 3 of all, or all of them being null will give a specific result ELSE do something else.
View Replies View RelatedIs there a better way to remove null values from an array than what I have tried? This works just fine, but I just get the feeling that there is a better way to do this, without using the JCF.
private static String[] removeNullValues(String[] list){
int count = 0;
for(int i = 0; i < list.length; i++){
if(list[i] == null)
count++;
[Code] ....
I technically dont need to remove the null values for the project that I'm working on (since I just print it out and I can avoid null values with a simple statement like
if(update[i] != null) SOP(update[i])
),
but I'm just curious.
Everything is written up and looks good and i get no compile errors but every student object other than the default constructor has null and zero values when printed.
import java.text.DecimalFormat;
import java.lang.Math;
public class Student
{
//instantiate variables
[Code] .....
I'm working on a program to create a blackjack game using objects (one for card, deck. and hand). Withing my hand object I am trying to add cards to the hand but it is only adding the last card i try to add and giving null values for the the ones before.
class BlackJackHand {
private BlackJackCard [] hand;
public void addToHand(BlackJackCard c) {
if (hand == null) {
BlackJackCard [] tempHand = new BlackJackCard[1];
tempHand[0] = c;
hand = tempHand;
[Code] ....
What I want this section to do is add cards to the current hand. I was intending for it the hand to be null at first and the if(hand == null) piece to add the card the first time and then the else piece would be used when the hand already has at leas one card. I want the else section to create a temporary array that is one larger than my current hand, copy the cards from the old hand to the new hand, and then add a new card to the last space before rewriting the old hand as what the temporary hand is.
The code I am using to test if the addToHand() is working is
class BlackJackTest
{
public static void main (String[]args) {
BlackJackCard c1= new BlackJackCard(1,0);
BlackJackCard c2= new BlackJackCard(1,4);
BlackJackCard c3= new BlackJackCard(1,5);
BlackJackHand h1 = new BlackJackHand();
[Code] .....
BlackJackCard has the parameters (int suit, int value)
This should print:
ace of clubs
4 of clubs
5 of clubs
but instead prints:
null
null
5 of clubs
I have a file which contains certain positions ([a][b]) that require to be placed in a certain multi-dimensional array. For example I might have an array String[][] that is a size of 6x6 but only have values in positions [2][1] and [3][2]. Because it is important for me to maintain the given array size and also do certain actions with the given positions I cannot modify the size. In addition I need to count the surrounding neighbors each element has (including elements that are null). However because some of my further code cant process with null elements I need to remove all null elements with " " (blank).
I am not sure how this is done or if it's even possible. If it is not possible how can I do something as close as possible to my needs?
My project consists of a web app where a user can select a area from a picture and f.e. if it is a office layout he can input the worker name and any peace of hardware that the area might have. In this case there are two categories: Hardware and Computer. Hardware - it has 5 dropdown lists consisting of printer, scanner and etc. Computer - like Hardware consists of many dropdown lists which add up to components such as processor, motherboard and etc. For me, considering this is my first ever web app project, is a huge step towards web development, I have used various mixes of Java, javascript and primefaces code.
My current problem: When a user selects an area he gets a dialog box where he is prompted to select his desired input, afterwards the user clicks the 'save' button and get's another dialogbox which has a resume of what he has selected so he could check out his input and save it by clicking the 'save' button in the resume box. My problem is that when the user clicks the save button the button calls a method which takes all the input and creates an Area object (Area object consists of various objects such as: Coordinates, Dimensions, Employee, ComputerList and HardwareList) and sends a query to the database, but all the values I get is null.
XHTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui">
[Code] ....
Trying to make me understand when to initialize a string 'null' and when not..??
View Replies View Relatedstatic 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).
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).
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) + "',";}
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?
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.
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.
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] ....
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?
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?
All I am trying to do is to make a section of code execute if two strings are equal. The two strings are userId and "A001062". When I use the debugger in Eclipse, I can see the value of userId as "A001062" but whatever string comparison I try never evaluates to true. I have tried
userId=="A001602"
userId.equals("A001602")
"A001602.equals(userId)
Assigning A001062 to a string called AAA and comparing userId to AAA
My code is as follows. I have also attached a screen shot from the Eclipse Debugger which makes me think the string comparison should succeed. I never see the debugger execute the print line nor do I see the print line on the JBOSS console.
String userId = StringUtils.trim(nextLine[HR_USER_ID]);
String AAA="A001062";
if (userId.intern().equals(AAA.intern())) {System.out.print("MKP1: " + userId+"-"+managerId);}
if (userId.compareTo("DTS0428")==0) {System.out.print("MKP2: " + userId+"-"+managerId);}
Attached image(s)
I have two big text file with approx 16 Lakh (1.6 Million) records in each. Both file contains Strings in each line. I would like to compare two files and find the descripencies and print them into separate file.
View Replies View RelatedI would like to create a component to detect the file being modify before process.is it the right way to detect the file modification based on file size value?
Below are the flow:
1. Get the file size of a file
2. Used file size value encrypt it with MD5 algorithm, and say it generated us encrypted value "0123sdf"
3. to avoid user modify the file content, before file process, we take the file and do the encryption with md5 again, if it return value "0123sdf", then we are sure it doesn't have modification.
my question:
a. is it the right approach to detect file modification?
b. what the library advise to use or using java.security.DigestInputStream will do?
I want the code for comparing the price of product on different online shopping site ...
View Replies View RelatedI'm not so new to java i know the basics. I want to make a mastermind game. Just for training purpose.
Now i am at the comparison phase where it is comparing your chosen "colors" with the actual "color code"
This is my code for that part:
guesChars is a char array of 4 of the actual code
readGuess is a string of 4 of which the players has filled in the console
goodGuess is a char at the right position with the right "color"
avgGues is a char with the right "color" at the wrong position
Java Code:
for(int i = 0; i < guessChars.length; i++){
for(int ii = 0; ii < readGuess.length(); ii++){
if(readGuess.charAt(ii) == guessChars[i]){
if(ii == i){
[Code] .....
The problem is when the code is for example
ACDD
and the player guess is
ADDD
Result is
2 right spot right color
1 right color wrong spot
It have to be
2 right spot right color
0 right color wrong spot
So - working on some new document composition tasks today, and realised my life would be made easier if I could have an application to allow me to compare two documents and highlight the differences...I know I could use a number of other tools, even word compare but it would be more fun if I could do it myself. Plus - there's the thrill of using non-approved technology at my workplace...I'm a maverick.
Just looking for the high level steps I should go through in creating an application which could be delivered to users in my team as an executable file (I have admin rights to my works laptop, but my direct reports do not have this on theirs) so would need to be able to run the app without installing if possible...
All I am trying to do is to make a section of code execute if two strings are equal. The two strings are userId and "A001062". When I use the debugger in Eclipse, I can see the value of userId as "A001062" but whatever string comparison I try never evaluates to true. I have tried
userId=="A001602"
userId.equals("A001602")
"A001602.equals(userId)
Assigning A001062 to a string called AAA and comparing userId to AAA
My code is as follows. I have also attached a screen shot from the Eclipse Debugger which makes me think the string comparison should succeed. I never see the debugger execute the print line nor do I see the print line on the JBOSS console.
String userId = StringUtils.trim(nextLine[HR_USER_ID]);
String AAA="A001062";
if (userId.intern().equals(AAA.intern())) {System.out.print("MKP1: " + userId+"-"+managerId);}
if (userId.compareTo("DTS0428")==0) {System.out.print("MKP2: " + userId+"-"+managerId);}