I made this while loop that is supposed to fulfill functions for different shapes and after it fulfills the function for that shape, it will keep asking for shapes until the user types "Exit". I have only done Triangles so far so I just have some filler functions to fulfill to make sure that it loops correctly. The problem is, after I'm done with triangles, it will print the menu twice before asking for an input instead of just printing once. Can anyone explain this to me?
while(password){
System.out.println();
System.out.println("---Welcome to the Shape Machine---");
System.out.println("Available Options:");
System.out.println("Circles");
System.out.println("Rectangles");
System.out.println("Triangles");
System.out.println("Exit");
String option = keyboard.nextLine();
if(option.equals("Exit")){
System.out.println("Terminating the program. Have a nice day!");
return;
} else if(option.equals("Triangles")){
System.out.println("Triangles selected. Please enter the 3 sides:");
int sideA = 0;
int sideB = 0;
int sideC = 0;
do{
sideA = keyboard.nextInt();
sideB = keyboard.nextInt();
sideC = keyboard.nextInt();
if(sideA<0 || sideB<0 || sideC<0)
System.out.println("#ERROR Negative input. Please input the 3 sides again.");
} while(sideA<0 || sideB<0 || sideC<0);
if((sideA+sideB)<=sideC || (sideB+sideC)<=sideA || (sideA+sideC)<=sideB){
System.out.println("#ERROR Triangle is not valid. Returning to menu.");
continue;
} else {
System.out.println("good job!");
}
}
}
It might be that you are using keyboard.nextLine();. In your code outside the while loop make sure that you are always using .nextLine() and nothing else.
Reasoning: If you use .next(), it'll only consume one word so the next time you call .nextLine(), it'll consume the end of that line.
After you say sideC = keyboard.nextInt() the carriage return that you typed (after typing the number) is still in the input buffer. Then you print the menu and execute String option = keyboard.nextLine(); That command reads up to and including the first newline it finds, which is the newline that is still in the buffer.
So option is now a bare newline character, which does not match "Exit" or "Triangle", so it loops again and prints th menu again.
This problem is caused by left-over characters like space, carriage-return, newline, form-feed in the input buffer.
Since the next keyboard.nextLine() doesn't match any of given options (and since there is no "else" at the bottom of while loop to deal with this case), the control goes into next iteration, prints the options again. Based on surrounding context of processing of input, there are several good answers to address this problem on SO.
Since your intention is to skip over all blanks, carriage-returns, newlines, form-feeds till you get a valid string (option) again, the following code works best in a case like yours.
System.out.println();
System.out.println("---Welcome to the Shape Machine---");
//...
System.out.println("Exit");
String option = keyboard.nextLine();
keyboard.skip("[\\s]*");
Related
I have been trying to create a game that asks the user to type in 2 three-letter words; the program is supposed to give clues for how close the words match by splitting them up and stating if the letters come before, or after, each other in the alphabet.
The game is nearly done, but my problem shows up when I try to start a new turn after one guess. I need some kind of while loop, but I've rearranged blocks of the code so many times that I feel like it made the entire thing more convoluted. The prompt for the second user to answer a question, as well as the clue, should be repeated every time the two inputs don't fully match.
Example Output when the two user inputs are cat and fan: after, a, before
The "after" shows that the letter comes after the user's letter in the alphabet, and the "before" shows that the letter comes before the user's letter.
EDIT: I have taken the answers into account as much as I can, thank you so much. So far, I have implemented a do while loop and tried to fix my variables. In the end, I feel that I may have to create an object to be able to recopy the code of the user inputs after a certain conditional statement would be set to false.
My new issues are
1. The compiler cannot find the symbols x1,y1,z1,x2,y2, and z2 whenever I have the user inputs inside the do while loop.
2. If I tried to make a new object, I would be rewriting & rearranging more than what might be necessary.
This is still ongoing, and as I continue to work on it I will keep updating this post.
(EDITED CODE -- I saved the original code which I can send to anyone who would like to see it.)
import java.util.Scanner;
class Main{
public static void main(String[] args) {
System.out.println("Guess The Word\n(requires two players)");
System.out.println("If the letter in each word matches, the letter will be reprinted.");
System.out.println("If the letter guessed doesn't match, either \"before\" or \"after\" will print.");
Scanner in1=new Scanner(System.in);
//Scanner in2=new Scanner(System.in);
try{
boolean correct1=false; boolean correct2=false; boolean correct3=false;
int indication=0;
//asks for user input and stores in substrings
do{
System.out.print("First Player, enter a three letter word: ");
String user1=in1.nextLine();
String x1=user1.substring(0,1);
String y1=user1.substring(1,2);
String z1=user1.substring(2,3);
System.out.print("Second Player, enter a three letter word: ");
String user2=in1.nextLine();
String x2=user2.substring(0,1);
String y2=user2.substring(1,2);
String z2=user2.substring(2,3);
}
while(!correct1||!correct2||!correct3);
//possible end to loop
// if(user1==user2){indication=1;}
// else{indication=0;}
//comparisons of each letter
int comp;
int comp2;
int comp3;
comp=x1.compareTo(x2);
comp2=y1.compareTo(y2);
comp3=z1.compareTo(z2);
//while1=(comp!=0);
//while2=(comp2!=0);
//while3=(comp3!=0);
//if statement 1
if(comp==0){
System.out.print(x1);
correct1=true;
}
else{
// System.out.println(comp);
if(comp>0){
System.out.println("before, ");
}
else{
System.out.print("after, ");
}
}
//if statement 2
if(comp2==0){
System.out.print(y1);
correct2=true;
}
else{
// System.out.println(comp);
if(comp2>0){
System.out.println(", before, ");
}
else{
System.out.print(", after, ");
}
}
//if statement 3
if(comp3==0){
System.out.print(z1);
correct3=true;
}
else{
// System.out.println(comp3);
if(comp3>0){
System.out.println(", before");
}
else{
System.out.print(", after");
}
}
//ignore else{System.out.print("Congratulations!");}
}
finally{in1.close();}/* in2.close();}*/
}
}
Maybe declare 3 booleans (1IsCorrect, 2IsCorrect, 3IsCorrect) set them default to false and in the if(comp/comp1/comp2 == 0) statements after printing the value set the corresponding boolean to true.
then put it in a do while(!1IsCorrect || !2IsCorrect || !3IsCorrect)
declare a variable perhaps for isFirstRun before loop and instantiate it to true at the declaration, then set to false at the very end.
Make an if !isFirstRun statement and add in the code there to ask for the next guess
Hope this works
I am trying to create a program that picks a random number, and as the user inputs guesses, the program dictates if it's "too high", "too low", AND keeps a running total. But my while loop only extends over the first nested loop I create, and won't cover anything after that.
I'm coding in Blujay on my mac, but received that same issue on a windows desktop, making me believe its a coding error, not a program one
System.out.println("Would you like to play this game? y/n");
Scanner scan = new Scanner(System.in);
playGame = scan.next().charAt(0);
while (playGame == 'y')
System.out.println("Please enter a number in 1-100 range");
userNumber= scan.nextInt();
while in Java, the while loop in the code below only cover(or goes purple / gets highlighted) the line with "while (playgame == y)", and the following print statement, but i need the whole program to be under a while loop so the game can repeat as long as the user says "y".
To make this valid Java code, you first need semicolons at the end of every statement. That's not the fix for your while loop, and maybe in you actual code you already have that, but I'm just pointing it out.
To make a while loop - or any kind of code block - cover multiple statements in Java, you use curly braces {}. Again, maybe your actual code has this, but the way you're wording your question makes me think you probably don't. So that's:
while (condition) {
statement1;
statement2;
...
}
Java does not care about indentation at all, you need the braces and semicolons to make this work.
Wrap the whole code in a while(true) statement and exit it when the user chooses to exit the game:
char playGame;
while (true) {
System.out.println("Would you like to play this game? y/n");
Scanner scan = new Scanner(System.in);
playGame = scan.next().charAt(0);
if (playGame != 'y') break;
System.out.println("Please enter a number in 1-100 range");
int userNumber = scan.nextInt();
System.out.println("You entered: " + userNumber); // or something else
}
Scanner kb = new Scanner(System.in);
String plt;
String msr;
double wgh;
System.out.println("'Welcome to interplanetary weight calculator.");
Thread.sleep(2500);
System.out.println("");
System.out.println("Please choose one planet for calculation:");
System.out.println("1.Venus 2.Mars 3.Jupiter");
System.out.println("4.Saturn 5.Uranus 6.Neptune");
System.out.print(">");
do {
while (!kb.hasNextLine()) {
System.out.println("That's not a planet!");
kb.nextLine(); // this is important!
}
plt = kb.nextLine();
} while (plt.equalsIgnoreCase("Venus"));
System.out.println("Thank you!Now will do calculation on " + plt); }}
I want to make a weight calculator between planets and I also want a spell checker too but when I write something, it just prints out "Thank you! Now, will do the calculation on ....".
It prints out integers too. I can't find where did I do wrong.
Essentially, what happens is that your loop will run once, you can enter something and it will then exit the loop because anything except "venus" (in any combination of upper and lower case) will exit the loop. This is why it will also print numbers, etc.
The solution to this might be to add an ! to the beginning of the condition. This will invert the condition, meaning now only entering "venus" will cause the loop to exit which will result in the program continuing to run everything below the loop. However, there's still not going to be any kind of error message. Spell-checking and error handling would be achieved differently.
I am trying to implement a simulator that has certain commands the user can input.
One of these commands is "s" which when entered should step through one instruction of the assembly file. However there is another instruction with the format "s num" where the user can define just how many instructions they want to step through.
I check for this
if(input.equals("s"))
{
//check for num next
if(user.hasNextInt())
{
input = user.next();
step(Integer.parseInt(input), assembler);
}
else
{
step(1, assembler);
}
}
However the problem is if the user only enters "s" the scanner will wait for the next input rather than just calling step. My idea is if there is an int after the s was input then proceed with the num step, other wise just call step.
Any help is greatly appreciated!
I would split the input into two parts and then treat it. For example,
String input = user.nextLine();
String array[] = input.split(" ");
if(array.length<2){
//check for `s`
}else{
//check for `s num`
}
you could try this:
if(input.equals("s"))
{
step(1, assembler);
}
else if(input.startsWith("s") && input.length() > 2)
{
step(Integer.parseInt(input.substring(input.indexOf(" ")+1)), assembler);
}
If control were to go inside the else if block, the current solution assumes that there is always a number after the String s with a white space delimiter in between them, but you can go on further and do more validations if necessary.
I've been working on a programming assignment that acts as a Scrabble dictionary for a while now. The program takes input from the user and outputs a file with a list of words, depending on what the user requests from a menu. The problem I've been having has to do with Scanner.nextLine().
I'm not aexactly sure why, but for some reason I have to press enter once sometimes before my code will take my input and store it as the variable. Essentially, I end up entering the input twice. I tried inserting Scanner.nextLine() around the code to "take up" the empty enter/spaces but it doesnt work, and I have to press enter multiple times to get it to process what I want.
Does anybody have any suggestions? I'd appreciate any and all help.
Here is a bit of the code:
System.out.println("Enter the length of the word you are" + " searching for.");
int n = -1;
while(!(n >=0)) {
if(in.hasNextInt())
n = in.nextInt();
else {
System.out.println("You have not entered a valid number.
Please enter a real number this time.");
in.nextLine();
}
}
in.nextLine();
System.out.println("Enter the first letter of the words" + " you are searching for.");
String firstLetter = "";
while(!(firstLetter.length() == 1)) {
if(in.nextLine().length() > 1) {
System.out.println("You have not entered a valid letter.
Please press enter and enter only one real letter.");
}
else if(in.hasNextInt()) {
System.out.println("Do not enter a number. Please enter one real letter.");
}
else {
in.nextLine();
firstLetter = in.nextLine();
break;
}
}
At the end of this, I have to press enter once and then input to get it to store anything in the variable firstLetter. I assume it has something to do with the nature of nextLine(), as the conditions using nextInt() give no issues.
It's because you're using both nextLine() and nextInt(), what's going on is that nextLine() is searching for a new line (enter) and nextInt will automatically stop the search if any integer is typed through System.in.
Rule of thumb: Just use Scanner.nextLine() for your input, then convert your string from Scanner.nextLine() accordingly through Integer.parseInt(string), etc.
I think you're overcompensating with too many nextLines. You may want to do that once to clear the line after the int is inputted, for example, to clear the newline, but the second time here just absorbs an extra line of input:
System.out.println("You have not entered a valid number. Please enter a real number this time.");
in.nextLine();//first time
}
}
in.nextLine();//this second time is unnecessary.
The same thing happens with your duplicate uses here:
in.nextLine();
firstLetter = in.nextLine();
break;
You should only add an extra in.nextLine() immediately between inputting nextSOMETHINGELSE() and another nextLine().
EDIT:
Additionally, note that whenever you call in.nextLine(), you are absorbing a line of input. For example, this line should be fixed:
if(in.nextLine().length() > 1){
because it reads in a line, using it up, and then checks whether that (now used-up) line is long enough.