java print method, a format method confusion of the string class - java

I am not sure how to interpret the format method down below of the String class,ugh so confused, could someone help me with me recognize it so i can use it.
StringBuilder sb = new StringBuilder();
String[] s = new String[] { "quit", "add", "delete", "find", "change" };
for (int i = 0; i < s.length; i++) {
sb.append(String.format("| %d:%s |", i, s[i]));
}

for (int i = 0; i < s.length; i++) {
sb.append(String.format("| %d:%s |", i, s[i]));
}
%d is a placeholder for numbers you just place it where you want to use your number.
%s is a placeholder for a string.
String.format("| %d:%s |", i, s[i])
first run string looks like this
"| 0:quit|"
each time you loop you just go trought array of strings s. And decimal is used for showing its location in array.
Formating string can be very usefull and it make your strings rather more elegant and easyer to read :)

Basically, %d represents a placeholder of numbers ("Formats the argument as a decimal integer") and %s is a placeholder for String
The command will supplement for the value of i where %d is and s[i] for where %s is...
Check out Formatter for more details
You could also check out How to format String in Java – String format Example which goes into more detail

Related

Java - Finding a certain string in JTextArea

I'm creating a simple program that gets 2 certain strings on an input from a JTextArea. It needs to find a non-integer string then finds an integer. All values matching from the same non-integer string will add and display the result in a JTextField. Like in the example below, all numbers who matches "ax" will be added together and the final result will be displayed in the texfield below the label "AX Box" (25 + 5 = 30)
My following code:
JTextField ax, bx, cx, dx;
int totalAX, totalBX, totalCX, totalDX;
String[] lines = textArea.getText().split("\\n"); // split lines
System.out.println(Arrays.toString(lines)); // convert each line to string
for (int i = 0; i < lines.length; i++) {
if (lines.contains("ax") {
// add each numbers.
// for example, 25 + 5
totalAX = totalAX + i;
ax.setText("Total: " +totalAX);
}
}
My problem is that the program cannot find the substring "ax", "bx" and so on. What's the best approach in this? I get errors like:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "ax"
I'm not sure that you're actually splitting the array, the escape sequence for a line jump is \n, you have it as \\n.
You are also only printing the array lines if you need to convert it to String you should be reassigning a value for it like:
for (int i = 0; i < lines.length; i++) {
String line = lines[i].toString();
And I'm pretty sure you don't need the toString() as it should come as a String variable from the textBox
After this you need to find if it contains the "ax" and the index where it is first contained, keep that number and use it to substring the whole line to find the number, so bearing in mind that the number should be in the last place of the string you would be looking at something like this after (inside) the loop:
if (line.contains("ax") {
int theIndex = line.indexOf("ax");
line = line.substring(theIndex);
}
Or in a oneliner:
if (line.contains("ax") {
line = line.substring(line.indexOf("ax"));
}
I used regex to extract numbers from the lines that match your text.
Pattern pattern = Pattern.compile("[0-9]+");
Matcher m;
System.out.println(Arrays.toString(lines));
for (int i = 0; i < lines.length; i++) {
if (lines[i].contains("ax")) {
m = pattern.matcher(lines[i]);
if (m.find()) {
totalAX += Integer.parseInt(m.group());
}
}
}
ax.setText("Total: " +totalAX); //put this line outside of the loop so that it will show the totalAX after all numbers have been read.

java.io.PrintStream display

I'm working on a java program using arrays and loops to create a table, however when the values print they are followed by "java.io.PrintStream#1909752" repeating over and over a number of times
The chunk of code causing the error is as follows, more specifically the "row +=" sections. Any help for how to get rid of the repeated part at the end would be appreciated.
for ( int i = starting; i <= ending; i+= 1){
row += System.out.format("%6d" + ": ", i);
for ( int j = 0; j <= 11; j+=1){
double answer = i*octaveArray[j];
row += System.out.format("%.0f ", answer );
}
System.out.printf(row);
System.out.println("");
}
From the documentation of PrintStream#format():
Writes a formatted string to this output stream using the specified format string and arguments.
That means that PrintStream#format() will write the values to the output stream but you then append its toString representation which looks like java.io.PrintStream#1909752 to the row variable which you then print out to the same output stream.
You should use String.format() instead if you wish to append the formatted result to a String variable.

Remove chars from string in Java from file

How would I remove the chars from the data in this file so I could sum up the numbers?
Alice Jones,80,90,100,95,75,85,90,100,90,92
Bob Manfred,98,89,87,89,9,98,7,89,98,78
I want to do this so for every line it will remove all the chars but not ints.
The following code might be useful to you, try running it once,
public static void main(String ar[])
{
String s = "kasdkasd,1,2,3,4,5,6,7,8,9,10";
int sum=0;
String[] spl = s.split(",");
for(int i=0;i<spl.length;i++)
{
try{
int x = Integer.parseInt(spl[i]);
sum = sum + x;
}
catch(NumberFormatException e)
{
System.out.println("error parsing "+spl[i]);
System.out.println("\n the stack of the exception");
e.printStackTrace();
System.out.println("\n");
}
}
System.out.println("The sum of the numbers in the string : "+ sum);
}
even the String of the form "abcd,1,2,3,asdas,12,34,asd" would give you sum of the numbers
You need to split each line into a String array and parse the numbers starting from index 1
String[] arr = line.split(",");
for(int i = 1; i < arr.length; i++) {
int n = Integer.parseInt(arr[i]);
...
try this:
String input = "Name,2,1,3,4,5,10,100";
String[] strings = input.split(",");
int result=0;
for (int i = 1; i < strings.length; i++)
{
result += Integer.parseInt(strings[i]);
}
You can make use of the split method of course, supplying "," as the parameter, but that's not all.
The trick is to put each text file's line into an ArrayList. Once you have that, move forwars the Pseudocode:
1) Put each line of the text file inside an ArrayList
2) For each line, Split to an array by using ","
3) If the Array's size is bigger than 1, it means there are numbers to be summed up, else only the name lies on the array and you should continue to the next line
4) So the size is bigger than 1, iterate thru the strings inside this String[] array generated by the Split function, from 1 to < Size (this will exclude the name string itself)
5) use Integer.parseInt( iterated number as String ) and sum it up
There you go
Number Format Exception would occur if the string is not a number but you are putting each line into an ArrayList and excluding the name so there should be no problem :)
Well, if you know that it's a CSV file, in this exact format, you could read the line, execute string.split(',') and then disregard the first returned string in the array of results. See Evgenly's answer.
Edit: here's the complete program:
class Foo {
static String input = "Name,2,1,3,4,5,10,100";
public static void main(String[] args) {
String[] strings = input.split(",");
int result=0;
for (int i = 1; i < strings.length; i++)
{
result += Integer.parseInt(strings[i]);
}
System.out.println(result);
}
}
(wow, I never wrote a program before that didn't import anything.)
And here's the output:
125
If you're not interesting in parsing the file, but just want to remove the first field; then split it, disregard the first field, and then rejoin the remaining fields.
String[] fields = line.split(',');
StringBuilder sb = new StringBuilder(fields[1]);
for (int i=2; i < fields.length; ++i)
sb.append(',').append(fields[i]);
line = sb.toString();
You could also use a Pattern (regular expression):
line = line.replaceFirst("[^,]*,", "");
Of course, this assumes that the first field contains no commas. If it does, things get more complicated. I assume the commas are escaped somehow.
There are a couple of CsvReader/Writers that might me helpful to you for handling CSV data. Apart from that:
I'm not sure if you are summing up rows? columns? both? in any case create an array of the target sum counters int[] sums(or just one int sum)
Read one row, then process it either using split(a bit heavy, but clear) or by parsing the line into numbers yourself (likely to generate less garbage and work faster).
Add numbers to counters
Continue until end of file
Loading the whole file before starting to process is a not a good idea as you are doing 2 bad things:
Stuffing the file into memory, if it's a large file you'll run out of memory (very bad)
Iterating over the data 2 times instead of one (probably not the end of the world)
Suppose, format of the string is fixed.
String s = "Alice Jones,80,90,100,95,75,85,90,100,90,92";
At first, I would get rid of characters
Matcher matcher = Pattern.compile("(\\d+,)+\\d+").matcher(s);
int sum = 0;
After getting string of integers, separated by a comma, I would split them into array of Strings, parse it into integer value and sum ints:
if (matcher.find()){
for (String ele: matcher.group(0).split(",")){
sum+= Integer.parseInt(ele);
}
}
System.out.println(sum);

Reading a string with multiple options

I have String like ",yes,,,,,,,,,,,,," which says option2 is selected out of 15 options. Here, a comma , represents a option; if it is selected then some data will be there in place of option. I need to read this string and get the exact option selected value. In above it should be option2. How shall I do this?
I have 15 options in database from which selected data is replaced here and , in place none selected.
Or, looked at another way, there are 15 fields separated by commas. One field — in the example, the second field — has a non-empty value; the others are all empty. How can I determine the first field that is not empty?
Try String.split(",") - this will return String[]
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29
public class Split {
public static void main(String [] args) {
String [] options = args[0].split(",",15);
for(int i = 0; i < options.length; i++) {
System.out.printf("option %d = [%s]\n", i, options[i]);
}
}
}
If I understand you correctly, you get a string of commas and between two commas there is some word like "Yes". Your task is to retrieve the index of that word, i.e., the number of commas (plus 1) before the word.
First of all, that encoding for an option is quite stupid, so if it lies in your responsibility, change it.
The simple solution is to count the commas before the word.
Something like this will do:
String s = ",yes,,,,"
for ( int i = 0 , len = s.length() ; i < len ; i++ )
if ( s.charAt(i) != ',' )
return i+1;
throw new Exception ("No option found");
Well, I assume you want to split the string on , like this:
String[] options = ",yes,,,,,,,,,,,,,".split(",");
String option2 = options[1]; //yields "yes"
However, why don't you use some more understandable markup, like option2=yes etc.?
Have a look at Apache Commons CLI for some library to support better options.
If your String always follows the format you specify, you can use String.split(). For example,
String[] split = ",yes,,,,,,,,,,,,,".split(",");
System.out.format("The chosen data is in Option %d and is '%s'%n", split.length, split[split.length - 1]);
prints
The chosen data is in Option 2 and is 'yes'

Java characters count in an array

Another problem I try to solve (NOTE this is not a homework but what popped into my head), I'm trying to improve my problem-solving skills in Java. I want to display this:
Students ID #
Carol McKane 920 11
James Eriol 154 10
Elainee Black 462 12
What I want to do is on the 3rd column, display the number of characters without counting the spaces. Give me some tips to do this. Or point me to Java's robust APIs, cause I'm not yet that familiar with Java's string APIs. Thanks.
It sounds like you just want something like:
public static int countNonSpaces(String text) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) != ' ') {
count++;
}
}
return count;
}
You may want to modify this to use Character.isWhitespace instead of only checking for ' '. Also note that this will count pairs outside the Basic Multilingual Plane as two characters. Whether that will be a problem for you or not depends on your use case...
Think of solving a problem and presenting the answer as two very different steps. I won't help you with the presentation in a table, but to count the number of characters in a String (without spaces) you can use this:
String name = "Carol McKane";
int numberOfCharacters = name.replaceAll("\\s", "").length();
The regular expression \\s matches all whitespace characters in the name string, and replaces them with "", or nothing.
Probably the shortest and easiest way:
String[][] students = { { "Carol McKane", "James Eriol", "Elainee Black" }, { "920", "154", "462" } };
for (int i = 0 ; i < students[0].length; i++) {
System.out.println(students[0][i] + "\t" + students[1][i] + "\t" + students[0][i].replace( " ", "" ).length() );
}
replace(), replaces each substring (" ") of your string and removes it from the result returned, from this temporal string, without spaces, you can get the length by calling length() on it...
The String name will remain unchanged.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
cheers
To learn more about it you should watch the API documentation for String and Character
Here some examples how to do:
// variation 1
int count1 = 0;
for (char character : text.toCharArray()) {
if (Character.isLetter(character)) {
count1++;
}
}
This uses a special short from of "for" instruction. Here's the long form for better understanding:
// variation 2
int count2 = 0;
for (int i = 0; i < text.length(); i++) {
char character = text.charAt(i);
if (Character.isLetter(character)) {
count2++;
}
}
BTW, removing whitespaces via replace method is not a good coding style to me and not quite helpful for understanding how string class works.

Categories