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
Related
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
}
}
}
This question already has answers here:
Best way to convert an ArrayList to a string
(27 answers)
Closed 3 years ago.
So I am having trouble trying to loop through an array list but i dont want to use a println statement to print the elements from the array list. Is it possible if i could store all the elements into a local variable through each loop and then return the local variable when i call the method later on?e
Here is my code:
public String displayProperties() {
String property = null;
for (int i = 0; i < properties.size(); i++) {
property = properties.get(i);
}
return property;
}
You would have to introduce an instance variable in order to cache the result of your method (your local variable doesn't live past the current execution of the method).
And you'd also need to change the logic of that method, to append all the elements into a single String.
I also suggest adding some separator between the elements.
private String cachedProperties = null;
public String displayProperties() {
if (cachedProperties == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < properties.size(); i++) {
if (i > 0) {
sb.append(',');
}
sb.append(properties.get(i));
}
cachedProperties = sb.toString();
}
return cachedProperties;
}
Note that if the properties List may change, you have to reset your cache instance variable each time that happens.
May be modify the code to get the final string as below
property += properties.get(i);
property += " "
This question already has answers here:
Default or initial value for a java enum array
(5 answers)
Can we assume default array values in Java? for example, assume that an int array is set to all zeros?
(4 answers)
Closed 4 years ago.
I created an enum array like this:
enum MyEnums {
FIRST, SECOND, THIRD, FOURTH;
}
public class MyEnumsTest {
public static void main(String[] args) throws Exception {
MyEnums[] myEnums = new MyEnums[4];
for(int i = 0; i< myEnums.length; i++) {
System.out.println(myEnums[i]);
}
}
}
But why is the output null, null, null and null? And how can I get the element by myEnums[i].FIRST?
What you're doing here is creating an array of MyEnums, and the default value is null (you haven't set the values in the array).
If you wanted to print out the enum values you can use the values() method:
for(MyEnums en : MyEnums.values()) {
System.out.println(en);
}
or (more like your original code)
for(int i = 0; i < MyEnums.values().length; i++) {
System.out.println(MyEnums.values()[i]);
}
This prints:
FIRST
SECOND
THIRD
FOURTH
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]);
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I've created a class called Human that works properly, it takes 2 arguments, age and name, to create a human.
To create a Human with command line arguments, I want to write
java Filename -H "Anna" 25
And it should create a Human with thatname="Anna", and thatage=25, where 25 is an int.
The code I've written is creating a list called Argument, and iterating through it to find -H. I need to do this because I'm going to be using this to create different classes later. I just need help with the syntax on the lines where I've written thename=, and theage=, because I don't know how to get the next item in list, and next-next item in list.
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
for (String item2: Argument) {
if (item2 == "-H") {
thatname = Argument.get(item2+1)
thatage = Argument.get(item2+2)
Human person = new Human(thatname,thatage);
System.out.println(person);
}
Why not just loop the args?
for ( int i = 0; i < args.length; i++ ) }
if (args[i].equals("-H")) {
i++;
thatName = args[i];
i++;
thatAge = args[i];
}
}
You should add some code to catch if one does not follow the rules you have set. Probably not enough arguments or other things humans do at the keyboard...
thatname = Argument.get(Argument.indexOf(item2)+1);
thatage = Argument.get(Argument.indexOf(item2)+2);
OR you know that 1st element is -H, 2nd element is name and 3rd is age, so you can use below code directly
thatname = Argument.get(1);
thatage = Integer.parseInt(Argument.get(2));
Your code have some problems, let me explain them to you for your assistance.
You cannot compare Strings with == you have to use equals method
in the String to compare between two Strings.
You have to use this for loop for(int i = 0; i < Argument.size();
i++) syntax so that you can iterate from zero to the number of
items in the list.
get method in ArrayList take the index as parameter and return the value at that index.
You can add i += 2 to skip the next two iterations which will
return the name and age value of the human. (It is optional)
Here is the working code:
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
String currentItem;
for (int i = 0; i < Argument.size(); i++) { // it will iterate through all items
currentItem = Argument.get(i); // getting the value with index;
if (currentItem.equals("-H")) {
String thatname = Argument.get(i+1);
String thatage = Argument.get(i+2);
i += 2; // Skipping 2 iterations of for loop which have name and age human.
Human person = new Human(thatname,thatage);
System.out.println(person);
}
}
}
You cannot iterate the list using String. When iterating a list you required a index number like list.get(indexNumber);
public static void main(String[] args) {
ArrayList<String> Argument = new ArrayList<String>();
for (String item: args) {
Argument.add(item);
}
for (int i=0;i<args.length;i++) {
if (args[i].trim().equals("-H")) {
i++;
thatname = Argument.get(i);
i++;
thatage = Argument.get(i);
Human person = new Human(thatname,thatage);
System.out.println(person.getName()+" "+person.getAge());
}
Why using array list when you can directly use args? and while you're having only two parameters don't use a for loop access them direclty.
One thing you should know is that String is an object in java so comparing two Strings with == sign will return false even if they have same value (== will compare the id of the object), you should use .equale() function to compare the value of the object.
Check out this code :
public static void main(String[] args) {
if(args.length>0)
{
try{
if (args[0].equals("-H")) {
Human person = new Human( args[1],args[2]);
System.out.println(person);
}
}catch(ArrayIndexOutOfBoundsException exception) {
System.out.println("error with parameters");
}
}else
System.out.println("No command");
}