How to check this If Condition? - Java - java

I have variable number of input values.
Like input is an array with variable values like [6,23,6] or [8,3,97].. like that and also i need to check it against another array.
Hence, I form a condition like this,
StringBuilder formStmt= new StringBuilder("");
for (int i = 0; i < input.size(); i++) {
formStmt= formStmt.append("input[" + i + "] != anotherArray[" +i+ "] &&");
}
formStmt= formStmt.delete(formStmt.length()-2, formStmt.length());
How to check formStmt inside if?
The Thing is I'm forming the if statement using formStmt. I'm forming
formStmt = input[0] !=anotherArray[i] && input[1] != anotherArray[i]
and placing it inside if.. like
if (formStmt){
//code
}
Edit:
I have updated the question. The right side value also is an array. Thats why I go for a stmt like this.?

as far as I understand, you want to check every input[i]'s value against 0. try this :
bool status=true;
for (int i = 0; i < input.size(); i++) {
if(input[i] == 0)
{
status=false;
break;
}
}
if(status)
{ // do your stuff}
so according to your updated question, you will need a nested loop. something like this :
bool status=true;
for (int i = 0; i < input.length && status; i++)
{
for(j = 0; j < anotherArray.length; j++)
{
if(input[i] == anotherArray[j])
{
status=false;
break; // you can use a labeled break if you want
}
}
if(status)
{ // do your stuff}

Don't build up code in a String.
You want to check that all of the elements of the Collection are non-zero.
boolean valid = true;
for (int i = 0; i < input.size(); i++) {
if (input.get(i) == 0) {
valid = false;
break;
}
}

Related

Searching Algoritm

I write this code but I don't know why doesn't work.
static boolean findeText(String text1, String text2) {
char c1[] = text1.toCharArray();
char c2[] = text2.toCharArray();
boolean b = false;
for (int i = 0; i <= c1.length - c2.length; i++) {
for (int j = 0, h = i; j <= c2.length; j++, h++) {
if (i == c2.length) {
return true;
}
if (c1[h] != c2[j]) {
b = false;
break;
}
}
}
return b;
}
I want find text 2 in text 1 and after that return true or false.
if you want to check if some string contains any other string, just use contains() method.
In your case that would be
return text1.contains(text2);
Plus you should always write your code in defensive way. That means you should always make sure there will be no NullPointerException etc. So in your particular case if someone pass either null text1 or null text2, your program will crash.
Above you had NPE in line
if (c1[h] != c2[j])
I have modified your code slightly to get output as requirement.
static boolean findeText(String text1, String text2) {
if ((text1== null) ||(text2==null) || (text1.isEmpty()) || (text2.isEmpty())) {
System.out.println("Invalid input");
return false;
}
char c1[] = text1.toCharArray();
char c2[] = text2.toCharArray();
for (int i = 0; i <= c1.length - c2.length; i++) {
int count = 0;
for (int j = 0; j < c2.length; j++) {
if (c1[i + j] == c2[j]) {
count = count + 1;
}
if (count == c2.length) {
return true;
}
}
}
return false;
}

How do i convert this forEach to forLoop

Hey im trying convert all my ForEachs into ForLoops as i am now using a Linked List.
I am having trouble with this one for some reason! Anyone able to covert the forEach into a forLoop
public String listCounty(String county) {
boolean matchFound = false;
int i = 0;
String displayPropertys = "All Propertys";
for (Property item : house) {
if (item.getGeneralLocation().equals(county)) {
displayPropertys += "\n" + i++ + item;
i++;
matchFound = true;
} else i++;
}
if (!matchFound)
return "No propertys for this County";
else
return displayPropertys;
}
}
Assuming house is a LinkedList<Property> you could use LinkedList.get(int) but it would be more efficient to use a traditional iterator (because accessing arbitrary indices of a LinkedList is potentially expensive). You could also use a StringJoiner. Something like,
public String listCounty(String county) {
boolean matchFound = false;
Iterator<Property> iter = house.iterator();
StringJoiner sj = new StringJoiner(System.lineSeparator());
sj.add("All Propertys");
for (int i = 0; iter.hasNext(); i++) {
Property item = iter.next();
if (item.getGeneralLocation().equals(county)) {
sj.add(String.format("%d%s", i + 1, item));
matchFound = true;
}
}
return !matchFound ? "No propertys for this County" : sj.toString();
}
You should be able to do it using the following.
for(int index = 0; index < house.size(); index++)
{
Property item = house.get(index);
// Your code goes here
}
There's also no need for the i variable now that we have the index from the for loop.
public String listCounty(String county) {
boolean matchFound = false;
String displayPropertys = "All Propertys";
for (int index = 0; index < house.length; index++) {
Property item = house.get(index)
if (item.getGeneralLocation().equals(county)) {
displayPropertys += "\n" + (index + 1) + item;
matchFound = true;
}
}
if (!matchFound)
return "No propertys for this County";
else
return displayPropertys;
}
You can also use an iterator like Elliot suggests. This will give you better performance but is a bit more difficult to read.
Iterator<Property> iterator = house.iterator();
for (int index = 0; iterator.hasNext(); index++) {
Property item = iterator.next();
// Your code goes here
}
As per your question, I am assuming house is a LinkedList
for (int k = 0; k < house.size(); k++) {
if (house.get(k).getGeneralLocation().equals(county)) {
displayPropertys += "\n" + i++ + house.get(k);
matchFound = true;
} else i++;
}

Java ArrayList AWT-EventQueue-0 error IndexOutOfBounds, Calculation

I am having a problem where when I am trying to calculate a scientific expression, it compiles however, it crashes when I run it. The way my program works is that it receives a string containing a mathematical expression which needs to be evaluated. Firstly, it is split into an ArrayList containing numbers and operators separately. It is then searched for any brackets which allows the program to work with the expressions within the brackets first. Then it calls calculate which calculates the answer. The error I keep receiving however is " Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsExcepton: Index:0, Size:0" I assume it has something to do with my sizes of the arraylist however, I cannot spot the error, can anyone else help me figure it out please? I believe the issue is most likely with the methods splitLabel and calculate
public ArrayList<String> splitLabel(String val){
ArrayList<String> label_split = new ArrayList<String>();
String value = "";
String op = "";
for (int i = 0; i< val.length(); i++){
boolean isDigit = Character.toString(val.charAt(i)).matches("[0123456789.]+");
boolean isOperator = Character.toString(val.charAt(i)).matches("[+*/^-]+");
boolean isSin = (Character.toString(val.charAt(i)).equals("s") && Character.toString(val.charAt(i+1)).equals("i") && Character.toString(val.charAt(i+2)).equals("n"));
boolean isCos = (Character.toString(val.charAt(i)).equals("c") && Character.toString(val.charAt(i+1)).equals("o") && Character.toString(val.charAt(i+2)).equals("s"));
boolean isTan = (Character.toString(val.charAt(i)).equals("t") && Character.toString(val.charAt(i+1)).equals("a") && Character.toString(val.charAt(i+2)).equals("n"));
boolean isOpBracket = Character.toString(val.charAt(i)).equals("(");
boolean isClBracket = Character.toString(val.charAt(i)).equals(")");
if (isOperator && !value.equals("")){
op = Character.toString(val.charAt(i));
label_split.add(value);
label_split.add(op);
op = "";
value = "";
} else if (isOperator && value.equals("")){
if (Character.toString(val.charAt(i)).equals("-")){
value = Character.toString(val.charAt(i));
}
} else if (isSin){
label_split.add("sin");
}else if (isCos){
label_split.add("cos");
}else if (isTan){
label_split.add("tan");
} else if (isOpBracket && !value.equals("")){
label_split.add(value);
label_split.add("(");
value = "";
} else if (isOpBracket && value.equals("")){
label_split.add("(");
} else if (isClBracket && !value.equals("")){
label_split.add(value);
label_split.add(")");
value = "";
}
if (i== val.length()-1 && !value.equals("")){
label_split.add(value);
} else if (i== val.length()-1 && Character.toString(val.charAt(i)).equals(")")){
label_split.add(")");
}
} return label_split;
}
public String bracket(ArrayList<String> label_split){
ArrayList<Integer> opBra = new ArrayList<Integer>();
ArrayList<Integer> clBra = new ArrayList<Integer>();
ArrayList<String> calculation = new ArrayList<String>();
int counter = 0;
int counter1 = 0;
if (label_split.contains("(") && label_split.contains(")")){
for (int j=0; j<label_split.size(); j++){
if (label_split.get(j).equals("(")){
counter = counter + 1;
opBra.add(j);
} else if (label_split.get(j).equals(")")){
counter1 = counter1 + 1;
clBra.add(j);
}
}
if (counter1 != counter){
return "error missing bracket";
} else {
for (int j=opBra.size(); j>0; j--){
int opBraPos = opBra.get(j) + 1; //+1 and -1 so it doesn't include ()
int clBraPos = clBra.get(opBra.size()-j) - 1;
opBra.remove(j);
clBra.remove(opBra.size()-j);
for(int t = 0; t < (clBraPos - opBraPos); t++){
calculation.add(label_split.get(t+opBraPos));
}
String value = calculate(calculation);
label_split.set(j , value);
calculation.clear();
for (int n = 0; n < ((clBraPos+1) - opBraPos); n++){
label_split.remove(n);
}
}
}
return calculate(label_split);
} else{
return calculate(label_split);
}
}
public String calculate(ArrayList<String> calculation){
double value = 0.0;
String value1 = "";
boolean isOperator = calculation.contains("[+*/^-]+");
boolean isSin = calculation.contains("sin"); //...ETC
for (int i=0; i < calculation.size(); i++){
if (calculation.get(i).equals("^") && i < calculation.size() && i < 0){
boolean isDigit1 = calculation.get(i-1).matches("[0123456789.-]+");
boolean isDigit2 = calculation.get(i+1).matches("[0123456789.-]+");
if (isDigit1 && isDigit2){
value = Math.pow(Double.parseDouble(calculation.get(i-1)), Double.parseDouble(calculation.get(i+1)));
value1 = Double.toString(value);
calculation.set(i,value1);
calculation.remove(i-1);
calculation.remove(i+1);
}
}
}
for (int a=0; a < calculation.size(); a++){
if ( (calculation.get(a)).equals("sin") && a < calculation.size() && a < 0){
boolean isDigit1 = calculation.get(a+1).matches("[0123456789.-]+");
if (isDigit1){
value = Math.sin(Double.parseDouble(calculation.get(a+1)));
value1 = Double.toString(value);
calculation.set(a,value1);
calculation.remove(a+1);
}
}
}
for (int b=0; b < calculation.size(); b++){
if ( (calculation.get(b)).equals("cos") && b < calculation.size() && b < 0){
boolean isDigit1 = calculation.get(b+1).matches("[0123456789.-]+");
if (isDigit1){
value = Math.cos(Double.parseDouble(calculation.get(b+1)));
value1 = Double.toString(value);
calculation.set(b,value1);
calculation.remove(b+1);
}
}
} // ETC
return calculation.get(0);
}
This is not your problem, but it certainly seems wrong:
calculation.set(i,value1);
calculation.remove(i-1);
calculation.remove(i+1);
The problem is that remove(i-1) is going to cause the index of everything from i onwards to be decremented by one. Then remove(i+1) is going to remove the element that was previously at index i+2.
Then there is this:
for (int i=0; i < calculation.size(); i++){
if (calculation.get(i).equals("^") &&
i < calculation.size() &&
i < 0) {
Think about it. If i starts at zero and is incremented up to size() which is non-negative, how can i ever be less than zero. And if i is never less than zero, how can the if test ever succeed. (You repeat this pattern in other places.)
However, the real problem is that somehow you are calling calculate on an empty list.
I think it is time that you learned to use a debugger .....

How to incorporate a boolean in a method JAVA

I having a hard time getting the right output because i dont know how boolean exactly works inside a method. I have an arraylist and I'm check for any duplicates in the arraylist Here's my code
public void rentOneInstrument(List<Instrument> instrumentList){
String a="";
String b="";
boolean found = false;
for (int j = 0; j < instrumentList.size(); j++) {
a ="";
a = instrumentList.get(j).getName();
for (int i = j+1; i < instrumentList.size(); i++) {
b = instrumentList.get(i).getName();
System.out.println("a" + a + " b" + b);
if(a.equals(b)){
found = true;
}else {
found = false;
}
}
}
if (found) {
System.out.println("duplicate");
}else{
System.out.println("no duplicate");
}
}
Here is my output
a Cymbals b Drums,..
a Cymbals b Cello,..
a Cymbals b Cymbals,..
a Drums b Cello,..
a Drums b Cymbals,..
a Cello b Cymbals
no duplicate // prints no duplicate when there is clearly a duplicate in the output. How can i correct this?
Edit.. Btw I just a want a single out put that prints whether it found a duplicate or not inside the loop
if(a.equals(b)){
found = true
}else {
found = false;
}
This is your problem. This way only the last iteration of your loop will be stored in found. Since you are initializing it as false you don't need to set it to that again here.
for (int i = j+1; i < instrumentList.size(); i++) {
b = instrumentList.get(i).getName();
System.out.println("temp1 " + a + " temp2 " + b);
if(a.equals(b)){
found = true;
}
}
Alternatively, you can use a break statement when you have found a match to get out of the loop like so:
if(a.equals(b)){
found = true;
break;
}else {
found = false;
}
This way, found will be true and no other iterations will be performed, continuing after the end of the loop instead.
Let found be false by default. and just set it true if any duplicate is found.
if(a.equals(b)){
found = true;
}else {
// found = false;
// don't do this otherwise it will override previous `found` value
}
Consider the following input :
a,b,c,a,d
Now whit your code it would be false as d is not repeated. It would over right the value for a that is repeated. Also once a element is fond that it is replanted you don't need to go through the entire loop of all elements hence there is a break.
public void rentOneInstrument(List<Instrument> instrumentList){
String a="";
String b="";
boolean found = false;
for (int j = 0; j < instrumentList.size(); j++) {
a ="";
a = instrumentList.get(j).getName();
if(found) { break; } // Changed line here
for (int i = j+1; i < instrumentList.size(); i++) {
b = instrumentList.get(i).getName();
System.out.println("temp1 " + a + " temp2 " + b);
if(a.equals(b)){
found = true;
break; // Changed line here
}
}
}
if (found) {
System.out.println("duplicate");
}else{
System.out.println("no duplicate");
}
}
Another way of doing it without a break would be
public void rentOneInstrument(List<Instrument> instrumentList){
String a="";
String b="";
boolean found = false;
for (int j = 0; j < instrumentList.size() && !found; j++) {
a ="";
a = instrumentList.get(j).getName();
for (int i = j+1; i < instrumentList.size() && !found; i++) { // Changed for condition to look at the found variable too.
b = instrumentList.get(i).getName();
System.out.println("temp1 " + a + " temp2 " + b);
if(a.equals(b)){
found = true;
}
}
}
if (found) {
System.out.println("duplicate");
}else{
System.out.println("no duplicate");
}
}
A much better way of doing this would be using sets that doesn't contain duplicates.
public void rentOneInstrument(List<Instrument> instrumentList){
Set< Instrument > instrumentSet = new HashSet< Instrument >(instrumentList);
if(instrumentList.size()== instrumentSet.size()) {
System.out.println("no duplicate");
} else {
System.out.println("duplicate");
}
}
public void rentOneInstrument(List<Instrument> instrumentList){
boolean found=false;
List<String> listString=new ArrayList<String>();
for (Instrument inst: instrumentList){
if(listString.contains(inst.getName())){
found=true;
}
else{
listString.add(inst.getName());
}
}
if (found) {
System.out.println("duplicate");
}else{
System.out.println("no duplicate");
}
}

Array Processing

Array Processing
Hi! I need to create a boolean method that processes two strings and returns if one is a subset of another. Example
if AAC is a subset of AAABBCK return true/
I currently have
for (int i = 0; i < shorterArray.length; i++) {
for (int j = 0; j < longerArray.length; j++) {
if longerArray[j] == shorterArray[i] {
count++
}
}
if (count == shorterArray.length) {
return true
) else {
return fasle;
}
}
However this doesn't take into account the repetitions
return longerString.indexOf(shorterString) > -1;
Never mind, thanks to Joachim for correcting me on the definition of subset. Now I have to provide the correct answer.
public boolean isSubset(String subset, String superset)
{
boolean[] used = new boolean[superset.length()];
iLoop:
for (int i = 0; i < subset.length(); i++) {
for (int j = 0; j < superset.length(); j++) {
if (!used[j] && subset.charAt(i) == superset.charAt(j)) {
used[j] = true;
continue iLoop;
}
}
return false;
}
return true;
}
If you can use the built in methods within the String class :
String input="your input string with substring";
CharSequence findMe="substring";
boolean retval = input.contains(findMe);

Categories

Resources