This question already has answers here:
Output in a table format in Java's System.out
(8 answers)
Closed 5 years ago.
for (int k = 0; k < 7; k++){
System.out.println("Vak/project:\t" + vakNamen[x] + "\t\t"
+ "Cijfer: " + vakCijfers[x] + "\t" + "Behaalde punten: "
+ vakPunten[x]);
x++;
}
EDIT: the assignment wants to use system.out.printf so I will have a look at that, ty for the hint
and the system.out.format seems interesting I never heard of that, will look into it
Ok so my question is in this for loop I print 3 different arrays and I want them to be in a table so I used \t, but the problem u get with this is that if the "vakNamen" which is the name of the subject is LONGER than another then the tabs will go further and create this ugly table:
https://gyazo.com/398953f233f3562eecfa6c483ec73e62
I dont really know how to ask this question but I think I should ask how to make sure \t is independant from the previous lines?
You can use System.out.format()
Example:
String project = "myProjectName";
String firstName = "firstName";
String lastName = "lastName";
System.out.format("%-20s%-15s%-15s", project, firstName, lastName);
Above code snippet should print the following formatted output:
myProjectName firstName lastName
Edit:
I found this library which simplifies such kind of formatting. It is also available on Maven.
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
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm learning the basics of Java, and wanted to practice something. So found a page of some programing problems and I get stuck at this problem:
2) Write a program that asks the user for her name and greets her with her name.
3) Modify the previous program such that only the users Alice and Bob are greeted with their names.
I've made well the 2nd but I have trouble with 3rd one.
System.out.pritnln("Please enter your name ");
Scanner input = user new Scanner(System.in);
String user_name;
user _name = input.next();
if(user_name == "Alice"){
System.out.println("Hello " + user_name + ", sweet name.");
if(user_name=="Bob"){
System.out.println("Hello " + user_name + ", sweet name.");
}
}
Don't use == for string comparison in Java unless you're really sure that is what you are doing. Use:
user_name.equals("Bob")
I actually use equalsIgnoreCase() as my standard approach unless I'm sure it should be case-sensitive.
This question already has answers here:
Difference between setText() and append()
(5 answers)
Closed 6 years ago.
For a highschool project I created a for loop that displays the 5 songs I initialised. I put it under the a button called btnInitializeActionPerformed so when the initialized button is pressed, it displays the songs, however it only displays the last song, what am I doing wrong?
Here is the loop
Collections.addAll (strSongArtist, "Dont Stop Believing", "this", "hello", "Think", "No");
for (int i = 0; i < strSongArtist.size(); i++) {
String valueContent = strSongArtist.get(i);
txtOutput.setText( valueContent);
}
when I display strSongArtist like this in side the for loop:
System.out.println(strSongArtist.get(i));
Btw my teacher gave an example of outputing the code like this:
txtOutput.setText( strSongArtist.get(rn.nextInt(strSongArtist.size())).toString());
but I have no idea how to use this either?
Your problem is that you are calling txtOutout.setText() during each loop iteration.
So, even if textOutput is some label/panel whatsoever that would be able to display more than string ... what you are doing is that you are telling it to only display that one string that you are passing to it.
Meaning: you have a loop that produces 5 individual strings. If you want those 5 strings to show up together, you have to build something that contains all those 5 individual strings.
You can either do that by collecting the results of your "get(i)" calls using a StringBuffer; or you call setTest() with the result of "getText() + "\n" + get(i)" ...
Every time the loop runs it is setting the text of txtOutput to the value of the valueContent, so it will display the last artist at the end of the loop. You should at least create a string and append each artist to it and set the text at the end of the loop
String artists = "";
for (int i = 0; i < strSongArtist.size(); i++) {
artists += strSongArtist.get(i) + ", ";
}
txtOutput.setText( artists );
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
After some awesome help yesterday on this site, I am back with another question. I have my input/output equation the way I want it but need help rounding the decimal off to the hundredths position. The way it is set up now the output of pounds seems to just repeat the answer. I have been inputting 10.2 as the weight in kilograms and the answer I keep receiving in pounds is 22.4422.44. I know it is something with the String.format I am using but after messing with it for quite a while I can't seem to figure it out. I know it is something silly but I have been working on this for a while now and I think my brain may be mush. Below is my program.
//This program converts kilograms to pounds using input/output dialog boxes.
import javax.swing.*;
public class SNHU2_3 {
public static void main (String[] args){
String inputStr;
String outputStr;
double pounds;
double kilograms;
inputStr = JOptionPane.showInputDialog("Enter weight in kilograms");
kilograms = Double.parseDouble(inputStr);
outputStr = ("Kilograms = " + kilograms) + "\n" + ("Pounds = " + (kilograms * 2.2)) + String.format("%.2f", (kilograms * 2.2));
JOptionPane.showMessageDialog(null, outputStr, "Weight Conversion", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
You can just simply use:
kilograms = Double.parseDouble(inputStr);
Math.round(kilograms);
I suggest
outputStr = String.format("Kilograms = %.2f \n Pounds = %.2f", kilograms, (kilograms * 2.2));
I would first of all suggest that you should thoroughly research your question before posting it. There are many related question that are already asked in this forum. Also study a little bit more about String.format.
Next to explain your problem:
outputStr = ("Kilograms = " + kilograms) + "\n" + ("Pounds = " + (kilograms * 2.2)) + String.format("%.2f", (kilograms * 2.2));
What this statement does is it concatenates different strings that you have placed between '+' signs. So we start from the left where your have the String "Kilograms = " so first it is taken then we have kilogram this is basically a double and in your example stores the value 10.2. Now the String becomes "Kilograms = 10.2". After that you have the string "\n". So the string becomes "Kilograms = 10.2\n". Then you have "Pounds = ", so on concatenation the string becomes "Kilograms = 10.2\nPounds = ". After that it hits the expression (kilograms * 2.2) Which in your case is 10.2*2.2 which computes to 22.44 So after concatenation the string becomes "Kilograms = 10.2\nPounds = 22.44". After that it hits String.format("%.2f", (kilograms * 2.2)). The return value of this expression in your case is '"22.44"'. So now the finally concatenated string is "Kilograms = 10.2\nPounds = 22.4422.44" which is finally stored in outputStr. And this is exactly what you get.
I believe that I have been able to explain you what is the problem. SO REMEMBER - you should thoroughly research your question before posting it.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
public String toString() {
String info = "";
String courseInfo = this.getCourseInfo();
if("".equals(courseInfo)) {
courseInfo = "None";
}
info += "--------------------------------------------------\n";
info += "Student Name: " + this.name + "\n";
info += "Student Address: " + this.address + "\n";
info += "Student #: " + this.studentNumber + "\n";
info += "Student Login ID: " + this.loginID + "\n";
info += "Courses taken:" + "\n";
info += courseInfo + "\n";
info += "GPA: " + this.getGPA() + "\n";
info += "--------------------------------------------------\n";
return info;
}
I was told that this is a bad toString method because it should be to output diagnostic information on one line, or a single literal value if that makes sense. I really don't understand. Should I just print all the instance variables and let the user decide what it is?
The problem is that this toString will produce a big block of code. Lets say it is called Student. If you wanted to log:
Student X linked to student Y because of Z.
Then the X and Y are going to become massive, and the whole line gets split out and unreadable.
You might have a "toFullDescription" or something method that looks like your current toString, but the toString should just have a few meaningful elements, probably just the name and Id inside curly braces.
You put in toString any information that you consider relevant about the object. It will be of great importance for debugging purposes, like log files or debugging sessions in your IDE. Also, information in toString objects written to logs are useful for forensics when trying to identify problems in the application.
It is likely, though, that you will probably try to avoid putting sensitive information there (i.e. passwords, credit card numbers, etc).
I like to use the Apache Commons EqualsBuilder class for this kind of things. It has different formatting styles for your toString to make your life simpler.
For instance:
#Override
public String toString(){
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("orderId", this.orderId)
.append("status", this.status)
.append("type",this.type)
.append("items", this.items)
.toString();
}