Java while loop help - nested if else statement [closed] - java

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 am brand new to java and trying to create a story based around goldilocks and the three bears in which I ask the user a series of questions and the questions loop until the expected answer is given. It is for a class, and the expectation is we use while loops and if/ nested if else statements to do so. I have managed to get it set up so that the correct messages appear if the user inputs the wanted answer, however, haven't managed to get the question to loop if they input the wrong choice. Instead it just prints the error message and ends the program.
Can anyone give me any tips on where I am going wrong/ no exact fixes just a basic outline would be appreciated. Please assume that there is more to the program but I don't want to have anything flagged for plagiarism of myself later.
This is my if else statement so far (we are using GTerm https://jupiter.csit.rmit.edu.au/~e58140/GTerm/doc/GTerm.html hence gt.getInputString and so forth)
String porridge1;
porridge1 = gt.getInputString("How hot was the porridge? Cold, hot, somewhere in the middle?");
//dialog box asking user question about porridge
gt.println("\n" + "How did Golidlocks find the porridge? Too cold, too hot, or just right?");
// printed message about porridge temperature for user to follow
if (porridge1.equalsIgnoreCase("cold") || porridge1.equalsIgnoreCase(hot")) {
gt.showErrorDialog("Oh no. This porridge was too " + porridge1 + "!");
//if user input = cold or hot; error dialog box appears
gt.println("Oh no! This porridge was too " + porridge1 + "!");
//if user input = cold or hot; print error message
} else {
gt.showMessageDialog("This porridge is just the right temperature!");
//if user types anything else, dialog box confirming correct choice to appear
gt.println("How wonderful! This porridge is just right!");
//if any other input given (middle, warm, perfect, just right etc, print following message

From what I can see there's no loops anywhere that's why it's ending. Put that code inside a while loop to keep it running then put the keyword break whenever you want it to break out of the loop.
while(true){
//Your code here
if(condition...){}
else(condition...){
//Your code here
break;
}
}
Also just a note, typically commenting code goes above the line(or side) of code you're referring to, not under

Related

Java Related, regarding: If-Else, Do-While, Try-Catch [closed]

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".

Understanding a coding challenging in finding the first duplicate value in an array [closed]

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 2 years ago.
Improve this question
I am currently practicing with my coding skills and one of the challenges I ran into was finding the first duplicate value produced in an array. I had solve the challenge, but not in a timely manner. I looked at the solution for the problem and ran into this solution and wanted help in understanding how it exactly works. I have the solution commented in the areas that I understand and what exactly is the purpose of that block of code, but I would like help in understanding the if-statement why it works the way it does.
int firstDuplicate(int[] a) {
for(int i=0;i<a.length;i++)
//Checks ???????????
if(a[Math.abs(a[i])-1]<0)
return Math.abs(a[i]);
//Make the checked value negative
else{
a[Math.abs(a[i])-1]=-a[Math.abs(a[i])-1];
}
//If there are no duplicates it returns -1
return -1;
}
Constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length.
Welcome to SO. I will not give you the exact answer but instead provide you with tools for you to figure it out.
In order for you to figure out this code, you need to debug it. Here are some ways you could go about it.
Set a breakpoint just prior to calling the function (look up how to do this for your IDE), thereafter step into your code line-by-line.
You could use a combination of temporary variables and System.out.println() statements. Looking into your code, break it down into modular bits that you can track. For instance you could re-write the expression inside the if statement as
int currentElementAbsolute = Math.abs(a[i]);
System.out.println(currentElementAbsolute);
int difference = currentElementAbsolute - 1;
System.out.println(difference);
int element = a[difference]
System.out.println(element);
if (element < 0)
{
return Math.abs(a[i]);
}
As you can see, for each operation/line, I print out the current value thus keeping track of events. Practice this and re-write the else part
PS: Upon completion you will realise this method fails to capture all duplicates when certain type of numbers are used. Happy Hunting :)

Java Basic I want to prompt user 9 digit zip code [closed]

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

Text not being read into variable [closed]

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

Java Input Empty show alert [closed]

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

Categories

Resources