I am building a hangman game but I need help trying to check whether the user input was used before (like they guess a then b and than a again):
String input = console.next();
if(input.length()>1){
System.out.println("One letter at a time");
}
//to insert data into arrays
letter[a]=input;
if (!input.equalsIgnoreCase(input)) {
System.out.println("You have aready enter " + input);
} else {
continue;
}
This will add the method you want to use to the String class:
String.prototype.equalsIgnoreCase = function(other_string) {
return this.toLowerCase() === other_string.toLowerCase();
}
Make sure you're not trying to compare a String to itself, though, like you're doing with input in your question. Also, use JavaScript syntax for web-served files instead of C++ syntax.
Related
//Code up
if (userinput.contains(help)) {
//Go on with the game
}
else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
I tried almost everything a beginner would know and nothing , do while loops not working in my case (maybe you can find a way) , if i let the if like that the game closes if you get the wrong answer (something out of conttext) , some help would be great! Thx :D
You could use a 'Recursive' function (a function that calls itself).
So in this case, you could do something like:
public void getAndParseInput(){
String userInput = getUserInput() // Use whatever you're using to get input
if(userInput.contains(help)){
// If the user input contains whatever the help is (note: if you're looking for the specific word help, it needs to be in speech marks - "help").
continueWithGame...
}else{
System.out.println("Im sorry , couldnt understand that");
this.getAndParseInput();
}
}
You need to put that code inside a while loop and establish an exit condition.
boolean endGame = false;
/* Here read userinput */
While(!endGame) {
if (userinput.contains(help)) {
//Go on with the game
} else if(userinput.contains("quit"){
endGame = true;
} else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
/* Here read userinput */
}
The Below code is similar to your code,reuse the code with appropriate changes as you required.
The code works as below.
1. Scans the input from the console
2. Compares the scanned input with the String "help"
3. If scanned input matches with help, then continue with the execution
4. Otherwise, if the user wants to continue then he can press the
letter 'C' and continues with the execution.
5. If user doesn't press 'C', then the control breaks the while loop
and comes out of the execution
public void executeGame() {
Scanner scanner = new Scanner(System.in);
String help = "help";
while(true) {
System.out.println("Enter the input for execution");
String input = scanner.nextLine();
if (input.contains(help)){
System.out.println("Continue execution");
} else {
System.out.println("Sorry Wrong input.. Would you like to continue press C");
input = scanner.nextLine();
if (input.equals("C")){
continue;
} else {
System.out.println("Sorry wrong input :"+input);
System.out.println("Hence Existing....");
System.exit(0);
}
}
}
}
beginner here. I want to be able to ask the user a question. If the user's answer is empty or contains only spaces, it should print out an error, then go back to the unanswered question. Thus creating a loop until the question is answered. Please see code below:
do {
while(true) {
System.out.print("Dog's name: ");
String dogName = scan.nextLine().toLowerCase().trim();
if(dogName.isEmpty()) {
System.out.println("Error: This can't be empty.");
continue;
}
do {
while(true) {
System.out.print("Breed: ");
String breed = scan.nextLine().toLowerCase().trim();
if(breed.isEmpty()) {
System.out.println("Error: Breed can't be empty.");
continue;
}
This code works but it gets very repetitive and long. Is there a shorter and faster way of writing this? Thank you.
This is an ideal use case for a function. A function encapsulates a piece of code that you need multiple times and allows for both input via parameters and output via return types.
I suggest to read beginner tutorials of Java on how to use functions (also called methods in Java if they belong to a certain object, i.e. are not static).
Functions (also called procedures sometimes in other languages) are the basic building block of procedural programming, so I suggest you to learn about that topic as well.
In your specific case, that function could look like this:
String input(String label)
{
System.out.print(label+": ");
String s = scan.nextLine().toLowerCase().trim(); // assuming "scan" is defined in the enclosing class
if(s.isEmpty())
{
System.out.println("Error: "+label+" can't be empty.");
return input(label);
}
return s;
}
This is a recursive function but you can do it iteratively as well.
Create a method for the code which takes the question as a parameter,if the input is wrong you need to ask the same question, call the same method(recursion) with the same question.
pseudo code::
public void test(String s) {
System.out.print(s + ": ");
String input = scan.nextLine().toLowerCase().trim();
if(dogName.isEmpty()) {
System.out.println("Error: This can't be empty.");
test(s);
} else {
return input;
}
To read about recursion.
You can try something like this so you can have many questions but same amount code, this is to illustrate the idea, may not fully work
String questions[] = {"Dog's name: ","Breed: "};
for (int i = 0; i < questions.length; i++) {
System.out.print(questions[i]);
Scanner scan = new Scanner(System.in);
String answer = null;
while(!(answer = scan.nextLine()).isEmpty()) {
System.out.print("You answered: " + answer + "\n");
}
}
You can do this :
while ((dogName = scan.nextLine().toLowerCase().trim()).isEmpty()) {
System.out.println("Error: This can't be empty.");
}
// Use dogName not empty
while ((breed = scan.nextLine().toLowerCase().trim()).isEmpty()) {
System.out.println("Error: Breed can't be empty.");
}
// Use breed not empty
Best
Hello and thank you in advance for your time. I'm working on a homework assignment that require an input from the user in command line. If the user input the "Exit" or "Quit" My program should quit. I'm able to do one one work but not sure how to do two. ALso the my loop is not looping all time. Can someone shine some light please.
import java.io.Console;
public class Echo2{
public static void main(String [] args){
String userText = System.console().readLine("Enter some text:");
//System.out.println("*** " + userText + " ***" );
if (userText.equals("Exit")){
return;
}
else{
System.out.println("*** " + userText + " ***" );
}
}
}
As of the loop you can simply do this:
while(true) {
if (userText.equals("Exit") || userText.equals("Quit")) {
break;
}
}
Or if you want to go a little fancy here you can do this
while(true) {
if ("exit".equals(userText.toLowerString()) || "quit".equals(userText.toLowerString()) {
break;
}
}
the 2nd approach is a little more flexi here, as regardless of the what the user types (this being quit, qUit, EXIT, exIT) the program will convert this to lower case and match within the condition specified
Just use the || operator if you want to do more than one check in an if statement:
if (userText.equals("Exit") || userText.equals("Quit")) { ... }
As far as your loop "not looping all the time"; I don't see any loop. Have you failed to include it in your post?
I'm very new to programming, especially Java. I need to create a program that counts how many orders each entry at a restaurant gets ordered. The restaurant carries 3 entries, hamburgers, salad, and special.
I need to set up my program so that the user inputs, say, "hamburger 3", it would keep track of the number and add it up at the end. If the user inputs "quit", the program would quit.
System.out.println("Enter the type (special, salad, or hamburger) of entrée followed by the number, or quit to exit the program.");
I'm thinking about using a while loop, setting it so if the user input != to "quit", then it would run.
What's difficult for me is I don't know how to make my program take into account the two different parts of the user input, "hamburger 3" and sum up the number part at the end.
At the end, I want it to say something like "You sold X hamburgers, Y salads, and Z specials today."
Help would be appreciated.
You'll probably want three int variables to use as a running tally of the number of orders been made:
public class Restaurant {
private int specials = 0;
private int salads = 0;
private int hamburger = 0;
You could then use a do-while loop to request information from the user...
String input = null;
do {
//...
} while ("quite".equalsIgnoreCase(input));
Now, you need some way to ask the user for input. You can use a java.util.Scanner easily enough for this. See the Scanning tutorial
Scanner scanner = new Scanner(System.in);
//...
do {
System.out.println("Enter the type (special, salad, or hamburger) of entrée followed by the number, or quit to exit the program.");
input = scanner.nextLine();
Now you have the input from the user, you need to make some decisions. You need to know if they entered valid input (an entree and an amount) as well as if they entered an available option...
// Break the input apart at the spaces...
String[] parts = input.split(" ");
// We only care if there are two parts...
if (parts.length == 2) {
// Process the parts...
} else if (parts.length == 0 || !"quite".equalsIgnoreCase(parts[0])) {
System.out.println("Your selection is invalid");
}
Okay, so we can now determine if the user input meets or first requirement or not ([text][space][text]), now we need to determine if the values are actually valid...
First, lets check the quantity...
if (parts.length == 2) {
// We user another Scanner, as this can determine if the String
// is an `int` value (or at least starts with one)
Scanner test = new Scanner(parts[1]);
if (test.hasInt()) {
int quantity = test.nextInt();
// continue processing...
} else {
System.out.println(parts[1] + " is not a valid quantity");
}
Now we want to check if the actually entered a valid entree...
if (test.hasInt()) {
int quantity = test.nextInt();
// We could use a case statement here, but for simplicity...
if ("special".equalsIgnoreCase(parts[0])) {
specials += quantity;
} else if ("salad".equalsIgnoreCase(parts[0])) {
salads += quantity;
} else if ("hamburger".equalsIgnoreCase(parts[0])) {
hamburger += quantity;
} else {
System.out.println(parts[0] + " is not a valid entree");
}
Take a look at The if-then and if-then-else Statements and The while and do-while Statements for more details.
You may also find Learning the Java Language of some help. Also, keep a copy of the JavaDocs at hand, it will make it eaiser to find references to the classes within the API
These two methods should be what you're looking for.
For splitting: String.split(String regex)
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
For parsing String into an Interger: Integer.parseInt(String s)
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
You can split your strings using input.split(" "). This method gives you two strings - two parts of the main string. The character you splitted with (" ") won't be found in the string anymore.
To then get an integer out of your string, you can use the static method Integer.parseInt(inputPartWithCount).
I hope this helps!
So everything is working fine for this calculator besides for the askCalcChoice1. Since askCalcChoice1 is a string, I am calling it wrong (obviously). The error says it cannot convert string to int, as well as convert int to boolean. However, when i make the inputOperation as a string, it breaks the other 2 calls below askCalcChoice1. (it breaks displayRedults and askTwoValues because those are not strings). I do not know how to format askCalcChoice in order to call for this method that is written in another class wihtout breaking anything. askCalcChoice is written as a string which i pasted below the oopCalculator code. Is there any way and can someone please show me how to write that portion of that code in oopCalculator?
int inputOperation; // user to choose the function
askCalcChoice1 myAskCalcChoice1 = new askCalcChoice1();
//menu becomes a complete string below
String menu = "Welcome to Hilda Wu's Calculator\t\t"
+ "\n1. Addition\n"
+ "2. Subtraction\n"
+ "3. Multiplication\n"
+ "4. Division\n"
+ "5. Exit\n\n";
calculatorCommands.pickNewSymbol(menu); //complete menu will be picked up as a string and display
calculatorCommands.putDownSymbol();
while (inputOperation = myAskCalcChoice1.calcChoice()) { //this will call for myAskCalcChoice1 class
calculatorCommands.pickNewSymbol("\n"); //pick up the class
calculatorCommands.putDownSymbol(); //display the class
askTwoValues myAskTwoValues = new askTwoValues();
float[] myFloats = myAskTwoValues.inputFloats(inputOperation);
displayResults myDisplayResults = new displayResults();
float result = myDisplayResults.showResults(inputOperation, myFloats);
String strFormat = "The answer is: " + result + "\n\n"; //print out The answer is as a string
calculatorCommands.pickNewSymbol(strFormat); //pick up string from above
calculatorCommands.putDownSymbol(); //display string
calculatorCommands.pickNewSymbol(menu); // pick up menu from the beginning of code, loop to calculator menu
calculatorCommands.putDownSymbol(); //display menu as loop
}
calculatorCommands.pickNewSymbol("\nThank you for using Hilda Wu's Calculator\n"); //when user choose to exit calculator
calculatorCommands.putDownSymbol();
}
String calcChoice() {
String input;
do { //do loop will continue to run until user enters correct response
System.out.print("Please enter a number between 1 and 5, A for Addition, S for Subtraction, M for Multiplication, or D for Division, or X for Exit: ");
try {
input = readInput.nextLine(); //user will enter a response
if (input.equals("A") || input.equals("S") || input.equals("M") || input.equals("D") || input.equals("X")) {
System.out.println("Thank you");
break; //user entered a character of A, S, M, or D
} else if (Integer.parseInt(input) >= 1 && Integer.parseInt(input) <= 5) {
System.out.println("Thank you");
break; //user entered a number between 1 and 5
} else {
System.out.println("Sorry, you have entered an invalid choice, please try again.");
}
continue;
}
catch (final NumberFormatException e) {
System.out.println("You have entered an invalid choice. Try again.");
continue; // loop will continue until correct answer is found
}
} while (true);
return input;
}
}
To start with, you are calling showResults with two arguments:
int choice
and
float [] f
Choice is never used.
You use input variable instead in your switch but on default you return the error showing choice.
Better pass choice as an argument in the function and be sure it is char and not other type.
Also this is not the form of a good stated question. I will not rate it down but please remake it so the whole code is correctly shown. I can not make sense of it easily. I might misunderstood it already. Please do not add comments between, be sure you have correct indentation and you got all the code in.
If you need to comment do it afterwards. It's not very complicated, just show us the code and ask what is wrong later ;)
If choice was meant to pass in the switch... then do it, but not as int but as char.