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".
Related
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.
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
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm doing a small project in Java whilst I'm learning the language.
Basically what I'd like is for a user to input a string via JOptionPane.showInputDialog();, if that string is empty, I want it to make them re-enter a valid string and then the program will continue.
What I did consider doing is using goto but I read up on it and it said it's not good practice.
Any help would be greatly appreciated.
Thanks :)
I would do it in an infinite loop asking for input (using OptionPane.showInputDialog()).
Here you have some pseudo code:
message = ""
while message.equals(""):
message = ask_for_input() // (.trim() if needed)
end
You could do it in a loop. So you take a while-loop where the condition is that the input is empty. Then the message will pop up until the user entered something.
Despite goto is a reserved keyword in Java, it's actually (implicitly) meant for not being used.
JOptionPane.showInputDialog(...) returns a String.
I suggest using an infinite while loop and comparing it to empty, through String.isEmpty().
For instance:
String input = null;
while (true) {
input = JOptionPane.showInputDialog("Your input (not empty):");
if (!input.trim().isEmpty()) {
// TODO something with the input variable
break;
}
}
This is what do ... while loops are for. You could also use the Apache commons StringUtils class.
String input;
do {
input = JOptionPane.showInputDialog("Please enter your string");
} while (StringUtils.isBlank(input));
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I need to write a program that defines the String variable containing the name 'JOE BLOGGS'. I then need to printout in the console the 1st and 5th characters, How could I make a java program for this so that the name can also be changed and the program will still function correctly?
And then I have to extend the code to add (concatenate) the string ‘is an employee’ to JOE BLOGGS's name and convert the sentence to upper case, and print the resulting string to the screen, i.e.
JOE BLOGGS IS AN EMPLOYEE
Many thanks for your time:) I literally got no idea how to start as i'm quite new to Java.
Sometimes I feel like programming is just a bunch of Googling to answer my questions.
But never fear; here are a couple of hand-picked (although thoroughly unoriginal) links that I believe will answer all of your listed questions:
Oracle's Java Strings Tutorial
Oracle's java.lang.String
The Oracle tutorials I find surprisingly good. On the second link, just search for upper, or better yet, skim the methods section.
try this...
public class TestClass {
public static void main(String[] args) {
new TestClass().printChars("JOE BLOGGS", "is an employee");
}
public void printChars(String baseString, String additionalString) {
System.out.println(baseString.charAt(1));
System.out.println(baseString.charAt(5));
System.out.println(baseString + " " + additionalString.toUpperCase());
}}
People should really stop posting their homeworks, and start trying at least...
If you're taking a java class, i'd say the least you have learned for you to do this homework is already enough.
Anyways:
public class classname{
public static void main(String[] args){
String str = "Your String goes here"; //so usually you should put JOE BLOGGS between the quotes
System.out.println(str.charAt(1));
System.out.println(str.charAt(5));
str += " is an employee";
str = str.toUpperCase();
System.out.println(str);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am doing an assignment and I have to do several simple string manipulations. I think I have the last one figured out, and it works by itself, but it does not work when I put it together with the other string manipulations, giving me an arrayoutofbounds exception error. Any advice?
Here is the small code I made
public static void main (Strings[] args) {
Scanner sc = new Scanner(System.in);
String theSentence = sc.nextLine();
String [] theWords = theSentence.split(" ");
Arrays.sort(theWords);
System.out.println(theWords[1]);
System.out.println(Arrays.toString(theWords));
}
This does not work when it is put together with the rest of the code even though it works by itself. For reference, this code is supposed to take in a small sentence and give me the smallest word lexicographically. Ex: input: "4 WHAT WAIT IS THIS" output would be "IS"
The code is assuming that theWords will always have at least two elements in it. If the sentence provided by the user does not have any spaces, theWords will never get an element in position 1 and so the program will crash on System.out.println(theWords[1]);
In Java arrays are indexed from zero, where the 0th element is the first.
As Mark said you are assuming that there are always two words entered in this case. You should check the length of theWords before trying to access an element.