How do I print an array without the first term? - java

I'm writing a program to open up links based on a command entered into a console. The command is "/wiki >term array<", and it will open up a web browser with the wiki open and the term array sent through the search function of said wiki.
Here is my current code for building the term array to send to the search field:
SearchTerm = Arrays.toString(StringTerm).replace("[", "").replace("]", "").replace(",", "");
Now, all that does is get all terms passed the word "/wiki" in my slash command and prints them into a list. It also removes commas and square brackets to make what it prints cleaner.
-- I want to add a specific parameter for the first term in the array, so if it is a specific code such as "/wiki wikipedia chickens" is entered, it will send the user to wikipedia with the term "chickens" searched instead of the default wiki with the terms "wikipedia chickens" searched.
Using the current code that I have to build the term array I need to use Arrays.toString in order to print the whole array in a readable fashion, but I don't want it to print the first term in the array after it passes through my keyword filter?
When I use this code:
WIKI_HYPERLINK = WIKI_WIKIPEDIA + StringTerm[1] + StringTerm[2] + StringTerm[3] + StringTerm[4] + StringTerm[5];
It uses array terms 1 - 5, but if there are only 3 entered terms it will throw an error, and if there are more than 5 it will throw an error.
So my question is: How do I get a whole array excluding the first term?

You could use StringBuilder in a loop
// StringBuilder with initial String
StringBuilder builder = new StringBuilder(WIKI_WIKIPEDIA);
for (int i=1; i < stringTerm.length; i++) {
builder.append(stringTerm[i]);
}
String searchTerm = builder.toString();

You could try something like this:
String outputString = "";
for (int i = 1; i < StringTerm.Length; i++)
{
outputString += StringTerm[i];
}
You may also be able to use a for each loop if there is something like if (Array.Element != 0) in Java, but I don't know of one. Just edit the code above to get it in the format you need.

Related

Java: Find word in string and edit words after the word

For example I have a String like this:
String myString = "Money = 10
Arrows = 4"
I want to edit the arrows, so I have to find the word "Arrow" in the String and edit the number "4". Any idea how to do that?
Thanks!
If you want to edit a value easily based on something else in the program, you can make it so the number is a variable instead. Judging by the code as well, you want there to be a new line, currently it's not doing that since you need to use "\n"
So the code should look like:
int arrows = 4;
String myString = "Money = 10" + "\n" + "Arrows = " + arrows;
If you then change the value of the integer arrows before declaring the string it will be different.
I don't use java that much but if you need to find out is something is a letter you can use
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5'));
And since your data is in a string you can loop trough it like trough an array, as far as I remember.
for(int i =0; i < yourStringName.length; i++)
But I must agree with #jack jay.
So here is a helpful post Java associative-array

Java String.split() and compare

Im working with flying saucer and want to export an xhtml to an pdf.
Everything works fine, but now I want to add an empty column, for example for descriptions or something.
I want to create a method addColumn(). which should add in every row of the table at the end a new, empty cell.
I tried following code:
String[] arr = content.split("<td");
String test = "";
for (int i = 0; i < arr.length; i++) {
if(i != 0){
arr[i] = "<td" + arr[i];
test += arr[i];
}
}
This should split the content on every beginning "td" tag.
String.split("<td") removes the "<td" from the content so i want to add it again.
But if i compare those:
if(test.equalsIgnoreCase(content)){
System.out.println("SUCCESS");
}
else{
System.out.println("FAIL");
}
I always fail.
Just help me to get the right content back out of the array, this would make me go a step in the right direction!
Thank you.
Try to replace your split line with this:
String[] arr = content.split("<td", -1);
Otherwise you will loose some input in arr, see the split(String) API doc:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
The added -1 makes sure that your content can also contain "<tr" at its beginning, for example. See the split(String, int) API doc for further explanations.

substring methods java

So I've been working on this portion of code for a while and I need help. I need to use a substring to print out a user input vertically. I think I am close but just need one litttle tip I think.
public static void method3(){
System.out.print("Method 3");
Scanner console = new Scanner(System.in);
String height = console.nextLine();
System.out.println(" Type in a word to be printed vertically!");
String str = console.nextLine();
System.out.println(str.charAt(height) + " ");
Simple option is-
System.out.println(str.charAt(height) + " ");
Or you can convert to char array and iterate through it.
String.substring() is a method, not a field, meaning you need to call str.substring() rather than simply str.substring. Further, the substring method takes parameters - you have to tell it the specific substring you want in the form of which indexes within the string. str.substring(0, 2) would print characters 0 and 1 (the upper bound is not included). For your purposes, str.substring(height, height+1) would work...
IF you have to use substring.
I would recommend using str.charAt(height), which accomplishes the same goal.
EDIT (based on your edit) :
1) You have height defined as a String, then you call str.charAt(height). The charAt() method takes an int parameter - if you give it 6, it will give you the charater at index 6 (i.e. the seventh letter) in the string. Knowing that, it doesn't make any sense to pass a String in as a parameter, does it?
2) You're still going to need a loop to accomplish this. Something like:
String str = console.nextLine();
for (int height = 0; height < str.length; height++) {
System.out.println(str.charAt(height);
}
Does that make sense? Let me know if I need to walk you through what we're doing in this.

Sorting info from a txt file into two different arrays

For a uni assignment, I have to take input from a text file and sort it into two separate arrays. The text file is a football league table, arranged as such:
Barcelona 34
Real Madrid 32
I have written a piece of code like this:
holdingString = fileInput.readLine ();
StringTokenizer sort = new StringTokenizer (holdingString + " ");
countOfTokens = sort.countTokens();
System.out.println (countOfTokens + " tokens: " + holdingString);
This prints out the number of tokens and what the tokens are for each line, so it gives output of
Two tokens: Barcelona 34
Three tokens: Real Madrid 32
I've then written this piece of code:
for (int i = 0; i < countOfTokens; i++)
{
String temp = sort.nextToken ();
System.out.println(temp);
}
This reads just the next token and prints it out.
However, rather than printing the next token out, I want to check if it is a word or a number, and separate it into a different array accordingly, so it will be like this:
ArrayTeam Zero Element Barcelona
ArrayTeam First Element Real Madrid
ArrayPoints Zero Element 34
ArrayPoints First Element 32
What's the easiest way to do this? I've tried using a try/catch, but didn't get it right. I've also tried using an if statement with \d, but that's not worked either.
Like AmitD, I agree that using split is more appropriate in this case, but if you still like to use a StringTokenizer you do something like:
StringBuilder teamName=new StringBuilder();
for (int i = 0; i < countOfTokens-1; i++)
{
if (i>0) teamName.append(' ');
teamName.append(sort.nextToken());
}
teamNames[k]=teamName.toString(); //add the new team to your teamNames array
points[k]=Integer.parseInt(sort.nextToken()); //if your points array is of int type
you could use java.util.Scanner class to read data from the file. it has methods such as nextInt(), nextDouble ...whhich might be useful in your case.
Scanner scan = new Scanner(file);
int number;
if(scan.hasNextInt()){
number = scan.nextInt();
}
check Scanner API
String readLine = "Real Madrib 40";
String[] team = readLine.split( "\\d" );
System.out.println(team[0]);
String score = readLine.replace( team[0],"" );
System.out.println(score);
Output :
team[0] : Real Madrib
score : 40
You can save all that trouble using split
String strs[] = holdingString.split("\\s");
E.g.
"Barcelona 34".split("\\s"); will return you Array of Strings where
array[0]=Barcelona array[1]=34
From Javadoc of StringTokenizer
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
Update
As #madhairsilence pointed out
You need another deliminator. You can use = like property files
"Real Madrid =34".split("=");//will return you Array of Strings where
array[0]=Real Madrid, array[1]=34
You can use Scanner as you are reading from file.

strange problem in an array

I'm working on a little server app with Java. So, I'm getting informations from different client, and if information comes in, the following method is called:
public void writeToArray(String data) {
data = trim(data);
String[] netInput = new String[5];
netInput[0]="a";
netInput[1]="a";
netInput[2]="a";
netInput[3]="a";
netInput[4]="a";
netInput = split(data, ",");
pos_arr = PApplet.parseInt(netInput[0]);
rohr_value = PApplet.parseInt(netInput[1]); // THIS LINE KICKS OUT THE ERROR.
if(pos_arr >0 && pos_arr<100) {
fernrohre[pos_arr] = rohr_value;
println("pos arr length: " + fernrohre[pos_arr]);
println("pos arr: " + pos_arr);
}
The console on OS X gives me the following error:
Exception in thread "Animation Thread"
java.lang.ArrayIndexOutOfBoundsException:1
at server_app.writeToArray(server_app.java:108) at server_app.draw(server_app.java:97)
at processing.core.PApplet.handleDraw(PApplet.java:1606)
at processing.core.PApplet.run(PApplet.java:1503)
at java.lang.Thread.run(Thread.java:637)
As you can see, I tried to fill the array netInput with at least 5 entries, so there can't be an ArrayIndexOutOfBoundsException.
I don't understand that, and I'm thankful for your help!
It would work already for me, if I can catch the error and keep the app continuing.
You put 5 Strings into the array, but then undo all your good work with this line;
netInput = split(data, ",");
data obviously doesn't have any commas in it.
In this line
netInput = split(data, ",");
your array is being reinitialized. Your split method probably returns an array with only 1 element (I can guess that data string doesn't contain any ",").
Update
The split() method is custom, not String.split. It too needs to be checked to see what is going wrong. Thanks #Carlos for pointing it out.
Original Answer
Consider this line:
netInput = split(data, ",");
This will split the data string using comma as a separator. It will return an array of (number of commas + 1) resulting elements. If your string has no commas, you'll get a single element array.
Apparently your input string doesn't have any commas. This will result in a single element array (first element aka index = 0 will be the string itself). Consequently when you try to index the 2nd element (index = 1) it raises an exception.
You need some defensive code,
if(netInput.length > 1)
pos_arr = PApplet.parseInt(netInput[0]);
rohr_value = PApplet.parseInt(netInput[1]);
You make
netInput = split(data, ",");
and
split(data, ",");
returns one element array
You are re-assigning your netInput variable when the split() method is called.
The new value might not have an array count of 5.
Can you provide the source for the split() method?

Categories

Resources