This question already has answers here:
Simple way to repeat a string
(32 answers)
Closed 9 years ago.
I need to print a specific set of lines without manually typing them.
I want my output to be like this
"|Word_________|"
Is there a code which allows me to set my own amount of "_"?
One may use a format, which then padds (left or right) with spaces.
System.out.printf("|%-30s|%5s|%n", "Aa", "1");
System.out.printf("|%-30s|%5s|%n", "Bbbb", "222");
String s = String.format("|%-30s|%5s|%n", "Aa", "1").replace(' ', '_');
String fortyBlanks = String.format("%40s", "");
You can print a _ with:
System.out.print("_");
If you want more, do it multiple times (inefficient), or build up a string containing multiple and print it. You may want to look at StringBuilder.
No direct way. But with looping you can do
String s = "";
for (int i = 0; i < 10; i++) { // sample 10
s = s + "_";
}
System.out.println(s);
Still it is not a bestway to use + in looping. Best way is
StringBuilder b = new StringBuilder();
for (int i = 0; i < 10; i++) { //sample 10
b.append("_");
}
System.out.println(b.toString());
Use a for loop.
Here's the link to the java documnentation for a for loop: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
int amountOf_ = 10;
System.out.println("|" + StringUtils.rightPad("Word", amountOf_, "_") + "|");
}
}
Related
This question already has answers here:
How to remove last comma and space in array? Java [duplicate]
(3 answers)
Closed 5 months ago.
Hei
I'm a beginner in Java and I have homework and I spent all day trying to figure out the solution and I couldn't. I'm so frustrated
Can someone help me?
Converting from any table in Int [] to string for eksmpel : int [] a = { 1,2,3} to String s = [1,2,3]
I didn't know how to put the comma, it always shows a trailing comma at the end or at the beginning a trailing comma as well as parentheses.
This is my code :
public class Test11 {
public static String til(int[] tabell) {
String str = "";
String na1 = "[";
String na2 = "]";
String na3 = ",";
String str3 = "";
for (int i = 0; i < tabell.length; i++) {
str += "," + tabell[i];
}
return str;
}
public static void main(String[] args) {
int[] tab = { 1, 2, 3 };
System.out.println(til(tab));
}
}
You need to handle the first iteration through your loop as a special case, because you don't want to add a comma the first time around. There's something you can use to know that you're in the first iteration...the fact that the string you're building is empty because you haven't added anything to it yet.
This makes extra good sense because if the string is empty, then it doesn't yet contain a term that you want to separate from the next term with a comma.
Here's how you do this:
String str = "";
for (int i = 0; i < tabell.length; i++) {
if (str.length() > 0)
str += ",";
str += tabell[i];
}
Use a variable to keep track of whether or not you're on the first iteration. If you are, don't put a comma before it.
boolean isFirst = true;
for (int i = 0; i < tabell.length; i++) {
if (!isFirst) {
str += ",";
}
isFirst = false;
str += tabell[i];
}
This question already has answers here:
How to print a table of information in Java
(6 answers)
Closed 2 years ago.
Is there a way to print an ArrayList like a Excel spreadsheet ?
My code is this:
private static void printList() {
for (int i = 0; i < matrizCuadrada.size(); i++) {
System.out.print(fillWithSpaces(matrizCuadrada.get(i).getValor()));;
}
}
private static String fillWithSpaces(String cadena) {
int cantidadEspacios = 9 - cadena.length();
for (int i = 0; i < cantidadEspacios; i++) {
cadena += " ";
}
return cadena;
}
To print a one-dimensional data structure like ArrayList in two dimensions you are going to have to set a fixed line size. This is actually a very similar problem as loading pixels stored in linearly stacked memory to a two-dimensional image. Check the linked article for more details about this problem.
You need nested loops to achieve this behaviour, which you already have (fillWithSpaces() (containing a loop) is called from inside another loop). So, change fillWithSpaces() to something like this:
private static String fillWithSpaces(String cadena) {
String line = "";
for (int i = 0; i < cadena.length(); i++) {
line += cadena.charAt(i);
line += " ";
}
return line;
}
This code can also be simplified using a utility called StringJoiner to join strings and characters with a delimiter:
private static String fillWithSpaces(String cadena) {
StringJoiner joiner = new StringJoiner(" ");
for (int i = 0; i < cadena.length(); i++) {
joiner.add(cadena.charAt(i));
}
return joiner.toString();
}
Also, you need to jump to a new line at the end of the outer loop. This can be done by changing System.out.print() to System.out.println(), which will automatically output a new line.
Check this article by Daniel Shiffman for an extensive explanation of the same problem in a different context (under Pixels, pixels, and more pixels): https://processing.org/tutorials/pixels/
I looking for a way to split my chunk of string every 10 words.
I am working with the below code.
My input will be a long string.
Ex: this is an example file that can be used as a reference for this program, i want this line to be split (newline) by every 10 words each.
private void jButton27ActionPerformed(java.awt.event.ActionEvent evt) {
String[] names = jTextArea13.getText().split("\\n");
var S = names.Split().ToList();
for (int k = 0; k < S.Count; k++) {
nam.add(S[k]);
if ((k%10)==0) {
nam.add("\r\n");
}
}
jTextArea14.setText(nam);
output:
this is an example file that can be used as
a reference for this program, i want this line to
be split (newline) by every 10 words each.
Any help is appreciated.
I am looking for a way to split my chunk of string every 10 words
A regex with a non-capturing group is a more concise way of achieving that:
str = str.replaceAll("((?:[^\\s]*\\s){9}[^\\s]*)\\s", "$1\n");
The 9 in the above example is just words-1, so if you want that to split every 20 words for instance, change it to 19.
That means your code could become:
jTextArea14.setText(jTextArea13.getText().replaceAll("((?:[^\\s]*\\s){9}[^\\s]*)\\s", "$1\n"));
To me, that's much more readable. Whether it's more readable in your case of course depends on whether users of your codebase are reasonably proficient in regex.
You can try this as well leveraging the java util
public static final String WHITESPACE = " ";
public static final String LINEBREAK = System.getProperty("line.separator");
public static String splitString(String text, int wordsPerLine)
{
final StringBuilder newText = new StringBuilder();
final StringTokenizer wordTokenizer = new StringTokenizer(text);
long wordCount = 1;
while (wordTokenizer.hasMoreTokens())
{
newText.append(wordTokenizer.nextToken());
if (wordTokenizer.hasMoreTokens())
{
if (wordCount++ % wordsPerLine == 0)
{
newText.append(LINEBREAK);
}
else
{
newText.append(WHITESPACE);
}
}
}
return newText.toString();
}
You were so close.
You were not appending your split words before setting it back into your text box. StringBuilder sb.append(S[k]) will add your split name to a buffer. sb.append(" ") will then add a space. Each line will be of 10 space separated names.
StringBuilder sb = new StringBuilder();
String[] names = jTextArea13.getText().split(" ");
for (int k = 0; k < S.length; k++) {
sb.append(S[k]).append(" ");
if (((k+1)%10)==0) {
sb.append("\r\n");
}
}
At last print it back to your jTextArea using:
jTextArea14.setText(sb.toString());
Just a side note, since sb is StringBuilder, you need to change it to string using toString nethod.
I cannot figure how to obtain latest 4 char of string before zeroes
String str = "41f1f3d1f10000000000000000000000000000000000"
I want: d1f1
I've tried to revert string string than do straight loop
public static boolean checklast4digit(String risposta) {
String crc = "";
risposta = reverseIt(risposta);
for (int i = 0; i < risposta.length(); i++) {
if (risposta.charAt(i) != '0') crc = Character.toString(risposta.charAt(i + 3)) + Character.toString(risposta.charAt(i + 2)) + Character.toString(risposta.charAt(i + 1)) + Character.toString(risposta.charAt(i));
}
Log.i("Crc letto: ", crc);
return true;
}
public static String reverseIt(String source) { //Inversione stringa
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--) {
dest.append(source.charAt(i));
}
return dest.toString();
}
Exception:
java.lang.StringIndexOutOfBoundsException
As mentioned in the comments, you are looping too far. If you want to access charAt(i+3) you should only loop until i < risposta.length() - 3
Also, you need to break out of your loop, once you have found your result:
for(int i=0 ;i < risposta.length() - 3 ;i++){
if(risposta.charAt(i) != '0') {
crc= Character.toString(risposta.charAt(i + 3)) + Character.toString(risposta.charAt(i+2)) + Character.toString(risposta.charAt(i+1)) + Character.toString(risposta.charAt(i));
break;
}
}
Note that this only gives you a result, if you have 4 non-zero characters before the zeros.
There are many ways to improve your code, one of which would be to just remove the trailing zeroes first, then reverse the remaining string and take the first 4 chars of it.
However, to point out errors in your code...
Take a look at the values you're using to get characters. While your loop is limited to i<risposta.length(), i+3 that you're using in the line below is not - it can go up to risposta.length()+2. If oyu want to fix the code, then change the loop condition to i+3<risposta.length().
It's not elegant and can be done better, but that would solve the immediate bug in your code.
Your IndexOutOfBoundsException is caused by:
risposta.charAt(i + 3)
risposta.charAt(i+2)
risposta.charAt(i+1)
If you take a look at your for loop:
for(int i=0 ; i < risposta.length(); i++){
}
You are iterating from index 0 to risposta.length() - 1. However because you are getting the char at i+3 when i is risposta.length() - 1 it tries to access the index risposta.length() + 2 which is out of bounds.
You ned to modify your loop so you only iterate up to risposta.length() - 3
Here you have a oneliner!
String a = new StringBuilder(new StringBuilder("41f1f3d1f10000000000000000000000000000000000".split("0")[0]).reverse().toString().substring(0, 4)).reverse().toString();
And the complete code looks like this:
package nl.testing.startingpoint;
public class Main {
public static void main(String args[]) {
String a = new StringBuilder(new StringBuilder("41f1f3d1f10000000000000000000000000000000000".split("0")[0]).reverse().toString().substring(0, 4)).reverse().toString();
System.out.println(a);
}
}
result: d1f1
Alternatively, you could strip the 0's with a replaceAll and then get the last 4 chars with a substring. That makes the code pretty simple:
public static void main(String[] args) {
String str = "41f1f3d1f10000000000000000000000000000000000";
str = str.replaceAll("0*$", "");
System.out.println(str.substring(str.length()-4));
}
First of all the StringBuilder has a reverse method, which you can use to revers a string. That would simplify the reversing quite a bit.
return new StringBuilder(source).reverse().toString();
and as the others pointed out your for loop probably causes the exception, as it iterates to long.
To remove all trailing zeros (as suggested by CptBartender) you can use regex.
risposta = risposta.replaceFirst("0+$");
Then you can reverse the string (as shown above) and get the first n characters using the substring method.
reversed.substring(0, Math.min(reversed.length(), 4));
Math.min() is used to ensure there is no error if there are less than 4 characters before the zeros.
This question already has answers here:
Splitting String to list of Integers with comma and "-"
(4 answers)
Closed 8 years ago.
The following code I have spent several hours on using multiple different strategies for extracting the integer values from the String st and getting them into their own int variables.
This is a test program, the actual assignment that I am working on requires me to build a class that will make another program ( program5 ) run correctly. The string generated by program5 could contain more than just three integers, but all will be seperated by a space. Because of the specifics of the assignment I am not allowed to use arrays, or regex because we have not covered them in class.
As of right now I can't even get it to print out all of the three integers I have in my test string. If anyone sees anything wrong with my syntax or problems with my logic please let me know!
public class test {
public static void main(String[] args){
String st = "10 9 8 7 6";
int score;
int indexCheck = 0;
String subSt;
for(int i=0; i <= st.length(); i++)
{
if(st.indexOf(' ') != -1)
{
if(st.charAt(i) == ' ')
{
subSt = st.substring(indexCheck, i);
score = Integer.parseInt(subSt);
indexCheck = st.indexOf(i);
System.out.println(score);
}
}
else
{
subSt = st.substring(st.lastIndexOf(" "));
score = Integer.parseInt(subSt);
System.out.println(score);
}
}
}
}
Use st.split(" ") to get a String[] that stores the string split by spaces, and then use Integer.parseInt(array[0]) on each index to to convert it to an int.
Example
String str = "123 456 789";
String[] numbers = str.split(" ");
int[] ints = new int[numbers.length];
for(int c = 0; c < numbers.length; c++) ints[c] = Integer.parseInt(numbers[c]);