I am doing a coding project for a basic non recursive, non GUI form of Minesweeper. One of the requirements is that input commands must be strictly formatted like so:
For marking commands (reveal, guess, mark):
["reveal"/"r"] [int] [int]
For help and quit:
just ["help"/"h"] or ["quit"/"q"]
Any inputs outside of these restrictions must be considered ill-formatted. My code for reveal looks something like this:
case "reveal":
case "r":
roundsCompleted ++;
if(input.hasNextInt()){
par1 = input.nextInt();
}
else{
commandIn = null;
}
if(input.hasNextInt()){
par2 = input.nextInt();
correctInput = true;
}
else{
commandIn = null;
}
if(correctInput && isInBounds(par1, par2)){
reveal(par1, par2);
where this is all inside a switch statement of course. The commandIn = null statements are designed to throw the default case which prints "command not recognized". I realize part of my issue here is that these are in two separate if-else statements. Another problem is that input.hasNextInt() doesn't seem to evaluating to false when there is not an int after the first one.
The essence of this problem is in completely restricting these commands to the formats I listed above. Can anyone give me some insight into this issue? Thanks.
I'd use regex to first see if something is either a good input or not just cause it'd be easier
String input = "r 3 4";
if (input.matches("^(help|h|quit|q|((r|reveal) \\d \\d))$"))
//switch case
System.out.println("match");
else
//null string
System.out.println("no match");
then after you've got a match you can use your switch case like what you're doing, if it's a "reveal" or "r", I would just use split() and turn it into an array to get the different x and y coordinates
Related
I'm trying to learn java but I'm stuck trying to do a single program which concerns Do While Statement with two conditions. Specifically, I want a method to run until the user write "yes" or "no". Well, down there is my thing, what is wrong with it?
String answerString;
Scanner user_input = new Scanner(System.in);
System.out.println("Do you want a cookie? ");
do{
answerString = user_input.next();
if(answerString.equalsIgnoreCase("yes")){
System.out.println("You want a cookie.");
}else if(answerString.equalsIgnoreCase("no")){
System.out.println("You don't want a cookie.");
}else{
System.out.println("Answer by saying 'yes' or 'no'");
}while(user_input == 'yes' || user_input == 'no');
}
}}
I'd do something similar to Tim's answer. But to do things the way you were trying to do them, you have a lot of problems that need to be fixed:
(1) String literals in Java are surrounded by double quote marks, not single quote marks.
(2) user_input is a Scanner. You can't compare a scanner to a string. You can only compare a String to another String. So you should be using answerString in your comparison, not user_input.
(3) Never use == to compare strings. StackOverflow has 953,235 Java questions, and approximately 826,102 of those involve someone trying to use == to compare strings. (OK, that's a slight exaggeration.) Use the equals method: string1.equals(string2).
(4) When you write a do-while loop, the syntax is do, followed by {, followed by the code in the loop, followed by }, followed by while(condition);. It looks like you put the last } in the wrong place. The } just before the while belongs to the else, so that doesn't count; you need another } before while, not after it.
(5) I think you were trying to write a loop that keeps going if the input isn't yes or no. Instead, you did the opposite: you wrote a loop that keeps going as long as the input is yes or no. Your while condition should look something like
while (!(answerString.equals("yes") || answerString.equals("no")));
[Actually, it should be equalsIgnoreCase to be consistent with the rest of the code.] ! means "not" here, and note that I had to put the whole expression in parentheses after the !, otherwise the ! would have applied only to the first part of the expression. If you're trying to write a loop that does "Loop until blah-blah-blah", you have to write it as "Loop while ! (blah-blah-blah)".
I might opt for a do loop which will continue to take in command line user input until he enters a "yes" or "no" answer, at which point the loop breaks.
do {
answerString = user_input.next();
if ("yes".equalsIgnoreCase(answerString)) {
System.out.println("You want a cookie.");
break;
} else if ("no".equalsIgnoreCase(answerString)) {
System.out.println("You don't want a cookie.");
break;
} else {
System.out.println("Answer by saying 'yes' or 'no'");
}
} while(true);
its only my second program with java and im running into some issues.
I'm trying to get input from a user, either yes or no, then based on that go to an if else statemene. Heres what I have so far
String answer= UI.askString("Do you want to continue?");
if(answer=="yes"){
UI.println("Lets go");
}
else if(answer == "no"){
UI.println("Thank you. Goodbye");
}
else{
UI.println("Please enter yes or no");
}
Im thinking perhaps its better to use booleans for this?
Any help is gladly appreciated!
(also if you're wondering, its a custom import hence the weird syntax in some lines)
Cheers.
When you compare two Strings in Java with the == operator, they are compared to see if they are the same object, rather than whether they contain the same text. So, you could type "yes", and when you use if (answer == "yes") the comparison fails, because the object you got back from UI.askString is a different object, stored at a different place in memory, than the String the compiler generated from the literal "yes".
To compare the value of the two Strings you need to write answer.equals("yes"), or "yes".equals(answer). Either one will work, and will call the equals method of the String class, which will compare the actual text.
The latter syntax, "yes".equals(answer), is often recommended because it will not cause a NullPointerException, even if the variable answer is set to null. This is because the equals method handles null and simply returns false. If, on the other hand, you used the answer.equals("yes") form, and answer was null, you would be trying to invoke a method on null and an exception would be thrown.
what you are looking for is a dialog box. Here is oracle examples, with code. It is more than I can write here. There are ton of yes, no boxes and detection's of user input with them.
http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
Quick answer:
int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){ ... }
Other choices ...
YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION, and CLOSED_OPTION
For a command line program you need...
import java.util.Scanner;
The code will look like ...
Scanner in = new Scanner(System.in);
String line = in.nextLine();
//ask them to write yes, no, whatever
if(line.equal("yes"){ }
else if (line.eqals("no") {}
else {}
using MikeG010590's answer, you can try:
Scanner in = new Scanner(System.in);
String line;
System.out.println("you want to continue?");
Boolean exit = null;
do {
line = in.nextLine();
switch (line) {
case "yes":
exit = false;
break;
case "no":
exit = true;
break;
default:
System.out.println("Please enter yes or no");
break;
}
}
while (exit == null);
System.out.println(exit ? "Thank you. Goodbye" : "Lets go");
I'm having trouble with passing a string and double to another class because it keeps on crashing at double cost = input.nextDouble();. Also, i was wondering if i am correct with the appending method used in public boolean addPARTDETAILS(String partDESCRIPTION, double partCOST).
For example. If the user enters the parts and cost, i want it to store that in a list and print it out with the cost appended.
Parts used:
brake pads ($50.00)
brake fluids ($25.00)
Note. Assuming that i have declared all variables and the array.
System.out.print("Enter registration number of vehicle");
String inputREGO = input.next();
boolean flag = false;
for(int i=0; i<6; i++){
if(inputREGO.equalsIgnoreCase(services[i].getregoNUMBER())){
System.out.print("Enter Part Description: ");
String parts = input.nextLine();
double cost = input.nextDouble();
services[i].addPARTDETAILS(parts, cost);
//System.out.println(services[i].getregoNUMBER());
flag = true;
}
}if(flag==false);
System.out.println("No registration number were found in the system.");
public boolean addPARTDETAILS(String partDESCRIPTION, double partCOST){
if(partDESCRIPTION == "" || partCOST <= 0){
System.out.println("Invalid input, please try again!");
return false;
}
else{
partCOST=0;
StringBuffer sb = new StringBuffer(40);
String[] parts = new String[50];
for (int i=0;i<parts.length;i++){
partDESCRIPTION = sb.append(partCOST).toString();
}
System.out.println(partDESCRIPTION);
totalPART+=partCOST;
return true;
}
}
it keeps on crashing at double cost = input.nextDouble();.
It is highly unlikely that your JVM is crashing. It is far more likely that you are getting an Exception which you are not reading carefully enough and have forgotten to include in your question.
It is far more likely your code is incorrect as you may have mis-understood how scanner works. And so when you attempt to read a double, there is not a double in the input. I suspect you want to call nextLine() after readDouble() to consume the rest of the the line.
I suggest you step through the code in your debugger to get a better understanding of what it is really doing.
Just to expand a bit on Joop Eggen's and Peter Lawrey's answers because I feel some may not understand.
nextLine doesn't play well with others:
nextDouble is likely throwing a NumberFormatException because:
next, nextInt, nextDouble, etc. won't read the following end-of-line character, so nextLine will read the rest of the line and nextDouble will read the wrong thing.
Example: (| indicates current position)
Start:
|abc
123
def
456
After nextLine:
abc
|123
def
456
After nextDouble:
abc
123|
def
456
After nextLine (which reads the rest of the line, which contains nothing):
abc
123
|def
456
Now nextDouble tries to read "def", which won't work.
If-statement issues:
if(flag==false);
or, rewritten:
if(flag==false)
;
is an if statement with an empty body. Thus the statement following will always execute. And no need to do == false, !flag means the same. What you want:
if (!flag)
System.out.println("No registration number were found in the system.");
String comparison with ==:
partDESCRIPTION == ""
should be:
partDESCRIPTION.equals("")
or better:
partDESCRIPTION.isEmpty()
because == check whether the strings actually point to the exact same object (which won't happen unless you assign the one to the other with = at some point, either directly or indirectly), not just whether the have the same text (which is what equals is for).
Data dependent error.
if(flag==false);
System.out.println("No registration number were found in the system.");
should be (because of the ;):
if (!flag) {
System.out.println("No registration number was found in the system.");
}
And
partDESCRIPTION == ""
should be:
partDESCRIPTION.isEmpty()
This is an assignment i have to complete.
Can someone lead me in the right direction?
The program compiles but wont run correctly.
The error is InputMissmatch exception.
The error you are getting means that you are trying to use some kind of data as another one, in your case, you are probably trying to use a String as a float.
When using any of the next methods in the Scanner class you should first be sure that there's an appropiate input from the user.
In order to do so, you need to use the has methods.
Your problem is that you are not checking wether the input is a correct float or not before using your Scanner.nextFloat();
You should do something like this:
if (hope.hasNextFloat())
{
// Code to execute when you have a proper float,
// which you can retrieve with hope.nextFloat()
}
else
{
// Code to execute when the user input is not a float
// Here you should treat it properly, maybe asking for new input
}
That should be enough to point you in the right direction.
Also, check the Scanner api documentation for further details.
EDIT
Also, you are asking the user to input characters (or strings): "A", "B", etc..., but you are trying to compare them with a float. That's wrong, you should compare them with a string or character, like this:
if (hope.hasNextString())
{
if (hope.nextString().equals("A"))
{
// Code for option "A"
}
else if (hope.nextString().equals("B"))
{
// Code for option "B"
}
else ...
}
You could use a switch there, but it seems that you are not yet very fammiliar with java, so I'll leave it for another time.
Your problem is that you are entering a letter into a float field.
In your program you're asking the user to enter a float:
A = hope.nextFloat();
But if you enter the letter "A", you're going to get an exception because "A" is not a float, it's a string.
A simpler way to solve your problem is instead of having all the choices fields, you just read the input the user enters from the scanner like:
String choice = hope.next();
Next in the if statement, you check if the value from the string choice is equal to a specific letter, for example
if (choice.equals("A")) {
number4 = (number1 + number2 + number3);
System.out.printf("Your results are:" + (number4));
}
And you can do the same thing for the other choices you have.
I'm trying to use string input (yes or no) as a sentinel for a loop. The loop repeats a switch statement, and at the end prompts the user with a yes or no question. Until they type 'yes' as their answer, the loop continues to receive data from the user. The problem comes from trying to receive a new value for the sentinel.
***Reviewed the comments and made some changes. Here's the updated code:
Scanner input = new Scanner ( System.in );
System.out.print( "Please enter a product number, 1 - 5: ");
int product = input.nextInt();
double sum = 0;
boolean complete = false;
while (!complete) {
switch (product){
case 1: sum = sum + 2.98;
break;
case 2: sum = sum + 4.50;
break;
case 3: sum = sum + 9.98;
break;
case 4: sum = sum + 4.49;
break;
case 5: sum = sum + 6.87;
break;
}
System.out.print( "Is your order complete? Please type true or false:");
complete = in.nextLine();
}
All of that is working but I am still having trouble with the prompt to break the sentinel. I'm trying to get it set up to where the user types true to end the loop or false to continue it. I'm starting to think I've overlooked something. I greatly appreciate the help, thank you.
Change
default: String complete = input.Stream(); //Not coded, but will also ask for input.
to
default: complete = input.Stream(); //Not coded, but will also ask for input.
You're redeclaring a String, which is not what you want. And follow the advice given of using .equals, not == for Strings or other reference types.
It's griping because you declared it twice. Take off the second String declaration:
default: complete = input.Stream(); //Not coded, but will also ask for input.
You are declaring complete twice. Try modifying your default case statement as:
default: complete = input.Stream()
Two things:
1) you are redeclaring complete. The default case should just be:
default: complete = input.Stream();
2) in Java you can't compare Strings with !=. Every String is an object and by using the comparison operators you are comparing the identifiers of the objects, not the contents of the objects. Java will never see two String objects as equal unless they are two strings pointing to the same memory location. To compare the values of two strings you have to use the .equals() method such as:
while (!complete.equals("yes")) {
Or even better as a habit:
while (!"yes".equals(complete)) {
This is better because if the complete String variable were null then the first comparison would throw a null pointer exception where the second won't since the literal string "yes" will always evaluate to a not-null object.
Hope that helps.
David