simple String example [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
i have the following piece of code but i could not detect why there is no output
when i debug it , the control flow is never goes inside for loop but i cannot figure out why
could anyone please help me ?
here is my code
public class DealWithStrings {
ArrayList<String> container = new ArrayList<>();
public void printDuplicate() {
String string = "aaabed";
String[] res = string.split("");
for (int i = 1; i < string.length(); i++) {
if (res[i] == res[i - 1]) {
container.add(res[i]);
}
}
for (String s : container) {
System.out.println(s);
}
}
public static void main(String[] args) {
DealWithStrings d = new DealWithStrings();
d.printDuplicate();
}
}

Compare String using .equals, not ==
Instead of
if(res[i]==res[i-1])
Use
if(res[i].equals(res[i-1]))
== will evaluate to true if the objects are the same, and in this case they never are. .equals will check if the contents of the Strings (the actual text) are the same.

Replace your code '==' operator with '.equals()' method, because ,
'==' equal operator compares the reference of the two characters in memory, whereas you need to check 'contents' at that reference.
And .equals method is overridden to check the content for Strings.
for (int i = 1; i < string.length(); i++) {
if (res[i].equals(res[i - 1])) {
container.add(res[i]);
}
}

Related

Check if input is any of the values in an array [duplicate]

This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 2 years ago.
I want to be able to check if the string input matches any of the strings in array, and then run only if it matches any of the strings.
String[] list = {"hey","hello"};
if (input == anyofthestringsinarray) {
}
Thought something like if(input.equalsIgnoreCase(list)) {} could work, but dont. Any tips?
Try this:
public static void stringContainsItemFromList(String inputStr, String[] items)
{
for(int i =0; i < items.length; i++)
{
if(inputStr.contains(items[i]))
{
// if present do something
}
}
}

Why does my switch case work here, but if does not? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I am learning how to use Lists, and in my following example the switch case works but (what I deem as) the equivalent if statement does not. Can you tell me why?
public class Kapitel14 {
public static void main(String[] args) {
ArrayList<String> testList = new ArrayList<String>();
testList.add("Cousin");
testList.add("Doof");
testList.add("Dorf");
testList.add("Dortmund");
testList.add("Franz");
System.out.println(listCount(testList));
}
public static int listCount(ArrayList<String> newList) {
int capDCounter = 0;
for (String element : newList) {
String firstLetter = Character.toString(element.charAt(0));
switch (firstLetter) {
case ("D"):
capDCounter++;
break;
default:
continue;
}
//if I use this instead it returns wrong results:
//if (firstLetter == "D")
// capDCounter++;
}
return capDCounter;
}
Use
if (firstLetter.equals("D"))
capDCounter++;
instead of
if (firstLetter == "D")
capDCounter++;
.equals() method should be used here as you want to compare the values of strings.

Passing strings to an array through a method [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Implement a method for adding elements to the class CacheMemory.
The Class cache memory has an array memory whose length is passed through a constructor.Elements can be added to the array only if it has not been added before and if the length of the arrays added is within the boundaries of the array.(within its length).
This is the code I came up with so far:
public class CacheMemory {
private String[] memory;
public CacheMemory(int length) {
this.memory = new String[length];
}
public void addingElementsToCache(String mem) {
for (int i = 0; i < memory.length; i++) {
if (memory[i] != mem) {
memory[i] = mem;
System.out.println(mem);
break;
} else {
System.out.println("Element already exists");
}
}
}
}
If i call this method without break,of course it will print out the string five times,but I don't want the same string to be printed out five times,I want to add five different strings and then,while loop goes through the array,and comes to element that has already been passed,to print out the message.
Actually , you need to use !string.equals("anotherString") instead of !=,since the != only compare the address of the string ,instead of the content of the string,but the method equals does it.
You got some of the logic wrong. You have to wait until you have checked all elements in the cache before you can decide that it doesn't already exist. And also, you should use .equals() for comparing Strings.
public void addingElementsToCache(String mem)
{
// Loop over slots
for (int i = 0; i < memory.length; i++)
{
if (memory[i] == null) {
// You have reached an unused slot, use it!
memory[i] = mem;
System.out.println(mem);
return;
}
else if (mem.equals(memory[i])) {
// You found a duplicate
System.out.println("Element already exists");
return;
}
}
// You have checked all positions without finding an empty slot
System.out.print("The cache was full, unable to add!");
}
If you exercise this code with
public static void main(String[] args)
{
CacheMemory cache = new CacheMemory(10);
asList("foo", "foo", "bar", "boz", "bar")
.forEach(cache::addingElementsToCache);
}
... it will print the following, which is what I think you expect:
foo
Element already exists
bar
boz
Element already exists

Java - search a string in string array [duplicate]

This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 6 years ago.
In java do we have any method to find that a particular string is part of string array.
I can do in a loop which I would like to avoid.
e.g.
String [] array = {"AA","BB","CC" };
string x = "BB"
I would like a
if (some condition to tell whether x is part of array) {
do something
} else {
do something else
}
Do something like:
Arrays.asList(array).contains(x);
since that return true if the String x is present in the array (now converted into a list...)
Example:
if(Arrays.asList(myArray).contains(x)){
// is present ... :)
}
since Java8 there is a way using streams to find that:
boolean found = Arrays.stream(myArray).anyMatch(x::equals);
if(found){
// is present ... :)
}
You could also use the commons-lang library from Apache which provides the much appreciated method contains.
import org.apache.commons.lang.ArrayUtils;
public class CommonsLangContainsDemo {
public static void execute(String[] strings, String searchString) {
if (ArrayUtils.contains(strings, searchString)) {
System.out.println("contains.");
} else {
System.out.println("does not contain.");
}
}
public static void main(String[] args) {
execute(new String[] { "AA","BB","CC" }, "BB");
}
}
This code will work for you:
bool count = false;
for(int i = 0; i < array.length; i++)
{
if(array[i].equals(x))
{
count = true;
break;
}
}
if(count)
{
//do some other thing
}
else
{
//do some other thing
}

compare an String and an array element in java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am trying to compare an String and an array element. If the requested element
package com.company;
public class Main {
static String[] List = {
"EUR", "AED"
};
static String[] IdList = {
"EUREUR", "EURAED", "AEDEUR","AEDAED"
};
public static void main(String[] args)
{
String value1 = "EUR";
String value2 = "EUR";
for(int i = 0; i < IdList.length; i++)
{
System.out.println(value1+value2 == IdList[i]);
}
}
}
The problem is that it always returns false . Even if the requested String matches to a value in the array. Can you help me?
You must use String.equals(), not the == operator, to compare strings reliably.

Categories