Unable to customize String format to print column-wise features - java

I am trying to print the result of my computation into JTextArea in columns similar to table. I have three features (three columns) and I use the following String format solution that I found here but it does not align them properly. Since I don't understand "%1$5s %2$-40s %3$-20s";, kindly can someone fix it?
String format = "%1$5s %2$-40s %3$-20s";
for (int i = 0; i < 10; i++) {
String s = String.format(format, i*5, km.runningTime[i], km.DB[i]);
jtextarea.append(s+ "\n");
}

You can find the explanations in the Format String Syntax paragraph of the Formatter documentation of Oracle.
For example: %1$5s means: first argument (it starts to count at 1 and not 0), 5 is the width and s means string. In %2$-40s, the minus sign means that the result will be left-justified. I let you guess the last part.
I hope it helps.

Related

NZEC error in Hackerearth problem in java

I'm trying the solve this hacker earth problem https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/anagrams-651/description/
I have tried searching through the internet but couldn't find the ideal solution to solve my problem
This is my code:
String a = new String();
String b = new String();
a = sc.nextLine();
b = sc.nextLine();
int t = sc.nextInt();
int check = 0;
int againCheck =0;
for (int k =0; k<t; k++)
{
for (int i =0; i<a.length(); i++)
{
char ch = a.charAt(i);
for (int j =0; j<b.length(); j++)
{
check =0;
if (ch != b.charAt(j))
{
check=1;
}
}
againCheck += check;
}
}
System.out.println(againCheck*againCheck);
I expect the output to be 4, but it is showing the "NZEC" error
Can anyone help me, please?
The requirements state1 that the input is a number (N) followed by 2 x N lines. Your code is reading two strings followed by a number. It is probably throwing an InputMismatchException when it attempts to parse the 3rd line of input as a number.
Hints:
It pays to read the requirements carefully.
Read this article on CodeChef about how to debug a NZEC: https://discuss.codechef.com/t/tutorial-how-to-debug-an-nzec-error/11221. It explains techniques such as catching exceptions in your code and printing out a Java stacktrace so that you can see what is going wrong.
1 - Admittedly, the requirements are not crystal clear. But in the sample input the first line is a number.
As I've written in other answers as well, it is best to write your code like this when submitting on sites:
def myFunction():
try:
#MY LOGIC HERE
except Exception as E:
print("ERROR Occurred : {}".format(E))
This will clearly show you what error you are facing in each test case. For a site like hacker earth, that has several input problems in various test cases, this is a must.
Coming to your question, NZEC stands for : NON ZERO EXIT CODE
This could mean any and everything from input error to server earthquake.
Regardless of hacker-whatsoever.com I am going to give two useful things:
An easier algorithm, so you can code it yourself, becuase your algorithm will not work as you expect;
A Java 8+ solution with totally a different algorithm, more complex but more efficient.
SIMPLE ALGORITM
In you solution you have a tipical double for that you use to check for if every char in a is also in b. That part is good but the rest is discardable. Try to implement this:
For each character of a find the first occurence of that character in b
If there is a match, remove that character from a and b.
The number of remaining characters in both strings is the number of deletes you have to perform to them to transform them to strings that have the same characters, aka anagrams. So, return the sum of the lenght of a and b.
NOTE: It is important that you keep track of what you already encountered: with your approach you would have counted the same character several times!
As you can see it's just pseudo code, of a naive algorithm. It's just to give you a hint to help you with your studying. In fact this algorithm has a max complexity of O(n^2) (because of the nested loop), which is generally bad. Now, a better solution.
BETTER SOLUTION
My algorithm is just O(n). It works this way:
I build a map. (If you don't know what is it, to put it simple it's a data structure to store couples "key-value".) In this case the keys are characters, and the values are integer counters binded to the respective character.
Everytime a character is found in a its counter increases by 1;
Everytime a character is found in b its counter decreases by 1;
Now every counter represents the diffences between number of times its character is present in a and b. So, the sum of the absolute values of the counters is the solution!
To implement it actually add an entry to map whenever I find a character for the first time, instead of pre-costructing a map with the whole alphabet. I also abused with lambda expressions, so to give you a very different sight.
Here's the code:
import java.util.HashMap;
public class HackerEarthProblemSolver {
private static final String a = //your input string
b = //your input string
static int sum = 0; //the result, must be static because lambda
public static void main (String[] args){
HashMap<Character,Integer> map = new HashMap<>(); //creating the map
for (char c: a.toCharArray()){ //for each character in a
map.computeIfPresent(c, (k,i) -> i+1); //+1 to its counter
map.computeIfAbsent(c , k -> 1); //initialize its counter to 1 (0+1)
}
for (char c: b.toCharArray()){ //for each character in b
map.computeIfPresent(c, (k,i) -> i-1); //-1 to its counter
map.computeIfAbsent(c , k -> -1); //initialize its counter to -1 (0-1)
}
map.forEach((k,i) -> sum += Math.abs(i) ); //summing the absolute values of the counters
System.out.println(sum)
}
}
Basically both solutions just counts how many letters the two strings have in common, but with different approach.
Hope I helped!

I need help understanding java code

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();

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.

Parsing file and detection of pattern in Java

My problem is quite simple, i am parsing a CSV file, line after line and i want to get the values of the columns.
The separators used are simply ";", but my file can have quite a lot of columns, and they won't be always in the same order.
So as example for my .CSV file :
time;columnA;columnB,ColumnC
27-08-2013 14:43:00; this is a text; this too; same here
And i would like to be able to get all the values of time, columnA, columnB and columnC.
What would be the easiest way?
I used StringUtils.countMatches(input, ";"); to get the number of separators i have.
I started trying to make a String index[][] = {{"time", "columnA", "columnB", "columnC"}{}};
And my plan was to fill this with the number of ";" before each other variable, so that i could easily now which result stands for which variable.
But now i'm quite stuck...
If you want me to show more of my code, i can.
Hope that someone can help me ! :)
(sorry for the poor english).
You can simply use split() method
For instance:
Scanner aScanner = ...
ArrayList<String> L = new ArrayList<String>();
while(aScanner.hasNextLine()){
L.add(aScanner.nextLine());
}
int rows = L.size();
String[][] S = new String[rows][];
for (int i = 0; i < rows; i++) {
S[i] = L.get(i).split(";");
}

Selection Indexes are not same to getText indexes

i'm new to java, start a project 7 days ago, today with some folks from this place i successed to pass through one problem, but still there's one more...
in last problem i needed to search an string and highlight it, but now, my problem is:
Why selection index are not same to the indexes i search for after some unknown character which i dont know my self :|
this is my button code:
int startFrom = jEditorPane1.getSelectionStart();
if(jEditorPane1.getSelectionStart() == jEditorPane1.getSelectionEnd()){
startFrom = -1;
}
String searchWord = jTextField3.getText();
int searchIndex = jEditorPane1.getText().indexOf(searchWord, startFrom + 1);
if(searchIndex != -1){
jEditorPane1.requestFocusInWindow();
jEditorPane1.select(searchIndex, searchIndex+searchWord.length());
}
else{
jEditorPane1.setSelectionStart(0);
jEditorPane1.setSelectionEnd(0);
}
and i'm sure that i need to do some string processing, to convert string index to swing jEditorPane/JTextPane index
for example:
i search for do in string like this:
"Hey,
How do you do?"
and it highlight it this way:
"Hey,
How doyou do?"
which mean it started one index forther that what it should, and in here it's casue escape char of \n and i dont know, cause some time it happen in single row text...
how can i get ride of this?
See Text and New Lines for more information and a solution. The basics of this link is to use:
int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);
The above will only return "\n" as the EOL string so the offsets will match when you do a search and then select the text.

Categories