Using Scanner object for spell checking as a newbie - java

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.

Related

How to stop a user from entering a letter in a switch case when the letter is the first input entered

When using a switch case with integers, I am able to successfully stop the user from crashing the program with a try/catch when they enter a letter (a, b, c, etc, not case specific). However, I can only stop it after an integer is entered. For this example, it is NOT my actual code, it is only an example as it is a general question. Secondly, I want to try and get it working with suggestions, not having it done for me:
int choice
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a number");
System.out.println ("1: Example one");
System.out.println ("2: Example two");
System.out.println ("0: Exit");
choice = scan.nextInt();
Loop: for (;;)
{
switch (choice)
case 1: System.out.println ("Example one successful");
choice = scan.nextInt();
break;
case 2: System.out.println ("Example two successful");
choice = scan.nextInt();
break;
case 0: System.exit (0);
break Loop;
default: try
{
System.out.println ("Please enter a number")
choice = scan.nextInt();
}
catch (InputMismatchException error)
{
System.out.println ("Not a valid number: " + error);
choice = scan.nextInt();
}
If the user enters a "1", it outputs the proper text inside the case 1 block. The same goes for case 2 and case 0 to exit. It will loop properly and continuously like this:
Enter a number: 1
Example one successful
Enter a number: 1
Example one successful
Enter a number: 2
Example two successful
Enter a number: ghdrf
Not a valid number: java.util.InputMismatchException
Enter a number: 0
The try/catch works in catching the wrong input, all the other case work. The problem is if the user never enters an integer from the start and enters a letter instead. It will throw the InputMismatchException right away. The try/catch doesn't even try to catch it.
My thinking was because I assigned the scanner to read an integer from the start. I tried to start there. I originally tried this between the loop label and the switch statement as it is the only place I could put it to not get an error:
Loop: for (;;)
{
String letter = input.nextLine();
if(letter.matches("[1-9]*")
{
choice = Integer.valueOf(letter);
}
else
{
System.out.println("Invalid input");
}
switch (choice)
...
This worked somewhat in the same way as my try/catch except it was simply printing "invalid input" with each selection (because of my print statement, I know that). But the same problem was occurring. If a letter was input instead of an integer right off the bat, it would throw an InputMismatchException. I have a feeling it has something to do with what is in the scanner. I've tried experimenting with "next(), nextLine(), nextInt(), equals()" and I've tried parsing with "Integer.valueOf()" trying to get the current line in the scanner to check it or parse it.
This leads me to my questions:
Am I correct to assume that the scanner is reading the input and throwing the exception before I have a chance to catch it?
How do I read the first line in the scanner at the beginning of the program in order to check if it is an integer or a String? I'm not a big fan of skipping the first line because then it causes the user to have to input their number twice in order for the program to print out a message such as:
Enter a number: 1
Enter a number: 1
Example one successful
Any input is greatly appreciated, thank you!
Question #1: no. The problem is, that the exception occurs in those lines which are not surrounded by try-catch (e. g. before the loop, in case 1 or case 2).
Question #2: to read a line, use Scanner#nexLine(). There's no need to have the user to perform his input twice.
Hint: write a method that requests an int value from the user and that returns only, if he entered a correct value.
You have 2 calls to next int. You're only catching exceptions from one of them. You need to do it for both.
I'd put some thought into reorganizing this code a bit. You don't really need two calls to nextInt. You can do it with one by changing what things are in the loop and what aren't. Since you're a beginner I'll let you think about that for a bit rather than hand you the answer.

How do I create a while loop in java that will end the game once the two user inputs match?

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

Creating while-loop with nested loops in it

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
}

Why does this While loop cycle twice?

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]*");

How to return to a specific line of code in java

OK so this is my first post here. (Be kind to me :)) I'm like two weeks old to java and wanted to create an app that can do the jobs of a total, average and average grader.
My question here is. How can I return to a specific line of code after one operation has ended
Eg: I want the code to runString menu1="Input the number of the operation you desire "; after the total or average has been found.
Thanks in advance
import java.util.Scanner;
public class grader
{
public static void main (String args[])
{
Scanner input=new Scanner(System.in);
System.out.println ("Input your Chemistry marks");
float a= input.nextFloat();
System.out.println ("Input your Biology marks");
float b= input.nextFloat();
System.out.println ("Input your Physics marks");
float c= input.nextFloat();
String menu1="Input the number of the operation you desire ";
String op1="1. Total ";
String op2="2. Average ";
String op3="3. Grade ";
String op4="4. Exit ";
System.out.println (menu1+op1+op2+op3+op4);
Scanner menuselect=new Scanner(System.in);
int option= input.nextInt();
float tot=(a+b+c);
float avg=((a+b+c)/3);
if (option==1)
System.out.println ("Your total is "+tot);
else if (option==2)
System.out.println ("Your average is "+avg);
else if (option==3)
if (avg<0.0)
System.out.println ("Please input proper data");
else if (avg<=49.9)
System.out.println ("Fail");
else if (avg<=69.9)
System.out.println ("Pass");
else if (avg<=100.0)
System.out.println ("Excellent");
else
System.out.println ("Please input proper data");
}
}
You should use the do-while loop. How it works is it executes some code, checks to see if a condition evaluates to true, and if so, executes the code again.
do {
//your code here
}
while (/*some condition*/);
Usually when you want to repeat one or more lines of code, you do so using a loop. In general, a loop is set up like this:
while(loopGuard){
//code to repeat
}
Where loopGuard is some boolean statement that gets updated inside your loop. The code inside the loop will continue executing until your loopGuard statement is no longer true.
In your case, you may want to loop until the user presses a certain button, until it has run a certain number of times, or any other arbitrary reason you have chosen. The main thing to remember is to make sure that your loop guard will eventually become false, otherwise you'll find yourself in an infinite loop.
In your case you should use a while loop with the usage of continue and break. A second option, you can use a labeled break statement (explained here).
Btw, in java language there a goto keyword. But it's not implemented (or removed). Read here for more details.
I would suggest a do - while loop . A do while loop runs at least once , which is necessary as you're program needs to be run at least once . Put all the statements from Input the operation number to the calculating statements under do while loop . It should work out just fine .

Categories