name = JOptionPane.showInputDialog("What is " + "your name? ");
How do I make this a do while loop so that if the user inputs a number instead of a string it will not move on till a letter is put in. Thanks
Before the loop make a boolean value set to true, and make it so the loop continues until you change the boolean to false. Only set the boolean to false when you get valid input.
You will of course have to check if the number is a int or a string, but exactly how you'd go about doing that will depend on if you want there to be no numbers at all in the string or if it's okay as long as there is at least one character. There are a lot of answers around about that so I'd just Google it.
Related
I have a method that loops through a file to find the number of lines.
static int findFileSize(Scanner f){
System.out.println("Got to counter:");
String str;
int line_count = 0;
while(f.hasNextLine()) {
line_count++;System.out.println(line_count);
//str = f.nextLine();
}System.out.println("File size: " + line_count);
return line_count;
}//end findFileSize
When i don't include the str = f.nextLine();, i can see it indexing indefinitely. What causes this to happen? And is there a way of finding the number of lines in a .txt file without needing to unnecessarily store a data into a string?
What causes this to happen?
You aren't reading anything from the Scanner, you're just asking it if you will be able to read something.
If you walk into a shop and ask if they have, say, carrots, if the answer is "yes", but you don't buy any carrots, the shop still has carrots. So, if you walk out and walk in to ask again, they will still have the carrots, so they will again answer "yes" (unless somebody else has bought them).
You have to "buy the carrots" by using f.nextLine().
without needing to unnecessarily store a data into a string?
You don't have to store it in a variable:
f.nextLine();
will read the String and immediately discard it. But there isn't really a huge difference between this and storing it in a variable: the variable only keeps the contents of the last-read line anyway. (But since you don't give str an initial value, it's not definitely assigned after the loop, so you can't read its value after the loop in any case).
I'm just learning Java and am practicing creating methods and then invoking them in my main program. To practice this I created a simple program that's supposed to gather data from a prospective horse rider.
Here is the main application:
public class CompleteApp {
public static void main(String[] args) {
TaskOne weight1 = new TaskOne();
TaskTwo nameagehealth1 = new TaskTwo();
TaskThree phoneaddress1 = new TaskThree();
if (weight1.Weight() < 250) {
nameagehealth1.NameAgeHealth();
phoneaddress1.AddressPhone();
}
else {
System.out.println("Thanks for checking!");
}
}
}
I've created three separate classes to do different tasks. Here is the class that's having prompting the error:
import java.util.Scanner;
public class TaskThree {
static void AddressPhone() {
Scanner input = new Scanner(System.in);
System.out.println("Please tell me your address: ");
String address = input.nextLine();
System.out.println("Please tell me your phone number: ");
int phone = input.nextInt();
System.out.println("You said your address is " + address + " and your phone is " + phone + ".");
System.out.println("Thank you for the information, we'll be in touch soon to schedule your ride.");
}
}
The error:
Exception in thread "main" java.util.InputMismatchException: For input string: "3037201234"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at TaskThree.AddressPhone(TaskThree.java:10)
at CompleteApp.main(CompleteApp.java:13)
It seems to indicate that the error is in the phone number and that is being read as a String, yet I made it an integer. I'm not sure where I'm going wrong here. Also, how would I handle it if a user entered their phone number like this: 303-720-1234 vs 3037201234?
Thanks so much for the help!
Since it can't be stored as an int due to the length as Sibbo mentioned, and you're concerned about formatting then you should store it as a String. If you have to do any type of checking to make sure the user inputs data in the correct format (either 1234567890 or 123-456-7890) then you should look into regular expressions. If you run a regular expression on your string then you will be able to get a boolean result to tell you whether or not it is valid.
Why not represent the phone number as a String and use scanner.next()? As mentioned before, when a phonenumber start with a 0 this zero would be removed if you use anything other than String, so I think it's the best way to go.
From your comments, I read that parsing it to a Long works for you. I would strongly recommend using a String though, for several reasons:
Phone numbers with leading zeroes (like international phone numbers). Integers and Longs 'trim' leading zeroes, rendering your phone numbers useless.
If you want to do some extra stuff when presenting your phone numbers (like adding dashes or anything), you will have to parse your Integer/Long back to a String and do your representation magic anyway.
As you just found out, not every phone number can be stored in a 32-bit Integer, but you already worked around that using a Long.
There are probably more reasons for this, but these 2 come to mind.
The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). Your input value is out of the range of int.
You should store phone number as String rather than int. If you want to handle numbers like 303-720-1234, parse it as string, remove the - character and then use it.
The input 3037201234 is too large to be represented as an int, so it cannot be parsed as an int.
Integers in Java range from −2,147,483,648 to 2,147,483,647.
Instead of using int for variable phone declare it as long and instead of input.nextInt() use method input.nextLong(). I think this will solve your problem.
I made a program that thinks of a number and you have to guess the number.
It is working well, but I got stuck.
First of all, you (the player) has 10 tries in a round. Every wrong guess subtracts 1 from the tries. If you reach 0 you lose.
The variable where the thing stores the randomized number looks like this:
int guess = Integer.parseInt(etGuess.getText().toString());
Of course I have an edittext field with the name etGuess.
So when the player enters the same number twice (for example: 5, then 5 again), the program subtracts 1 then again 1 (so 2) tries.
I'd like to know how can I get the previous value of the guess integer and check whether it was already guessed or not.
I think of something like this:
if ( previous_guess != guess )
Use a HashSet.
Here's how I would do this:
//Declare the variable outside of a function
HashSet<Integer> previousGuesses = new HashSet<Integer>();
//Check if it is already guessed
if (set.contains(guess)) {
//Alert the user that they can't use this.
}
//Adding a variable to it in a function:
set.add(guess);
Make sure to test if it contains before adding it or preforming any of the regular code.
Store all of your previous numbers in an array and then check the array then the player enters a new number.
I finished a beginner's game program and it works fine, except it's a bit slow when it prompts the user to play again. It is a do...while loop that goes around the entire main method. I want to make it so that the user only needs to type "1" and press enter ONCE rather than twice for the game to replay.
How can I fix this? Also, I'm not sure which part of my program I need to show (if needed), so if you need that, please let me know.
This should work.
if (correctc == 3 && correctp == 3){
System.out.println("\nUser wins! Colour was " + colchoice);
System.out.println("Press 1 to play again with a new combo.");
pagain = myInput.readLine(); // game starts with new combo or ends
}
// User tries guessing again
else{
System.out.println("\nEnter 1 to guess again.");
loop = myInput.readLine();
}
}while("1".equals(loop)); // user continues guessing the same combo
}while("1".equals(pagain)); // new game with new combo
The reason for this is readLine() waits for line to be terminated by "\n" (an enter in this case). You use it twice:
pagain = myInput.readLine();
and then
loop = myInput.readLine();
Isn't "pagain" supposed to be doin what your "loop" is doing? I beileve it is possible to use only one variable to steer both of these loops. For example, you ask to type in "1" to loop again the same set and type in "2" to try with a new set. Then you can get rid of the "loop" variable. It will go out of the inner do-while when it checks that you typed in "2".
I asked about this array a little while ago, and I can't see what the problem is. Too tired. What have I done wrong? Basically, I am taking a string array and trying to check to see if it contains numbers or an x (ISBN number validation). I want to take the number from a given input (bookNum), check the input, and feed any valid input into a new array (book). At the line
'bookNum.charAt[j]==book[i]'
I get the 'not a statement error'. What gives?
String[] book = new String [ISBN_NUM];
bookNum.replaceAll("-","");
if (bookNum.length()!=ISBN_NUM)
throw new ISBNException ("ISBN "+ bookNum + " must be 10 characters");
for (int i=0;i<bookNum.length();i++)
{
if (Character.isDigit(bookNum.charAt(i)))
bookNum.CharAt[j]==book[i];
j++;
if (book[9].isNotDigit()||
book[9]!="x" ||
book[9]!="X")
throw new ISBNException ("ISBN " + bookNum + " must contain all digits" +
"or 'X' in the last position");
== is java is used for equivalence comparison. If you want to assign it, use a single =.
The first issue here is that charAt is a function, and thus needs parenthesis even though you are accessing with an index like an array.
The other issue is that the line is a boolean expression, which just by itself does not mean anything. A lot of people are suggestion that you mean to make an assignment to that character, but just changing to a single equals causes other problems. The left side of an equals sign needs to be a variable, and the result of a function is not a variable.
Strings are immutable, so you can not simply change one of the characters in the string. Earlier in your code, you have a call to replaceAll(), that returns a new string with the alterations. As written, this altered string is being lost.
There are few odd problems here. For starters, did you mean for book to be an array of Strings, as opposed to just one string? You're trying (assuming CharAt was written properly and the assignment was proper) to assign a character to a string.
Second, instead of copying character by character, why not check the whole string, and copy the whole thing at the end if it is a proper ISBN? Depending on what you do with Exceptions (if you continue regardless), you could add a boolean as a flag that gets set if there is an error. At the end, if there is no error, then make book = to booknumber.replace(etc...)
bookNum.CharAt[j]==book[i];
Should be
bookNum.CharAt[j]=book[i];
You are using an equality boolean operator, not an assignment one.
Looks like you're using .charAt(i) wrong! Assuming that "bookNum" is a String, you should use:
bookNum.charAt(i)==book[i];
Instead. Note that this is a boolean expression, and not "=".
The line bookNum.CharAt[j]==book[i]; isn't a statement. It's a comparison. Perhaps you want bookNum.CharAt[j]=book[i]; (single = instead of ==).
Edit: That's not going to fix things, though, since you can't assign to bookNum.CharAt[j].