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
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 4 days ago.
Improve this question
I am in my first semester of a Java Course. I am struggling to understand how I put exclusiveness on a statement. I am writing a Class for an Object Couch. I have tried to build a well formed class, but for the outcome from my main, in the console it must only have 4 or 8 legs on the couch. There is no user input as I am hard coding the variables, but I want to be sure that if I hard code for 5 legs it will stop me or an error message will pop up. Any suggestions?
public void setNbrLegs(int nbrLegs){
if ((nbrLegs == 2) || (nbrLegs == 4)){
this.nbrLegs = nbrLegs;
}
}
I tried putting an "else" with a message that that number is bad, but what is did was bypass my error message and just insert the incorrect number ofLegs as 5.
Consider looking for the opposite: a condition where you must fail. From there, you can use runtime exceptions to ensure a few things:
The invalid state is not applied
A developer passing this invalid state will get an exception, and have a clear reason to fix their code
You no longer have to worry about invalid state further on in the method (i.e. legs will only be 2 or 4 further on).
In doing so, your method may end up looking like this:
public void setNbrLegs(int legs) {
if (legs != 4 && legs != 2) {
throw new IllegalArgumentException("Can only have 2 or 4 legs");
}
this.nbrLegs = legs;
}
This preconditional checking is also good to do early in your methods (fast-fail), as it will prevent excess work being done for a method that will only "fail".
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 9 years ago.
Improve this question
is there a way to tell the compiler in Java or Android to not remove some statements in code -which are intended to clean up variables after use to prevent any data remnant in ram-??
would creating a dummy method solve this issue??
these statements basically set the variables to their type-based initial values..
Thanks in advance!
The code that you describe is not dead code.
Dead code is code that will never execute.
Here is an example:
private int secretSchmarr;
public boolean blammo()
{
boolean returnValue;
secretSchmarr = calculateSecretValue();
returnValue = useSecretValue(secretSchmarr);
secretSchmarr = 99; // this is not dead code.
return returnValue;
secretSchmarr = 98; // This is dead code because it can never execute.
}
I answer under the odd assumption that you have a good reason to believe that the code is still useful even though it is dead.
Store the value false in some obfuscated form that the compiler can't understand. Then, conditionally branch to that code using your obfuscated value. The compiler will not know it is dead, so it will not be removed.
I'll use a file for my example, but it is probably not the most efficient way. Say your code that the compiler thinks is dead code was in a function called myCode(). Assume that fin is reading from a file that only contains false followed by EOF
if(Boolean.parseBoolean(fin.next()))
myCode();
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
I know this may be a weird question to be asking, but I came across this method and is not too sure of it's purpose.
I been reading online for it's explanation, but did not find one that is easily understood.
What I need is not a code, but rather why should it be implemented.
The snippet code are as follow:
private PrintWriter out;
private static final String end = "067e6162-3b6f-4ae2-a171-2470b63dff00 ";
//generated using the above method, UUID.randomUUID()
public static String getEnd() {
return end;
}
private void sendOutputToClientFile(String str) {
out.println(str);
out.println();
out.println(end);
}
The codes are found inside a server file, and is supposedly use to denote the end of message.
But what purpose does it serve here and why is it necessary?
P.S : I would prefer a layman's term of explanation...
The code writes the random string that is assumed (and with astronomic level of probability very likely to be true) unique, no other calls to UUID.randomUUID will probably ever produce it. Probably this string is checked at another end as the "end of stream" sequence.
Most likely the designer was not able to reserve any particular char sequence to mark the end of the data stream, and for some reason could not use the usual IO methods either. It is highly unlikely that such string will appear inside the stream as well for some reason just by chance.
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.
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.