Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
What function should i use for Java programming to get the total number of colons in a CSV file?
PS: not a Java developer.
Read the file char by char (using a BufferedReader to make it fast), and count each colon you meet:
int countColons() throws IOException {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file.txt), "UTF-8"))) {
int count = 0;
int c;
while ((c = in.read()) >= 0) {
if (c == ':') {
count++;
}
}
return count;
}
}
Of course, you should use the appropriate encoding for your file. Not necessarily UTF-8.
Read the file line by line. For every line, use replaceAll to get rid of every character that isn't a colon. Then get the length of the resulting String. Keep a cumulative total of the results of this.
If you don't want to reinvent the wheel:
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
int count = StringUtils.countMatches(FileUtils.readFileToString(new File("file.csv")), ":");
One cool trick I found a while ago for counting the number of occurences is to take the length of the string, and minute all the values from it that are not your desired value.
Example
// Assume fileStr contains everything in the file
int numberOfColons = fileStr.length() - fileStr.replaceAll(":", "").length();
This will give you the number of colons in the file.
Edit
Just remembered when I got it from. It is from this question.
The reason why I like this approach
Obviously, it's extremely short, which is always nice. It does give some of a hit to the processor, but it avoids all loops (in your code at least) and it seems like a very elegant solution to the problem.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I came upon an issue in React-Native interacting with NativeModules, where in Java passing a String from React-Native to the Java host trimmed the string of null chars. The string in question is "R\u0000" which represents fine in both Java and React-Native. However when typecasting between the two, the null value is erased and only "R" comes through.
You can imagine how funny it is to trim trailing zeros in a number, but it is second nature in strings. These strings represent binary sequences largely for BLE communications, and trimming is destructive.
So it came upon me to interpret each letter of the string as a hexidecimal value in an array of strings. In the JS, a Uint8Array goes from [82,0] (decimal) to [52,0] and then as a string ["52", "0"]. The array ["52", "0"] arrives in Java fine.
I'm weak in Java and struggling here. I need to turn these strings whose contents are hexidecimal values of bytes, in to a byte[].
Try this.
public static void main(String[] args) throws IOException {
String[] input = {"52", "0"};
int length = input.length;
byte[] output = new byte[length];
for (int i = 0; i < length; ++i)
output[i] = (byte)Integer.parseInt(input[i], 16);
System.out.println(Arrays.toString(output));
}
output:
[82, 0]
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So let's say I have a CSV file of random alphabets in columns for example's sake:
a
wrrq
jt
pkto
b
They are in String format and I want to be able to find the minimum String length in this CSV list. In the example given, the minimum being 1 (the maximum being 4). Then I want to print all the minimums in order, resulting in:
a
b
This is my code that reads each line from the top and it's barely anything to a helpful guideline but I'm kind of stuck right now.
BufferedReader br = new BufferedReader(new FileReader("Example.csv"));
while ((nextLine = br.readLine()) != null) {
...
}
Is there a way to do this a simple way without using fancy 3rd party scripts. Maybe putting them into an array and then working from there perhaps(?) Keeping in mind that the minimum may not always be 1.
For a single-pass solution…
Create an empty collection to store results. Read first line, and store it in collection.
Read another line.
If this line is the same length as previously stored line, add to collection.
If longer, ignore.
If shorter, empty collection and then add.
Lather, rinse, repeat.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is my code:
public class sample {
public static void main(String []args) throws Exception {
System.out.println("Enter from file:");
BufferedReader br=new BufferedReader(new FileReader("C:\\Users\\KK\\A Key.txt"));
String currentline;
while((currentline=br.readLine())!=null){
System.out.println(currentline);
}
BigInteger a = new BigInteger(currentline);
System.out.println(a);
}
I want to read from the text document , convert it into big integer from a string, I tried this but i get a run time error , How to convert String into corresponding Big integer Ascii value.
Your problem is very simple: you build a BigInteger from a null string!
You are looping until currentLine is null.
Afterwards you try to create a BigInteger from that!
Simply move things into your loop:
while((currentLine=br.readLine())!=null) {
System.out.println(currentLine);
BigInteger a = new BigInteger(currentline);
System.out.println(a);
}
Et voilĂ , things are working (assuming that you expect each line in your file to be a number). If the whole file represents one number, then you must do as zstring suggests in his comment: you would have to use a StringBuilder for example to "collect" all lines into a single string that you then use to create the BigInteger object.
And please note java coding styles: class names start Uppercase; and variable names use camelCase (thus I changed to currentLine).
But just for the record: you wrote a low quality question. You should always include compiler error messages or stack traces when asking "why is my code not working".
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am very new to Java, but I am really enthusiastic to learn it. I would like to solve the problem by myself step by step
I tried to do my homework piece by piece.
I want to ask users to put 9 digit zip code, for example 701152014, not for 5 digit like 70115.
I wanted to keep asking users until they type 9 digits like 701152014
if they put 5 digits I want to keep asking please type 9 digit.
I use NetBean.
System.out.println(zipNew); This part, something wrong with it.it says error.
so I wanted to prompt user until users would type 9 digit zip code.
how can I do that? Thank you so much.
Thank you so much for teaching me. I really would like to learn Java. Thank you.
package week7;
import javax.swing.*;
public class test {
public static void main(String[] args){
//Scanner scanner = new Scanner(System.in);
String zip=JOptionPane.showInputDialog(null,"Enter your zip");
String zipNew;
int ziplength = (zip.length());
if (ziplength == 9){
zipNew = zip;
}
else if (ziplength !=9)
{
String zip = JOptionPane.showInputDialog(null,"please type 9 digit zip code not 5 digit"); //----this part is wrong
}
System.out.println(zipNew); //----this part is wrong,
}
Normally, I'd use a JFormattedField and/or DocumentFilter, but lets keep it simple...
The basic idea is, you need to loop until you get what you need, for example...
String zip = null;
do {
zip = JOptionPane.showInputDialog(null, "Enter your zip");
} while (zip != null && zip.length() < 9);
System.out.println("zip = " + zip);
This will loop until the user presses [Cancel] or the value they enter has 9 characters. You need to beware, this can result in zip been equal to null and you will need to check for this. Also, there is nothing stopping the user from entering non-numeric values...
Take a closer look at The while and do-while Statements for more details
First off, the formatting is terrible. Not sure if it occurred when posting it here and you didn't actually use that formatting, but you might wanna make it more readable.
You declare the String zip twice. You can't have two variables of the same name in the same class, so in your else if condition (you don't need the if ziplength != 9 as the else guarantees that condition is true) change the name of the String or don't declare the variable again (e.g. say zip = blahblah not String zip = blahblah in the else).
To answer your question, use a do-while loop. Here's an example:
String zip;
do {
zip = blahblah
} while (zip.length != 9)
My assumption is that in the line :
int ziplength = (zip.length());
You are simply not getting the length of zipNew, but instead the length of zip, which doesn't appear to have been declared anywhere.
I would suggest changing this line to :
int ziplength = (zipNew.length());
I have very little experience with java, but just from broad understanding of other languages, I believe you've just made a simple mistake.
Hope this works!
Cheers,
Mike
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Here is my code, I am supposed to read in data such as AAABBBCCCDDD and output a3b3c3d3.
I have updated the code, and now the code compiles and runs, however nothing is output. I dont know if its the way im reading data in or if the code is incorrect.
String text;
FileReader data = new FileReader("input.txt");
BufferedReader in = new BufferedReader(data);
text=in.readLine();
in.close();
//Counter looks at length of data
int counter=0;
//Counter2 looks at current letter or number to make see if its the same then iterates it
int counter2=0;
while (text.charAt(counter)<=text.length())
{
while (text.charAt(counter)==text.charAt(counter2+1))
{
counter2++;
}
System.out.println(text.charAt(counter) + counter2);
counter=counter2;
}
The reason the compiler is complaining is because in this loop:
while (in.readLine()!=null)
{
text = in.readLine();
}
it's possible that the body of the loop will never get executed, which means it's possible that text will never be set to anything. And the Java compiler doesn't like it when you use a variable that may not have been set to anything.
But the whole loop is wrong anyway. You're only using one input string, so why is this a loop? Before we can help fix this problem, we need to know what you're trying to accomplish. And if you really do want a loop, it would be wrong to call in.readLine() twice as you have above, since that means it will read two lines each time through the loop.
Assuming you've properly imported all the java.io classes, here are the two problems causing compilation to fail:
String text;
This must be initialized to something. Such as
String text = null;
Possibly setting it in the while loop is not good enough.
The other problem is this variable, output doesn't exist anywhere, which is why this line won't compile:
System.out.println(output);
I think you mean for it to be text