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
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 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
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 4 years ago.
Improve this question
First of all, I'm extremely new to Java, so simple answers would be much appreciated.
I'm trying to write a program so that the user can either input the following:
java howManyFiles 10
and get the output:
You selected 10 files.
Or, the user can input the following:
java howManyFiles
and get the output:
How many files would you like?
I can't seem to figure out a way to create a scanner that reads the initial input. The nextLine() scanner method looks for a new user input, rather than checking to see if one already exists. Any help would be a life saver. Thanks
java howManyFiles 10 seems like 10 is a command-line argument. Those arguments appear in the String[] argument to main. Here's a simple example:
public static void main(String[] args) {
if (args.length == 0) {
// User didn't provide number of files.
// You need to prompt the user and read their input.
} else if (args.length == 1) {
int numFiles = Integer.parseInt(args[0]);
System.out.println("You selected " + numFiles + " files.");
} else {
// User provided two or more command-line arguments.
// You might want to print an error message in this case.
}
}
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 7 years ago.
Improve this question
hi i have a java programming assignment wich include 3 exercice i have done 2 already but in the third one i am dont know wich data type i should use
here is the question :
Write a java program that reads from the user the course code, section and the scores of a student for three exams representing two midterms and a final. The percentage of each of the three exams is of fixed value 30, 30 and 40 percent respectively. Your program computes the final average grade and displays it along with the course code and the section.
Remark: All data, except for the average, must be whole numbers and you should use the most efficient data type that is suitable for this specific exercise.
Sample Run:
Enter your course code: CSCI250
Enter your section: E
Enter the scores of the tests and the final: 97 83 77
CSCI250 E 84.8 (result)
so what i want to know is what is the preferable data type to use for course code ? and char is the one that i should use for section right ?
If you're capturing user input, use a String for everything.
Reason? You may request a number, but the user can type anything. Your code needs to handle bad input.
I think you can use String as data type for Course Code. You can write both numbers and letters by using it. And for section, yes, char will be suitable for it.
Use a String for arbitrary text.
If the section code is always present1 and is never more than character than a char can be used.
However, I would still use a String for consistency, flexibility, and easy of use. The teacher may prefer this based on the "efficient"cy they are going for.
1The is a soft "always": while char cannot represent null a sentinel (eg. '\0' or ' ') can be used to indicate 'no section specified'. Using such a sentinel to supplement null can also (but does not always) lead to more logic work - in particular when the record is displayed.
In any case, it is probably best to not switch to Character just for the null as this is most likely outside of the scope of current course work.
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));