Can somebody explain me why this code does not print the numbers?
String text = new String("SomeString");
for (int i=0; i<1500; i++) {
text = text.concat(i+"");
}
System.out.println(text);
Result
SomeString
If I lower the number of runs to 1000 it works, why?!
And also if I add not only a number but also a character, it works.
Ok New Update:
Thanks for the code examples. I tried them all but what I found out is, that the console
actually display the numbers but only in fontcolor white. But the first part of the String
SomeString is black.
I use jdk1.7.0_06 !
This is eclipse bug. Fixed width console fixes the output.
String.concat() accepts a String parameter.
If you add "a number and a character" you are adding a string because the + operator understands you are chaining String and numeric data.
Anyway code runs fine to me, numbers appended till 1499 as expected.
There are a couple things you could try. I'll give you an example of both.
First, in Java you can simply add strings together. Primitives such as int should be automatically converted:
String text = new String("SomeString");
for (int i = 0; i < 1500; i++) {
text += i;
}
System.out.println(text);
Second, if the first method still isn't working for you then you can try to explicitly convert your int to a String like so:
String text = new String("SomeString");
for (int i = 0; i < 1500; i++) {
text += Integer.toString(i);
}
System.out.println(text);
To do the same more efficiently
StringBuilder text = new StringBuilder("SomeString");
for (int i = 0; i < 1500; i++) {
text.append(i);
}
System.out.println(text);
Both examples work for me on Java 6 update 32 and Java 7 update 3.
Woah, this is weird. I got the same result. At first glance, it looks like a bug in the JVM, but I tried running the program from the command-line and it works fine. It must be a bug in the Eclipse console. I found that changing the console to have a fixed width solves the display issue.
I also found that if you replace i + "" with i + "," it displays fine. It seems there's something Eclipse console doesn't like about having a long continuous stretch of pure numbers.
String text = "SomeString";
for (int i = 0; i < 15000; i++) {
// text = text.concat(i + ""); // Doesn't display correctly
// text += i; // Doesn't display correctly
text = text.concat(i + ","); // Displays correctly
// text += i + ","; // Displays correctly
}
System.out.println(text);
This bug is somewhat worrying to me. Good find!
UPDATE: I tried just printing a long line of "xxxxxx" and found that up to 32000 characters are displayed correctly. When the line goes to 32001 it's not displayed. When I put "12345" + "xxxxxxxxx...", I was still able to display 32000 "x" characters which means the line length is longer than 32000, so it's nothing to do with total line length. It seems that it's to do with the length of parts of String objects.
Related
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
Wrote a program to display all that character. But the output only display the ? character. I am a total newbie, please help.
public class charSheet {
public static void main(String args[]){
char c;
for(int i = 0; i < 65536; i++){
c = (char) i;
System.out.println(i + "---" + c);
}
}
}
Output(only a part):
57987---?
57988---?
57989---?
57990---?
57991---?
57992---?
Try printing it till 100, it does prints some characters, you probably are using command prompt which does not supports much characters, try using some IDE such as Eclipse, i think you will get better results.
Range of characters are from 0 - 255.
Everything after that is therefore irrelevant.
I am trying to take a file full of strings, read it, then print out a few things:
The string
The string backwards AND uppercase
The string length
There are a few more things, however I haven't even gotten to that point and do not want to ask anyone to write the code entirely for me. After messing around with it for a while, I have it almost completed (I believe, save for a few areas).
The piece that is tripping me up is the backwards word. We are required to put our output neatly into columns using prinf, but I cannot do this if I read each char at a time. So I tried setting a String backwardsWord = ""; and adding each character.
This is the piece that is tripping me up:
for(int i = upperCaseWord.length() - 1; i >= 0; i--)
{
backwardsWord += (upperCaseWord.charAt(i) + "");
}
My issue is that when I print it, the first word works properly. However, each word after that is added to the previous word.
For example: if I am printing cat, dog, and rat backwards, it shows
TAC
TACGOD
TACGODTAR
I obviously want it to read
TAC
GOD
TAR
Any help would be appreciated.
It looks like your variable backwardsWord is always appending a character without being reset between words. The simplest fix is to clear the backwardsWord just before your loop by setting it to empty string.
backwardsWord = ""; //Clear any existing characters from backwardsWord
for(int i = upperCaseWord.length() - 1; i >= 0; i--)
{
backwardsWord += (upperCaseWord.charAt(i) + "");
}
If you are building up a String one character at a time you will be using a lot of memory because Java Strings are immutable.
To do this more efficiently use a StringBuilder instead. This is made for building up characters like what you are doing. Once you have finished you can use the toString method to get the String out.
StringBuilder builder = new StringBuilder(); //Creates the String builder for storing the characters
for(int i = upperCaseWord.length() - 1; i >= 0; i--)
{
builder.append(upperCaseWord.charAt(i)); //Append the characters one at a time
}
backwardsWord = builder.toString(); //Store the finished string in your existing variable
This has the added benefit of resetting the backwardsWord each time.
Finally, since your goal is to get the String in reverse we can actually do it without a loop at all as shown in this answer
backwardsWord = new StringBuilder(upperCaseWord).reverse().toString()
This creates a new StringBuilder with the characters from upperCaseWord, reverses the characters then stores the final string in backwardsWord
Where are you declaring the String backwardsWord?
If you don't clear it between words then the memory space allocated to that string will still contain the previously added characters.
Make sure you are tossing in a backwardsWord = ""; in between words to reset it's value and that should fix your problem.
Without seeing more of your code I can't tell you exactly where to put it.
This should do the job ->
class ReverseWordsInString{
public static String reverse(String s1){
int l = s1.length();
if (l>1)
return(s1.substring(l-1) + reverse(s1.substring(0,l-1)));
else
return(s1.substring(0));
}
public static void main(String[] args){
String st = "Cat Dog Rat";
String r = "";
for (String word : st.split(" "))
r += " "+ reverse(word.toUpperCase());
System.out.println("Reversed words in the given string: "+r.trim());
}
}
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.
I'm trying to make a piece of code that will yell out anything I input.
So the command is 'yell'
I want to be able to type 'yell (whatever i want here)' and it will yell it out. I've managed to get this working with a help of a friend. But for some reason it will only yell the first word that's been output. So I can't type a sentence because it will only say the first word of a sentence.
Here's the piece of code, I hope you can help.
case "npcyell":
for (NPC n : World.getNPCs()) {
if (n != null && Utils.getDistance(player, n) < 9) {
String sentence = "";
for (int i = 1; i < cmd.length; i++) {
sentence = sentence + " " + cmd[i];
}
n.setNextForceTalk(new ForceTalk("[Alert] "
+ Utils.getFormatedMessage(sentence)));
}
}
return true;
Well I did something similar a while ago. You said that you wanted to be able to say "yell(text)" and have it output whatever the text was. I have a different way of implementing it than you do, but the general result is the same, but it can be adapted to however you are using it in this context. This is also assuming that you are running this program as a console project only. if not change the scanner with whatever you are using to input text into and replace the text assignment to text = textInputArea.getText().toString(); and change the output statement to System.out.println(text.getText().toString().substring(6,text.getText().toString().length() - 1));
Scanner s = new Scanner(System.in);
String text = s.nextLine();
if (text.startsWith("yell(") && text.endsWith(")")){
System.out.println(text.substring(6,text.length() - 1));
}
I hope this works for you. And I honestly hope that this is adaptable towards the program you are making.