I need help understanding java code - java

I am looking over a friend's code and I'm in a java 2 class. What is the difference between system.out.format and system.out.println? Also, can I get a quick description/website that can explain what %-26,25s or %-10,10s, etc does in this project? Finally, with j.getxxx, what does the j. do in this project? Or, is there a site explaining it better? Thanks for any help
for(int i=0; i<inventory.size(); i++){
Product j = inventory.get(i);
System.out.format("%-26.25s",j.getName());
System.out.format("%-10.10s", j.getInventoryCode());
System.out.format("%-6s", j.getType());
int avgRating = j.getAvgUserRating();
String stars = "";
int k = 0;
while (k<avgRating){
stars= stars +"*";
k++;
}
System.out.format("%-7s", stars);
System.out.format("%6d", j.getUserRatingCount());
System.out.format("%7d", j.getQuantity());
System.out.format("%7.2f", j.getPrice());
System.out.println();
}

System.out.println simply prints out the string with no formatting. System.out.format allows for additional formatting before output, such a padding or decimal precision.
Documentation
The %-6s is him formatting the output with padding.
j. indicates that the method that follows is a member of the object j

System.out.println writes to the stdout(console) and the System.out.format returns a String object.
Which to use depends on the sole purpose. If you want to display the string in the stdout (console), then use the first. If you want to get a handle to the formatted string to use further in the code, then use the second.
Product j = inventory.get(i);
here j is reference variable of Product class. At the time of creating the object you are assigning the reference of that object to reference variable so that later you can call the class method with the help of reference variable. As in your code you are using this for calling getName() method like
j.getName();

Related

I cannot print value of converted string

I want to reverse a string. I know there are some other methods to do it but I wanted to do in a different way. There is no error but no output when I run my code. I dont understand why "String.valueOf(word.charAt(i)" doesnt return a value? Am I missing something?
String word = "myword";
for (int i = word.length(); i <= 0; i--) {
System.out.print(String.valueOf(word.charAt(i)));
}
The first value of i is out of index. And I also fixed your code. Check below:
String word = "myword";
for(int i=word.length()-1;i>=0;i--){
System.out.print(String.valueOf(word.charAt(i)));}
Just for providing another slightly different solution:
You can use a StringBuilder to reverse a String using its method reverse().
If you have a String, you can use it to initialize the StringBuilder with it and directly reverse it.
This example additionally uses an enhanced for-loop, which always goes through all of the elements. Using that, you can get rid of checking the length of a String and you won't have to use an int i for iterating.
For your requirements, this is a suitable option because you want to reverse the whole String.
String word = "myword";
for (char c : new StringBuilder(word).reverse().toString().toCharArray()) {
System.out.println(c);
}
Note that you can use the reverse() method for printing the reversed word in one line just doing
System.out.println(new StringBuilder(word).reverse().toString());
Your code has 2 issues.
i should be initialized with word.length()-1. Other wise you will get StringIndexOutOfBoundsException
for loop condition should be >= 0.
Below is the corrected code.
String word = "myword";
for(int i=word.length()-1;i>=0;i--) {
System.out.print(word.charAt(i));
}

java I thought strings were immutable

I was always told strings in java are immutable, unless your going to use the string builder class or string writter class.
Take a look at this practice question I found online,
Given a string and a non-negative int n, return a larger string that is n copies of the original string.
stringTimes("Hi", 2) → "HiHi"
stringTimes("Hi", 3) → "HiHiHi"
stringTimes("Hi", 1) → "Hi"
and the solution came out to be
Solution:
public String stringTimes(String str, int n) {
String result = "";
for (int i=0; i<n; i++) {
result = result + str; // could use += here
}
return result;
}
As you see in the solution our 3rd line assigns the string , then we change it in our for loop. This makes no sense to me! (I answered the question in another nooby way ) Once I saw this solution I knew I had to ask you guys.
Thoughts? I know im not that great at programming but I haven't seen this type of example here before, so I thought I'd share.
The trick to understanding what's going on is the line below:
result = result + str;
or its equivalent
result += str;
Java compiler performs a trick on this syntax - behind the scene, it generates the following code:
result = result.concat(str);
Variable result participates in this expression twice - once as the original string on which concat method is called, and once as the target of an assignment. The assignment does not mutate the original string, it replaces the entire String object with a new immutable one provided by concat.
Perhaps it would be easier to see if we introduce an additional String variable into the code:
String temp = result.concat(str);
result = temp;
Once the first line has executed, you have two String objects - temp, which is "HiHi", and result, which is still "Hi". When the second line is executed, result gets replaced with temp, acquiring a new value of "HiHi".
If you use Eclipse, you could make a breakpoint and run it step by step. You will find the id (find it in "Variables" View) of "result" changed every time after java did
result = result + str;
On the other hand, if you use StringBuffer like
StringBuffer result = new StringBuffer("");
for(int i = 0; i < n; i++){
result.append(str);
}
the id of result will not change.
String objects are indeed immutable. result is not a String, it is a reference to a String object. In each iteration, a new String object is created and assigned to the same reference. The old object with no reference is eventually destroyed by a garbage collector. For a simple example like this, it is a possible solution. However, creating a new String object in each iteration in a real-world application is not a smart idea.

Error in swapping characters in stringbuffer object

i am trying to sort a string in the alphabetical order, however i am facing an error in the line :
sb.charAt(j)=sb.charAt(j+1);
where the compiler shows an error as expected variable; found value
the rest of the code is as follows :
import java.util.Scanner;
class a
{
public static void main(String[] agrs)
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
StringBuffer sb = new StringBuffer();
sb.append(s);
for(int i = 0; i< s.length(); i++)
{
for(int j = 0; j<s.length(); j++)
{
if(s.charAt(j)>s.charAt(j+1)){
char temp = s.charAt(j);
sb.charAt(j)=sb.charAt(j+1);
sb.charAt(j+1)=temp;
}
}
}}}
kindly help me out as i'm a beginner and i cannot figure out why this issue is occurring , thank you .
This looks like a homework assignment where the goal is to sort the characters of a text being entered, so if you enter gfedbca the result should be abcdefg.
You already got a comment telling you what the problem is: StringBuffer#charAt() is not returning a reference to StringBuffer's internal array that you can change the value of. Dependent on the actual assignment you can call StringBuffers setCharAt method or you can go another approach by converting the text to sort to a char array and do the sorting in there. There are actually helper-classes in the JVM, that do that for you, have a look e.g. at the class java.util.Arrays
As already answered by many, the issue is in charAt(index) you are using, as this returns the character at the given index rather than setting a char at the index position.
My answer is to divert your approach of sorting. For simpler solutions, where smaller data sets (like your problem) are used, you should use the predefined sorting algorithms, like Insertion Sort
You may get help for the algo from here: http://www.geeksforgeeks.org/insertion-sort/
StringBuffer's charAt returns just the value of the char at the index, if you want to swap two chars you need to use setter for that, so you possible want to do somtehing like:
for(int j = 0; j < s.length() - 1; j++) {
if(s.charAt(j) > s.charAt(j + 1)) {
char temp = s.charAt(j);
sb.setCharAt(j, sb.charAt(j + 1));
sb.setCharAt(j + 1, temp);
}
}
This method can only return values and can not set values, I guess you might want to use this method:
setCharAt()
It can meet your requirement

Does str.length() takes o(n)? [duplicate]

I've been told that code such as:
for (int i = 0; i < x.length(); i++) {
// blah
}
is actually O(n^2) because of the repeated calls to x.length(). Instead I should use:
int l = x.length();
for (int i = 0; i < l; i++) {
// blah
}
Is this true? Is string length stored as a private integer attribute of the String class? Or does String.length() really walk the whole string just to determine its length?
No, the length of a java string is O(1) because java's string class stores the length as a field.
The advice you've received is true of C, amongst other languages, but not java. C's strlen walks the char array looking for the end-of-string character. Joel's talked about it on the podcast, but in the context of C.
Contrary to what has been said so far, there is no guarantee that String.length() is a constant time operation in the number of characters contained in the string. Neither the javadocs for the String class nor the Java Language Specification require String.length to be a constant time operation.
However, in Sun's implementation String.length() is a constant time operation. Ultimately, it's hard to imagine why any implementation would have a non-constant time implementation for this method.
String stores the length in a separate variable. Since string is immutable, the length will never change.
It will need to calculate the length only once when it is created, which happens when memory is allocated for it.
Hence its O(1)
In the event you didn't know you could write it this way:
for (int i = 0, l = x.length(); i < l; i++) {
// Blah
}
It's just slightly cleaner since l's scope is smaller.
You should be aware that the length() method returns the number of UTF-16 code points, which is not necessarily the same as the number of characters in all cases.
OK, the chances of that actually affecting you are pretty slim, but there's no harm in knowing it.
I don't know how well the link will translate, but see the source of String#length. In short, #length() has O(1) complexity because it's just returning a field. This is one of the many advantages of immutable strings.
No worries even though we are calling length() as a method on x.length(), Actually length is stored as a field/property in String class and this field/property returned by length() method whenever we call " x.length()".
Check out this image link or below code snippet of length() method defined in String class-
ImageLink
public int length() {
return value.length >> coder();
}
length() method returns the length property which is already stored in String class.
According to this, the length is a field of the String object.

How to align print statements on the same line with varying lengths in Java?

I have information from a text file that I have read in through 3 parallel arrays. There's one for names, id numbers, and gpa. However because the name lengths vary the id numbers and gpa are all shifted differently. Is there a way to align all the id numbers so they begin on the same part of the line and the same for the gpa's despite different name lengths? I used a for loop for all of it and my code looks like this:
{
int lineLength;
lineLength = lineFinder(names);
System.out.printf("NAME ID GPA\n");
System.out.println();
for(int i = 0; i < lineLength; i++)
{
System.out.printf("%s %14d %14.2f", names[i] , id[i], gpa[i]);
System.out.println();
}
}
Any suggestions would be appreciated :)
Take a look at the JavaDocs for the Formatter. The printf method is ultimately using that class to format the output for you.
In your case, it sounds like you want to left-justify the ID values. By default, as you've probably seen, everything is always right-justified, and as Ooga said in the comments, a negative number in the formatting will left-justify.
However I believe part of the problem is that you're not specifying the length of the name field. It'll shrink or expand based on the length of the string provided, which I'm guessing is why you're saying your output looks all over the place. I would specify a length in the format (something reasonable, such as 30 perhaps).
So in your case, I think you will want to do something like this:
{
int lineLength;
lineLength = lineFinder(names);
System.out.printf("%30s %14s %14s", "NAME", "ID", "GPA");
System.out.println();
for(int i = 0; i < lineLength; i++)
{
System.out.printf("%30s %-14d %14.2f", names[i] , id[i], gpa[i]);
System.out.println();
}
}
Also note I've added similar formatting to your field headers that roughly match the lengths of the data. That way everything appears consistently and tabular. You can of course play with the values as you need.
Hope that helps.

Categories