Is there a way to retrieve a string from an ArrayList if we know the index of the string we want to retrieve? for example in this string:
String text2 = "if(AGE_Y>15){\r\n"
+ "x=PROPERTY_LENGTH;\r\n"
+ "}";
The list this string is added to would look like : if, (, AGE_Y, >, 15, ), {, ...
Now if we loop through the list and add each item to a StringBuilder and define the index for each item:
for (int i = 0; i < list.size(); i++)
{
a=list.get(i);
strBuilder.append(a);
index = strBuilder.length() - a.length();
}
We will know exactly at what index we have the string "PROPERTY_LENGTH" for example.
My question is, how can we retrieve the string "x" from the List? I'm asking because at the line above "x"(or whatever that variable will be named) I want to insert something else in the StringBuilder. Normally we could do something like:
String previous=list.get(indexOfPropertyLength-2);
strBuilder.insert(index-previous.length-1,"string to insert");
Is this at all possible?
Firstly you can rewrite your list iteration to work more efficiently:
for (int i = 0; i < list.size(); i++) {
a=list.get(i);
index = strBuilder.length(); // (you don't have to calculate an index)
strBuilder.append(a);
}
To address the title of your question, if you want to simply find a String in a List given an index, you can of course use myList.get(myIntIndex);. However, it seems that you're asking how to find an index given a String: myList.indexOf(myString) or something of that nature. If you could be a bit clearer, we might be of more help. Are you writing a hybrid assembler or compiler?
Related
I am trying to print user input from an array to display in java. When i run this, it just prints out "null" for each amount no matter what the user inputs. I am a beginner at java and want to learn more about arrays, and I can't seem to figure this out.
String itemAmount = ss.getInputString("How many items?");
int amount = Integer.parseInt(itemAmount);
String[] Items = new String[amount];
for (int i = 0; i < Items.length; i++) {
ss.getInputString("Please enter items?");
}
for (int i = 0; i < Items.length; i++) {
ss.println((Items[i]));
}
Also, how would i be able to print the items, for example user inputs 3 items -> "Eggs", "Bacon", "Tomato" how would I print this to show in a line separated by commas.
I'm not sure what gt is, but since you're using it this way
String itemAmount = gt.getInputString("How many items?");
I guess it's some sort of wrapper around the standard input.
You can use it the same way to populate an array, one item at a time.
for (int i = 0; i < Items.length; i++) {
Item[i] = gt.getInputString("Please enter items?");
}
You seem to be able to use the array in the other loop, so I'll assume you don't need further explanation.
Then to print them on a single line, separated by a comma you can use the join method of String (note: you need to convert your array to a List, first)
String joinedString = String.join(", ", Arrays.asList(Items));
I think you are checking the length of wrong array/string in second for loop. It should be Items.length not Appliances.length
OK so I'm trying to design a simple program that checks to see if a substring of length 4 characters is within all initial strings. Here is my code as follows:
public class StringSearch{
private String[] s1Array = {"A","C","T","G","A","C","G","C","A","G"};
private String[] s2Array = {"T","C","A","C","A","A","C","G","G","G"};
private String[] s3Array = {"G","A","G","T","C","C","A","G","T","T"};
//{for (int i = 0; i < s1Array.length; i++){
// System.out.print(s1Array[i]);
//}}//check if Array loaded correctly
/**
* This is the search method.
*
* #param length length of sub string to search
* #param count counter for search engine
* #param i for-loop counter
* #return subStr returns strings of length = 4 that are found in all 3 input strings with at most
* one mismatched position.
*/
public String Search()
{
int length = 4;
int count = 0;
int i = 0;
ArrayList<StringSearch> subStr = new ArrayList<StringSearch>();
//String[] subStr = new String[4];
do
{
for (i = count; i < length; i++){
subStr.add(s1Array[i]); // cant find .add method???
count = count + 1;
}
if (s2Array.contains(subStr) && s3Array.contains(subStr)){ //can't find .contains method???
System.out.println(subStr + "is in all 3 lists.");
}
if (count = s1Array.length){
System.out.println("Task complete.");
}
else{
count = count - length;
count = count + 1;
}
}while (count <= s1Array.length);
}
}
For some reason, Java cannot seem to find the .add or .contains methods and I have no idea why. So my approach was to turn the initial Strings each into an array (since the assignment specified each string would be exactly N elements long, in this case N = 10) where 1 letter would be 1 element. The next thing I did was set up a for loop that would scan s1Array and add the first 4 elements to an ArrayList subStr which is used to search s2Array and s3Array. Here is where .add isn't a valid method, for whatever reason. Commenting that out and compiling again, I also ran into an issue with the .contains method not being a valid method. Why won't this work? What am I missing? Logically, it seems to make sense but I guess maybe I'm missing something in the syntax? Help would be appreciated, as I'm a Java novice.
There are lots of errors and misunderstandings here.
Let's start with #1
private String[] s1Array = {"A","C","T","G","A","C","G","C","A","G"};
Making an array of strings is just silly, you should either use a single string or an array of characters.
private String s1 = "ACTGACGCAG";
Or
private char[] s1Array = {'A','C','T','G','A','C','G','C','A','G'};
Now #2
ArrayList<StringSearch> subStr = new ArrayList<StringSearch>();
This means you are trying to make an ArrayList that contains objects of type StringSearch. StringSearch is a class that contains your three arrays and your Search function so I don't think this is what you want.
If you wanted to make a list of 3 strings you might do something like this:
ArrayList<String> stringList = new ArrayList<String>();
stringList.add(s1);
stringList.add(s2);
stringList.add(s3);
Now say you defined s1, s2 and s3 as strings you can do something like this.
for(int i = 0; i <= s1.length() - 4; i++)
{
String subStr = s1.substring(i, i + 4);
if(s2.contains(subStr) && s3.contains(subStr))
{
System.out.println(subStr + " is in all 3 lists.");
}
}
System.out.println("Task Complete.");
The above code should achieve what it looks like you are trying to do. However, it should be noted that this isn't the most efficient way, just a way, of doing it. You should start with some more basic concepts judging by the code you have so far.
After declaring subStr as ArrayList you can call add or contains only with StringSearch objects as parameters.
Instead of:
ArrayList<StringSearch> subStr = new ArrayList<StringSearch>();
Replace it with:
String subStr = "";
And within the for loop to get the first 4 letters in s1 to be in its own string (subStr) add the line:
subStr += s1Array[i];
Also, s1Array is a String array, and not a String. The .contains method is a method that belongs to String variables, so for eg. the way you have it implemented, you can say s1Array[i].contains. But you cannot say s1Array.contains. If you change your String arrays to Strings and edit your code to suit, everything should work the way you expect it to work.
First of all you need to educate yourself on the concept of Java generics.
The most basic thing about generics is that once you declare a collection, here it is the arraylist, as you can only add objects of StringSearch.
Second of all, logically what you can do is to implement an algorithm called
Longest Common Subsequence. Check in pairs whether the longest subsequeces are 4 or not on the arrays.
I believe that we can use a for loop to reverse a string in Java. Just like below:
String[] name = new String[10];
for(int i = name.length; i >0; i--){
System.out.print(name[i-1]);
}
But another implementation is using LinkedList. So my understanding is to use LinkedList when the client is not sure how long the string array might increase dynamically. Is that correct?
A linked list of characters can be used to do this.
In this instance, think of an array list as an array with unlimited length. For this, instead of adding values to the END of the array, we will add them to the BEGINNING of the linked list
LinkedList<Character> linkedList = new LinkedList<Character>();
String str = "Hello World";
for (int i = 0; i < str.length(); i++) {
linkedList.addFirst(str.charAt(i));
}
//whenever it is time to print the value....
for (char c : linkedList) {
//Print it out, one character at a time
System.out.print(c);
}
Whenever you have to add more characters to it, just use linkedList.addFirst() to append it to the beginning.
I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.
So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int stringNumber = 0;
String[] stringArray = new String[10];
for (int i = 0; i <= stringArray.length; i++) {
out.println("\nEnter a string");
String input = keyboard.next();
stringArray[stringNumber] = input;
out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");
PrintArray(stringArray);
stringNumber++;
You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.
for (int i = 0; i <= stringArray.length; i++) {
boolean isInArray = false;
System.out.println("\nEnter a string");
String input = keyboard.next();
if (i > 0) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[j].equalsIgnoreCase(input)) {
isInArray = true;
break;
}
}
}
if (!isInArray) {
stringArray[stringNumber] = input;
} else {
System.out.println("\"" + stringArray[stringNumber-1] + "\""
+ " has been stored.");
}
PrintArray(stringArray);
stringNumber++;
}
It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.
If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.
public static boolean contains(String[] array, String value) {
// Iterate over the array using for loop
// For each string, check if it equals to value.
// Return true, if it is equal, else continue iteration
// After the iteration ends, directly return false.
}
For iterating over the array, check enhanced for statement.
For comparing String, use String#equals(Object) method.
When you got the String input, you can create a method that will :
Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
Returns a boolean value wheter the string is in the array or not
Then just add a while structure to re-ask for an input
Basically it can look like this :
String input = "";
do {
input = keyboard.next();
}while(!checkString(input))
The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.
Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.
For me the best solution is to have a helper HashSet to check the item for presence.
Also have a look at this question.
To avoid you should use an Set instead of an array and loop until size = 10.
If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.
while (no input or duplicated){
ask for a new string
if (not duplicated) {
store the string in the array
break;
}
}
You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.
public boolean exists(String[] strs, String search){
for(String str : strs){
if(str.equals(search))
return true;
}
return false;
}
performance would be O(n) as it searchs linearly.
Sometimes, due to faulty data collected, a line generated by the following method ends up looking like this when saved: ",-1,0" or something similar, with no name, an ID of -1 and a level of 115 or something else. (The lines are formatted like this (excluding quotes): "name,id,level" (e.g: "Honour guard,5514,115")
What i need to do is to remove all strings in monstersToAdd that contains -1.
I've tried this, but with no success:
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
monstersToAdd.remove(monstersToAdd.contains("-1"));
}
with the line monstersToAdd.remove(monstersToAdd.contains("-1")); I was trying to remove all strings in monstersToAdd that contains "-1". This however does not work, probably for good reasons, which I unfortunately don't know of yet.
I would really appreciate any input :).
You would be better off not adding the lines you don't want in the first place.
for (....) {
if (IDs[i] != -1) {
// add it
}
// else it simply doesn't get added
}
More on your original code: You could post a little more detail, such as the type of monsterToAdd. If it is a non-generic list, then the contains method just returns true or false depending if the parameter (here a string of "-1") is present in the list exactly as you pass it, that is it doesn't search for substring matches of the list elements.
remove then tries to remove the element you ask to remove, which may be a Boolean object, automatically boxed from the boolean primitive value returned by contains.
Also, it is suspicious that you have a variable called monsterList which you use for iteration length, but not actually use any elements from that list. Maybe the arrays you use have the same values as the list, and were copied out beforehand? If so, it would be nicer to iterate on the monsterList directly and use its elements.
Its easier if you dont even add them, than adding and removing them so check the sanity of ID names and levels before adding them
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
//add only if name is non empty, ID is not negative and level is below 100
if(!(names[i].isEmpty() || IDs[i]<0 || levels[i]>100))
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
Why don't you do this instead:
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
if(IDs[i] != -1){
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
}
monstersToAdd.remove(monstersToAdd.contains("-1"));
}
That way, you never add the monster to the list in the first place, if the ID is -1.
You are really close:
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
if (IDs[i] == -1) continue; // Skip this iteration
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
}
Filter them out as early as possible rather than back-tracking and removing them.
contains() returns only a true/false result depending on whether the list contains the given input object (in your case the string "-1"). So in your example, your list wouldn't contain "-1", so your remove statement would be resolved to this:
monstersToAdd.remove(false);
which wouldn't work for obvious reasons.
Here is the code:
for(Iterator<String> it = monsterList; it.hasNext();) {
String elem = it.next();
if (elem.contains("-1")) {
it.remove();
}
}
contains() method of collection returns true if collection contains element equals to one passed as an argument. In you case you want to use String's contains() that returns true if the string contains specified substring. This is the reason that you need loop.
This loop must be implemented with iterator. Using new java 5 syntax for(String elem : list) will not work here because you have to remove element. Using for(int i = 0; i < list.size(); i++) requires implementation of logic that safely moves to the next index after element removal.
And the last point. You have to use iterator.remove() instead of Collection.remove() to avoid ConcurrentModificationException