Issue with .equals() - java

Following is a small section of the code I am using, along with the syntax of the text file I am using. (I am fairly sure both are grossly overcomplicated, but I am not exactly sure how to simplify them.)
while((line = bufferedReader.readLine()) != null)
{
if(line.split("##")[0].equals(lineNumber))
{
numberOfLines = Integer.parseInt(line.split("##")[1]);
spaceSkip = 1;
worked = 0;
}
if(spaceSkip == 0)
{
if(numberOfLines > 0)
{
System.out.println(line);
numberOfLines--;
}
}
spaceSkip = 0;
}
And the format of the text file is:
1##2##3##0
Text goes below it,
and can span multiple lines.
The 3 and 0 do not come into play here. The intent is for the program to search for the number selected and match it to the first number, 1 in this case. The second number is the number of lines to read. In the code, I have "spaceSkip" so that it does not read the indexing line.
Explanations aside, the issue I am having is that line.split("##")[0].equals(lineNumber) seems to be reading false. I have printed both out to the screen at the same time, and both equal 1, but it is still returning an error message I included. ("worked = 0;" is what keeps the error from triggering.) I am certain it is a stupidly simple mistake I am making here, but I still am unable to figure it out. Thank you in advance.

Whenever a comparison doesn't return what you think it should, check that the types are what you think they are.
String#split returns an array of Strings. For your given input the first element of that array will be "1". If lineNumber is something other than a String, say an int, then equals will still work (the primitive int gets autoboxed to a java.lang.Integer, which is a subclass of java.lang.Object, which is the type the equals method takes as a parameter), but the comparison ("1".equals(1)) will always return false. JavaScript is OK with equating a string and an int ("1" == 1 returns true), but Java is not.
The easiest fix would be to convert the lineNumber to a String, by calling String#valueOf passing in lineNumber. It would be better to convert lineNumber to a String than try to convert the split output to an Integer, because the Integer parsing could fail on bad input, and I'd rather avoid having to manage that possibility.
The cut-n-pasting of the split call is unfortunate mostly because of redundancy, you should do the split once into a local variable like:
String[] parts = line.split("##");
if (parts[0].equals("1")) {
numberOfLines = Integer.parseInt(parts[1]);
...

Without seeing the initialization of the variables it is hard to tell, but it is possible that you are comparing a String to an Integer in this if statement.
You may want to try casting the second argument to a String as follows.
if(line.split("##")[0].equals(String.valueOf(lineNumber)))

Related

How can I fix my code to find a certain character in an array and make changes to that array

while (scan_file.hasNext()) {
String b = scan_file.nextLine();
// checks if string b contains the tag <h>
if (b.contains("<h>")) {
char arrayString[] = b.toCharArray();
for (int i = 0; i < arrayString.length; i++) {
if (arrayString[i] == '<') {
arrayString[i] = arrayString[i + 2];
}
System.out.print(arrayString[i]);
}
}
}
What I was expecting the program to do was(for now) iterate through the while loop and store each line as string 'b'.
I want to check if that string b contains a certain string like <h> for this example. And I want to convert string b into an array if it contains said string like <h> and iterate through that array to check for '<' and move the array up 2 spaces.
For example, string b had <h>hello, I wanted to eventually print hello because the program would have moved up 2 elements.
I feel like I got the loops and general idea on how I want to tackle the problem.. but when I ran the program, nothing printed so I don't know if I did the loops and if statements correctly.
I really don't know how to word my problem well, so bear with me and I'm sorry in advance.
All feedbacks are greatly appreciated (:
System.out.print(arrayString[i]); just print the ith character of arrayString, it's definitely not what you want.
In fact you don't have to convert a String to char[], String has many utils method can help you with your goal.
I won't give you full code , but I can give you some tips.
You can use String.indexof('<') to find the index of '<'.
You can use String.subString(startIndex) to get the subString start with the specified index.
Suppose your code scan_file.hasNext() and scan_file.nextLine() is work well. You can try code below to remove all from current line:
if (b != null && b.contains("<h>")) {
System.out.println(b.replaceAll("<h>", ""));
}

Don't understand how accessing CSV file in processing 3 works. Need an explanation

I have created previously a CSV file with textedit called titanicLinearisedDataSet.csv. My goal is to access this file using processing 3 and check whether element in a column are equal to string value "Nil". I don't receive result whereas the csv file contains "Nil"s.
I have joint an image of the CSV file
(CSV_file_image.jpg).
Thanks for your help !
String [][] array;
void setup() {
String [] lines = loadStrings("titanicLinearisedDataSet.csv");
array = new String[lines.length][3];
int i = 0;
for(String line: lines){
String [] pieces = split(line,",");
if(pieces[3] == "Nil"){
println("It worked");
}
}
You should not use == to compare String values. You should use the equals() function instead:
if(pieces[3].equals("Nil")){
println("It worked");
}
From the reference:
To compare the contents of two Strings, use the equals() method, as in if (a.equals(b)), instead of if (a == b). A String is an Object, so comparing them with the == operator only compares whether both Strings are stored in the same memory location. Using the equals() method will ensure that the actual contents are compared.
Also watch your curly brackets. The code you posted seems to be missing one.
If that doesn't work, try to get into the habit of debugging your code. For example, try printing out the values of pieces and pieces[3] to see exactly what's going on.

Recursive java method to parse a string with condition?

Fairly new to java and programming.
Wrote this recursive method, with the objective of asking for a valid string that is both an integer and greater than 0:
private int getDimension(String tableElement){
Integer Input= 0;
System.out.println("Define table rows "+tableElement+"'s."
+"Enter an integer >= 1:");
if( !Reader.hasNextInt() || (Input=Input.parseInt(Reader.nextLine())) <= 0)
return getDimension(tableElement);
return Input;
}
I'd like to stick to using a short and recursive method. It seems to handle the >= 0 logic fine, but blows up when i pass it something other than an integer.
Can someone explain why does that happen to me please?
hasNextInt() doesn't actually consume your input, so you're stuck with the same non-int input on your next call.
Simply spoken, your code doesn't make much (any?) sense.
First of all, there is not really a point in using a recursive method that asks the user for input; and that does not at all do anything about the argument passed to it!
private int getDimension(String tableElement){
Integer Input= 0;
Bad: you keep up mixing int and `Integer. They are not the same. And - read about java coding style guides. Variable names start lower case!
if( !Reader.hasNextInt() || (Input=Input.parseInt(Reader.nextLine())) <= 0)
The first condition gives:
true: when there is NO int ...
false: when there is an int
true leads to: calling your method again without retrieving a value from the reader.
false leads to parsing an int; and checking its value for <= 0.
In one case, you are doing a recursive call; completely ignoring the input you got from the reader; in the other case, you returning 0; or that value in input.
Solution: do something like:
while (true) {
if (reader.hasNextInt()) {
input = reader.nextInt();
break;
}
// there is no number!
read.nextLine(); // consume & throw away non-number!
print "Enter a number"
}
instead.
But seriously: start with throwing away this code.
Final side note: you do Input.parseInt() ... but that is a static method on the Integer class. Just call that as Integer.parseInt() instead! But as said; throw away your code; and learn how to properly use that Scanner class; start reading here.
Because the user can enter anything, you must always read in the line, then compare it:
String num = Reader.nextLine();
return num.matches("[1-9][0-9]*") ? Integer.parseInt(num) : getDimension(tableElement);
Here I've use regex to figure out if it's a positive number; the expression means "a 1-9 char followed by 0 or more of 0-9 chars"

Calling substring Method?

I am fairly new to Java. Over the past few weeks I have been trying to teach myself java. This has been primarily based on tutorials i find online and forums I can find. So keep this in mind and any additional critique you can share is greatly appreciated! I am currently trying to create a calculator that runs off of if-else loops. I'm working on a method that allows the user to derive a function based on the principle that if
f(x)=ax^n+bx^o+cx^p... then f'(x)=anx^n-1+box^o-1+cpx^p-1...
I'm trying to use .split() to separate the parts of the function, perform the changes to the individual parts, and then print them together. I could get most of the way through this but I couldn't convert a string with a negative sign to an integer so I am trying to call a method that uses .substring and then replaceAll to get rid of the negative sign then convert to integer. However, I keep getting a compiling error stating the "actual and formal argument lists differ in length". Can anyone explain why this might be happening?
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class InputInteger
{
public String changeSign(String second) {
String negative = second.substring(0,1);
return negative;
}
public static void splitFunction() {
Scanner o = new Scanner(System.in);
String function = o.next();
String[] parts = function.split("(?=\\+|\\-)");
for (int i = 0; i < parts.length;) {
String[] second = parts[i].split("(?=[0-9]+|[a-z]+|[A-Z]+\\^)");
InputInteger.changeSign();
if (negative = ("-")) {
second = second.replace("-","");
int x = Integer.parseInt(second[0]);
int y = Integer.parseInt(second[2]);
int w = x*y;
int z = y-1;
System.out.println(w + "x^" + z);
i++;
}
}
}
Problem that you are talking about is the method not working . You have to pass argument in the function like
InputInteger.changeSign(function);
or
InputInteger.changeSign(second[i]);
according to requirement
changeSign(String second) should be defined as static
negative variable is not defined
you should compare strings with equals() method
you call .replace(...) on an array, which doesn't have this method
And these are only compile errors, I see at least one runtime problem:
you increase i only in the if which may result in an infinite
loop...
I suggest you use some good IDE like Eclipse or IntelliJ IDEA, which will help you with warnings/errors/etc.
First of all in your code if (negative = ("-")) you have a single "=" and I think you meant to use "==" for comparison. Second, method parseInt() as well as valueOf() (which I prefer to parseInt()) should handle negative numbers just fine. there is no need to remove "-". Yout method changeSign() takes a String argument, also your method ChangeSign() returns String value and you must assign a result to some String: String negative = InputInteger.changeSign(str);. Plus also String class has a method startsWith(String prefix) that fits your better then substring(). Hope this helps. If anything there is an Open source library that provides a Utility for parsing String into Integer (among other things). in That util there is a method
parseStringToInt(String numStr, int defaultValue,
String nullOrEmptyStringErrorMessage, String numberFormatErrorMessage)
That tries to parse a String to Integer and if it does not succeed it returns a default value and never throws an Exception. That method definitely works fine with negative integers. Here is the link to the article about the library.https://www.linkedin.com/pulse/open-source-java-library-some-useful-utilities-michael-gantman?trk=pulse_spock-articles. There you will find the instructions on where to get the library including javadoc and source code.

Workaround for declaring array in an if condition

I have a problem with this part of the code where I want to be able to declare an array and the size of which should be the corresponding no of splits in the string.
Or do I need to count the no of commas in the string and allocate size accordingly or is there a better solution.
String MapPath2[];
if(type.equals("comparative"))
MapPath2[]=args[1].split(",");
I haven't had a chance to code in java in the recent past. Please spare me if it is a silly question and guide me as a noob. Appreciate your help.
You don't need to declare the size, what you have is fine if you remove the extra []:
String MapPath2[];
if(type.equals("comparative"))
MapPath2=args[1].split(",");
The array split gives back to you has the appropriate size. If you need to know the resulting size, use MapPath2.length (after assigning it).
You'd probably want to do something in the else as well, so that MapPath2 has a definite value either way:
String MapPath2[];
if(type.equals("comparative"))
MapPath2=args[1].split(",");
else
MapPath2=null;
or more concisely:
String MapPath2[];
MapPath2 = type.equals("comparative") ? args[1].split(",") : null;
(Instead of the nulls there, if having an empty array is preferred for subsequent logic as is sometimes handy, replace null with new String[0] above and below. Other times, it's more handy to have the null as a "no data" flag.)
Side note: There are some overwhelmingly common code style conventions in the Java world that you would be best advised to use in your code:
Variable names should start with a lower case letter, so as not to be confused with class names.
The [] should go with the type name rather than the variable name.
Always use {} even when the body of an if or else is only one line.
Put spaces around operators and keywords for ease of reading.
Applying those:
String[] mapPath2;
if (type.equals("comparative")) {
mapPath2 = args[1].split(",");
}
else {
mapPath2 = null;
}
Many people also put the else on the same line as the }, so:
String[] mapPath2;
if (type.equals("comparative")) {
mapPath2 = args[1].split(",");
} else {
mapPath2 = null;
}
Or again, more concisely:
String[] mapPath2;
mapPath2 = type.equals("comparative") ? args[1].split(",") : null;
You can use List instead of Array if you don't know what size it needs be.
Then you can use
List<String> list = new ArrayList<>();
if(type.equals("comparative")){
Collections.addAll(list, args[1].split(","));
}

Categories

Resources