I'm learning Java and have spent way too much time on this stupid little problem. I'm trying to dynamically pad the left side of my string outputs with spaces, so all values displayed will be padded left. The problem is, I don't know the length of the values until a user enters them.
Here's an example of what I'm trying to do. nLongestString is the length of the longest string I'm displaying, and strValue is the value of the string itself. This doesn't work dynamically at all. If I hardcode a value for nLongestString it works, but I can't do that since I don't always know how long the strings will be.
System.out.printf("%"+nLongestString+"s", strValue + ": ");
Output should look like:
thisisalongstring:
longstring:
short:
I'm not seeing your problem, the following works fine for me. (Java 7)
Edit: Have you checked the value of nLongestString? I'm guessing it doesn't get set to what you think it does.
String[] arr = { "foo", "bar", "foobar" };
int max = 0;
for( String s : arr ) {
if( s.length() > max ) {
max = s.length();
}
}
for( String s : arr ) {
System.out.printf( ">%" + max + "s<%n", s );
}
Random random = new Random( System.currentTimeMillis() );
// just to settle the question of whether it works when
// Java can't know ahead of time what the value will be
max = random.nextInt( 10 ) + 6;
for( String s : arr ) {
System.out.printf( ">%" + max + "s<%n", s );
}
}
Output:
> foo<
> bar<
>foobar<
// the following varies, of course
> foo<
> bar<
> foobar<
If you already have your data then you just need to find max length of your words and after that print them. Here is code sample
// lets say you have your data in List of strings
List<String> words = new ArrayList<>();
words.add("thisisalongstring");
words.add("longstring");
words.add("short");
// lets find max length
int nLongestString = -1;
for (String s : words)
if (s.length() > nLongestString)
nLongestString = s.length();
String format = "%"+nLongestString+"s:\n";// notice that I added `:` in format so
// you don't have to concatenate it in
// printf argument
//now lets print your data
for (String s:words)
System.out.printf(format,s);
Output:
thisisalongstring:
longstring:
short:
Related
I have a task which involves me creating a program that reads text from a text file, and from that produces a word count, and lists the occurrence of each word used in the file. I managed to remove punctuation from the word count but I'm really stumped on this:
I want java to see this string "hello-funny-world" as 3 separate strings and store them in my array list, this is what I have so far , with this section of code I having issues , I just get "hello funny world" seen as one string:
while (reader.hasNext()){
String nextword2 = reader.next();
String nextWord3 = nextword2.replaceAll("[^a-zA-Z0-9'-]", "");
String nextWord = nextWord3.replace("-", " ");
int apcount = 0;
for (int i = 0; i < nextWord.length(); i++){
if (nextWord.charAt(i)== 39){
apcount++;
}
}
int i = nextWord.length() - apcount;
if (wordlist.contains(nextWord)){
int index = wordlist.indexOf(nextWord);
count.set(index, count.get(index) + 1);
}
else{
wordlist.add(nextWord);
count.add(1);
if (i / 2 * 2 == i){
wordlisteven.add(nextWord);
}
else{
wordlistodd.add(nextWord);
}
}
This can work for you ....
List<String> items = Arrays.asList("hello-funny-world".split("-"));
By considering that you are using the separator as '-'
I would suggest you to use simple split() of java
String name="this-is-string";
String arr[]=name.split("-");
System.out.println("Here " +arr.length);
Also you will be able to iterate through this array using for() loop
Hope this helps.
so I'm pretty new at Java and StackOverflow (That's what they all say) and I am stuck at the given problem:
My method is given a String e.g.: "[ 25 , 25 , 125 , 125]". Now the method should return an Array of integers representation of the String provided, that is: it should return
[25,25,125,125].
Here is a segment of my method. Note: input is the String provided
if(input.charAt(index) == '['){
index++;
int start = index;
while(index <= input.length() && input.charAt(index) != ']'){
index++;
}
String[] arrayStr = input.substring(start, index).split(",");
int[] arrayInt = new int[4];
for (int i = 0; i < arrayStr.length; i++){
arrayInt[i] = Integer.parseInt(arrayStr[i]);
}
return arrayInt;
My code works if input is: "[25,25,125,125]" (If there are no spaces between the numbers).
However if there are spaces between the numbers then my code doesn't work and I understand why, but I am struggling to find a way to solve this problem. Any help will be appreciated.
Spaces will fail with Integer.parseInt(arrayStr[i]) (e.g. the string "25 " is not a valid number as it contains a space. (parseInt will throw an exception in such cases.)
However you can solve it quickly by trimming your array elements:
Integer.parseInt(arrayStr[i].trim())
trim() returns a copy of the string without leading/trailing white space
You can replace the space with empty in the string
input=input.replace(" ","")
You can
remove [ and ] and all spaces
split on , to get all tokens
iterate over all tokens
parse string number to int
add parsed int to result array
So your code can look like
String data = "[ 25 , 25 , 125 , 125]";
String[] tokens = data.replaceAll("\\[|\\]|\\s", "").split(",");
int[] array = new int[tokens.length];
for (int i=0; i<tokens.length; i++){
array[i]=Integer.parseInt(tokens[i]);
}
Or if you have Java 8 you can use streams like
int[] array = Stream.of(data.replaceAll("\\[|\\]|\\s", "").split(","))
.mapToInt(number -> Integer.parseInt(number))
.toArray();
I'm trying to ensure text does not appear outside of the window as the window size cannot be changed.
The image above shows what happens when the string of the order numbers exceeds the length of the window. I'm trying to ensure that when the length of the string of order numbers reaches a certain length, I use regex to make a new line for the next orders.
private String listOfOrders( Map<String, List<Integer> > map, String key )
{
String res = "";
if ( map.containsKey( key ))
{
List<Integer> orders = map.get(key);
for ( Integer i : orders )
{
res += " " + i + ",";
}
} else {
res = "-No key-";
}
return res;
}
}
This is the code to display the text, it works by forming the string res and filling it with the order numbers from the array list.
I found, through researching, a cool little piece of code which replaces a string every set amount of characters with itself plus a new line.
if(res.length() >= W-10)
{
res = res.replaceAll("(.{20})", "$1\n");
}
else
{
res += " " + i + ",";
}
But this has no effect at all. And I also realised that this code can not tell how long each line is because I'm using length to determine the length of each line and not how long each line is between each "\n".
My question is, how do I go about using regex to ensure each line in the string is a certain number of characters long? As my attempt does not work. The above just provides context as to why I want lines in a string a certain legnth.
Thanks!
This question already has answers here:
Wrap the string after a number of characters word-wise in Java
(6 answers)
Closed 8 years ago.
Let us say I have a long string
String s1="This is my world. This has to be broken."
I am breaking the above string at a fixed interval of string length let's say when it's 10.
So the output I get after breaking is
This is my
world. Thi
s has to b
e broken.
Where as I want that the string should contain complete words and not broken words.
Just like this I want the output to be
This is my
world.
This has
to be
broken.
How can I achieve the above output.
Try this:
String line = "element1 element2 element3";
String [] separatedList = line.split("\\s+");
for (String stringSeparated : separatedList) {
System.out.println(stringSeparated);
}
I don't exactly understand the logic of the program, but you can use String.indexOf(' ') or something like that to know where exactly are the spaces of your string. check here http://www.tutorialspoint.com/java/java_string_indexof.htm and read the documentation http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)
Something along these lines?
int limit = 10;
// Tokenize words
String s1="This is my world. This has to be broken.";
final String[] words = s1.split( " " );
// Apply word-wrapping
final StringBuilder sb = new StringBuilder();
for( String word : words ) {
if( sb.length() + word.length() > limit ) {
// Next word wraps
System.out.println( sb );
sb.setLength( 0 );
}
else {
// Otherwise add to current line
if( sb.length() > 0 ) sb.append( ' ' );
}
sb.append( word );
}
// Handle final line
System.out.println( sb );
So I'm still shaky on how basic java works, and here is a method I wrote but don't fully understand how it works anyone care to explain?
It's supposed to take a value of s in and return it in its reverse order.
Edit: Mainly the for loop is what is confusing me.
So say I input "12345" I would want my output to be "54321"
Public string reverse(String s){
String r = "";
for(int i=0; i<s.length(); i++){
r = s.charAt(i) + r;
}
return r;
}
We do a for loop to the last index of String a , add tha carater of index i to the String s , add here is a concatenation :
Example
String z="hello";
String x="world";
==> x+z="world hello" #different to z+x ="hello world"
for your case :
String s="";
String a="1234";
s=a.charAt(0)+s ==> s= "1" + "" = "1" ( + : concatenation )
s=a.charAt(1)+s ==> s='2'+"1" = "21" ( + : concatenation )
s=a.charAt(2)+s ==> s='3'+"21" = "321" ( + : concatenation )
s=a.charAt(3)+s ==> s='3'+"321" = "4321" ( + : concatenation )
etc..
public String reverse(String s){
String r = ""; //this is the ouput , initialized to " "
for(int i=0; i<s.length(); i++){
r = s.charAt(i) + r; //add to String r , the caracter of index i
}
return r;
}
What this code does is the following
Create a new variable r="";
then looping for the string in input lenght it adds at the beginning of r the current character of the loop.
i=0) r="1"
i=1) r="21"
i=2) r="321"
i=3) r="4321"
i=4) r="54321"
When you enter the loop you are having empty string in r.
Now r=""
In 1st iteration, you are taking first character (i=0) and appending r to it.
r = "1" + "";
Now r=1
In 2nd iteration, you are taking second character (i=1) and appending r to it
r = "2" + "1";
Now r=21
You can trace execution on a paper like this, then you will easily understand what is happening.
What the method is doing is taking the each character from the string s and putting it at the front of the new string r. Renaming the variables may help illustrate this.
public String reverse(String s){
String alreadyReversed = "";
for(int i=0; i<s.length(); i++){
//perform the following until count i is as long as string s
char thisCharacterInTheString = s.charAt(i); // for i==0 returns first
// character in passed String
alreadyReversed = thisCharacterInTheString + alreadyReversed;
}
return alreadyReversed;
}
So in the first iteration of the for loop alreadyReversed equals 1 + itself (an empty string).
In the second iteration alreadyReversed equals 2 + itself (1).
Then 3 + itself (21).
Then 4 + 321.
Then 5 + 4321.
GO back to your problem statement (take an input string and produce an output string in reverse order). Then consider how you would do this (not how to write Java code to do this).
You would probably come up with two alternatives:
Starting at the back of the input string, get one character at a time and form a new string (thus reversing its order).
Starting at the front of the string, get a character. Then for each next character, put it in front of all the characters you have created so far.
Your pseudo code results might be like the following
Option 1
let l = the length of the input string
set the output string to ""
while l > 0
add the "lth" character of the input string to the output string
subtract 1 from l
Option 2 left as an exercise for the questioner.
Then you would consider how to write Java to handle your algorithm. You will find that there are several ways to get the "lth" character of a string. First, in Java a string of length l has characters in position 0 through l-1. You can use string.charAt(loc) or string.substring(loc,loc+1) to get the character at position loc