I am trying to run a do...while while a condition is not met but for some reason my code keeps looping every time regardless of the value of the condition. I've checked my debugger and the value of the variable is correct and the conditions within the loop are met according to similar logic. For some reason the ! doesn't work. Here is my code
do
{
if(isRaceHorse.equalsIgnoreCase("Y"))
{
System.out.print("Please enter the number of races your horse has been in >> ");
numRaces = input.nextInt();
input.nextLine();
System.out.println("Your horse is named " + name + " it is a " + color + " horse born in " + birthYear + " and it has been in " + numRaces + " races.");
}
else if(isRaceHorse.equalsIgnoreCase("N"))
{
System.out.println("Your horse is named " + name + " it is a " + color + " horse born in " + birthYear + ".");
}
else
{
System.out.println("Please use Y for yes and N for no.");
System.out.print("Is your horse a race horse? Enter Y for yes and N for no >> ");
isRaceHorse = input.nextLine();
}
}while(!(isRaceHorse.equalsIgnoreCase("y")) || !(isRaceHorse.equalsIgnoreCase("n")));
Anybody have any ideas as to why this is not giving me what I want?
!(isRaceHorse.equalsIgnoreCase("y")) || !(isRaceHorse.equalsIgnoreCase("n"))
In English, this means the loop will continue as long as isRaceHorse is not equal to "y" or isRaceHorse is not equal to "n". Since it cannot be equal to both "y" and "n" at the same time, I'm pretty certain you want to use && instead:
!isRaceHorse.equalsIgnoreCase("y") && !isRaceHorse.equalsIgnoreCase("n")
Related
one problem I noticed is that the program crashes if you enter non digits even though there is a catch statement. can someone help me out? I can't seem to find the problem.
Can you also explain what I'm doing wrong and why it's wrong? Thank you in advance.
//previous code had an issue while I was creating a new scanner. it's correct now.
import java.util.*;
public class HighLow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numberOfAttempts = 0;
System.out.println("WIN THE THREE ROUNDS TO WIN THE GAME!.");
int theNumber = (int) (Math.random() * 10 + 1);
System.out.println("Round 1: I am thinking of a number between" + "\n" + "1 and 10, can you guess the number in " + "\n" + "less than 3 attempts?");
System.out.println("Type a number below and press enter.");
int guess = 0;
do {
try {
guess = scan.nextInt();
if (guess != theNumber) {
if (guess < theNumber) {
System.out.println("Sorry " + guess + " is too low, please try again");
}else if (guess > theNumber) {
System.out.println("Sorry " + guess + " is too high, please try again." );
}
numberOfAttempts = numberOfAttempts + 1;
}else {
System.out.println(guess + " is the correct answer. You got it on" + "\n" + "attempt number " + (numberOfAttempts + 1) + ". Proceeding to round 2.");
theNumber = (int) (Math.random() * 100 + 1);
System.out.println("\n" + "Round 2: I am thinking of a number between " + "\n" + "1 and 100, can you guess the number in " + "\n" + "less than 6 attempts?");
numberOfAttempts = 0;
int secondRoundGuess = 0;
do {
try {
secondRoundGuess = scan.nextInt();
if (secondRoundGuess != theNumber) {
if (secondRoundGuess < theNumber) {
System.out.println("Sorry " + secondRoundGuess + " is too low, please try again");
}else{
System.out.println("Sorry " + secondRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}
else {
System.out.println(secondRoundGuess + " is the correct answer. You got it on " + "\n" + "attempt number " + (numberOfAttempts + 1) + "." + "\n" + "Proceeding to round 3.");
System.out.println("\n" + "Round 3: I am thinking of a number between " + "\n" + "1 and 1000, can you guess the number in " + "\n" + "less than 10 attempts?");
theNumber = (int)(Math.random() * 1000 + 1);
numberOfAttempts = 0;
int thirdRoundGuess = 0;
do {
try {
thirdRoundGuess = scan.nextInt();
if (thirdRoundGuess != theNumber) {
if (thirdRoundGuess < theNumber) {
System.out.println("Sorry " + thirdRoundGuess + " is too low, please try again");
}else {
System.out.println("Sorry " + thirdRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}else{
System.out.println(thirdRoundGuess + " is the correct answer.");
System.out.println("You won the game, you are a badass." + "\n" + "I made this game and I cant even beat " + "\n" + "level 3.");
System.out.println("I am a newbie at programming and it's my " + "\n" + "fourth month on this java journey ." + "\n" + "I am looking for fellow newbies who are willing " + "\n" + "to learn and grow together (or advanced programmers " + "\n" + "who will not get annoyed by teaching newbies)." + "\n" + "If you get to this point in the game " + "\n" + "and see this message, hit me up via direct " + "\n" + "messaging, lets create a group where we can learn " + "\n" + "and grow together.");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
thirdRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 10);
System.out.println("Game over, you were so close. Try again");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
secondRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 6);
System.out.println("Game Over. Try again?");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
}while (numberOfAttempts != 3);
System.out.println("Game Over. Try again?");
scan.close();
}
}
The root cause of the problem is using scan.nextInt() inside the catch block. What is happening is guess = scan.nextInt(); just below the try is throwing an exception for non-integer input and the control enters the catch block where it encounters guess = scan.nextInt(); again which tries to consume the Enter from the last input causing the program to crash as Enter is not an int.
How to get rid of it?
You need to make two changes to get rid of the problem:
A. Use guess = Integer.parseInt(scan.nextLine()); in which scan.nextLine() will also consume Enter.
B. Comment out the line, guess = scan.nextInt(); as shown below:
} catch (Exception e) {
System.out.println("Please enter a number.");
//guess = scan.nextInt();
}
This is the exception stack trace you get when you run the code:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at HighLow.main(HighLow.java:137)
When you handle the exception first time the user types in a non-numeric value, the exception gets handled below:
catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
When it reaches guess = scan.nextInt();, the previous non-numeric value is still present in the scanner. And when it tries to get an integer out of the scanner when it has a non-numeric value, it throws another InputMismatchException inside catch that is not handled.
I want to display the sum of two numbers beside the equal sign.
Scanner scan = new Scanner(System.in);
int i ;
System.out.println("enter a number: " );
i = scan.nextInt();
int a = i - 1 ;
while(a >= 1){
System.out.println(i +" + "+ a + " = " );
//i want to display the sum of two numbers beside the equal sign.
i =i + a ;
System.out.println(i);
a --;
// how can I display the answer beside the equal sign?
}
}
}
How can I display the answer beside the equal sign?
Change your first println to print.
As per your question I think you are most probably asking how we can show the sum of two numbers in the print statement.
So in your code after "=" you just need to add (i+a) this will sum the value of i and a.
System.out.println(i +" + "+ a + " = " + (i+a)).
I hope this answers your question.
System.out.println() method prints a "newline character" (\n) right after its' input.
There is another method that does not do this:
System.out.print()
You should change
System.out.println(i +" + "+ a + " = " ); to
System.out.print(i +" + "+ a + " = " ); this.
This is my first time posting to this site, so if I get any formatting wrong, please be easy on me Lol
I'm writing a Java program that needs to look up a part number from an inventory, and then print the part number along with the data following it. The code is only printing out the information at the top of the file, and then repeating my else statement 5 times.
Here is the code:
package inventory;
import java.util.Scanner;
import java.io.*;
public class inventory
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
// File Information
String parts;
File inventoryFile;
FileWriter inventoryFW;
PrintWriter inventoryPW;
Scanner inventorySC;
//User Information
String userChoice;
// Part Information
String partID, partFileID, partFileDesc, partFileLoc, partDesc, partLoc;
double partFilePrice, partPrice;
int partFileQuan, partQuan;
userChoice = ("A");
// Loop
if(userChoice.equalsIgnoreCase("Q"))
System.exit(0);
else
while(!userChoice.equalsIgnoreCase("Q"))
{
// Get Employee Decision
System.out.println("Please choose a letter: \n"
+ "L - Look Up Part \n"
+ "A - Add to Inventory File \n"
+ "E - Erase From Inventory File \n"
+ "G - Generate a Sales Slip \n"
+ "I - Add Quantity to Inventory File \n"
+ "D - Display Inventory \n"
+ "Q - Quit \n"
+ "Selection: ");
userChoice = keyboard.nextLine();
// Process User Choice
if(userChoice.equalsIgnoreCase("L"))
{ // Choice L
// Look Up Part
System.out.println("Enter Part I.D. Number: ");
partID = keyboard.nextLine();
// Do until partID is equal to partFileID
parts = "inventoryFile.txt";
inventoryFile = new File(parts);
inventorySC = new Scanner(inventoryFile);
partFileID = "0";
partFileDesc = "0";
partFilePrice = 0;
partFileLoc = "0";
partFileQuan = 0;
while(inventorySC.hasNextLine())
{
String lineFromFile = inventorySC.nextLine();
if(lineFromFile.contains(partID))
{
partFileDesc = inventorySC.nextLine();
partFilePrice = inventorySC.nextDouble();
inventorySC.nextLine();
partFileLoc = inventorySC.nextLine();
partFileQuan = inventorySC.nextInt();
System.out.println("Part I.D. Number: " + partFileID + "\n");
System.out.println("Part Description: " + partFileDesc + "\n"
+ "Part Price: " + partFilePrice + "\n"
+ "Part Location: " + partFileLoc + "\n"
+ "Part Quantity: " + partFileQuan);
}
else
System.out.println("Sorry, this part cannot be found");
}
}
}
}
}
And here is the datafile I am trying to pull from:
1234567
Clutch
45.68
Warehouse B
8
1234
Brake
66.78
Warehouse A
4
For example, if the user entered part number "1234" the program should search for that part number in the file, and then display:
1234
Brake
66.78
Warehouse A
4
Sorry about any poor code formatting, I have been fighting with this for a while now.
Any help would be greatly appreciated.
There are a few issues.
The contains will have multiple matches.
You will print "not found every line" you don't find.
You are not breaking out of the loop.
boolean found = false;
while(inventorySC.hasNextLine()){
String lineFromFile = inventorySC.nextLine();
if(lineFromFile.equals(partID)) {
partFileDesc = inventorySC.nextLine();
partFilePrice = inventorySC.nextLine();
partFileLoc = inventorySC.nextLine();
partFileQuan = inventorySC.nextLine();
System.out.println("Part I.D. Number: " + partFileID + "\n");
System.out.println("Part Description: " + partFileDesc + "\n"
+ "Part Price: " + partFilePrice + "\n"
+ "Part Location: " + partFileLoc + "\n"
+ "Part Quantity: " + partFileQuan);
found = true;
break;
}
}
if(!found)
System.out.println("Sorry, this part cannot be found");
Your issue is that you are only skipping to the next line if the part list doesn't contain your part value. You actually want to skip down 5 lines if the part is not on the 'next line'.
In your "else" statement, you'll just want to call the inventorySC.nextLine(); 4 more times to get to the next place in the file you actually want to check for a part number.
If you want the 'not found' condition to reflect more effectively that the part number actually wasn't found at all, you'll want to move that message to after it could have scanned the whole file. Set a boolean with a name like 'found' to false before the file scan. If you enter your 'contains' condition because there is a part number in the file that contains your input, set the 'found' equal to true.
At the end if the 'found' is still 'false', you can output the 'not found' message.
As MadProgrammer commented above, you'll need to use 'equals' instead of 'contains'- this is why you match on the first entry. When you find a match and output it, you need to exit the while loop using a 'break' - otherwise you output the else value for each line left over (as is happening to you). But there is one other problem in that you may need to read an entire record - not just the first line of the record - when there is no match so you don't get screwed up when an inventory item has a quantity of 1234 when searching for part number 1234.
So here's a simple code to adjust the right "st", "nd", "rd", "th" with the input number. It's placed in a loop for a reason. Nevermind that.
System.out.println("How many?");
int num = x.nextInt();
for(int i=1;i<=num;i++){
System.out.print("Enter the " + i);
System.out.println(i==1? ("st"):(i==2? "nd":i==3? "rd":"th") + " number!");
}
when num is input as 5 here's the output:
Enter the 1st
Enter the 2nd number!
Enter the 3rd number!
Enter the 4th number!
Enter the 5th number!
Question is where's "number!" with the case "1st"??
You forgot a pair of braces, change:
System.out.println(i==1? ("st"):(i==2? "nd":i==3? "rd":"th") + " number!");
to:
System.out.println((i==1? ("st"):(i==2? "nd":i==3? "rd":"th")) + " number!");
^ ^
Notice the condition of your print :
i == 1 ? ("st") : ((i==2? "nd":i==3? "rd":"th") + " number!")
^ ^
true false
I added parenthesis to the false part so it is easier for you to understand.
I believe what you want is :
(i == 1 ? ("st") : (i==2? "nd":i==3? "rd":"th")) + " number!"
^
Now we add it to the result of what is returned for the condition.
System.out.println(i==1? ("st"):(i==2? "nd":i==3? "rd":"th") + " number!");
is the source of the problem. Do you see how you have + " number!"); after the : that separates the 1st and the 2nd/3rd? You need to have this twice.
System.out.println(i==1? ("st number"):(i==2? "nd":i==3? "rd":"th") + " number!");
or
System.out.println((i==1? ("st"):(i==2? "nd":i==3? "rd":"th")) + " number!");
I am having 2 main issues. the first is I cannot make it loop back around for another persons details to be input. the second is I cannot get the shortestHight or shortestName to be recorded. (This is an assignment, I would like help and not the answer please)
{
System.out.println("Do you want to enter another person? Y/N ");
answer = KB.next();
while ("yes".equals(answer) || "Yes".equals(answer));
System.out.println("Enter a Name ");
name = KB.next();
System.out.println("Enter " + name + "'s hight in meters");
hight = KB.nextFloat();
while (hight <= 0.8 || hight >= 2.5)
{
System.out.println(name + "must be between 0.8 and 2.5 meters");
System.out.println("Enter " + name + "'s hight in meters");
hight = KB.nextFloat();
}
}
if (hight >= tallestHight)
{
tallestHight = hight;
tallestName = name;
}
else if (hight <= shortestHight)
{
shortestHight = hight;
shortestName = name;
}
System.out.println("The tallest persone is " + tallestName + " at a hight of " + tallestHight);
System.out.println("And The shortest persone is " + shortestName + " at a hight of " + shortestHight);
}
}
What is wrong is this:
while ("yes".equals(answer) || "Yes".equals(answer));
This will not result in waiting for another input. It will hang your program as soon as someone enters Yes or yes. It means while answer is yes do nothing. And it will do nothing forever (as answer won't change when application is doing nothing).
I think it should look like this:
boolean getAnotherPerson = true;
do
{
System.out.println("Enter a Name ");
// and so on.
System.out.println("And The shortest persone is " + shortestName + " at a hight of " + shortestHight);
System.out.println("Do you want to enter another person? Y/N ");
answer = KB.next();
if ("n".equalsIgnoreCase(answer) || "no".equalsIgnoreCase(answer))
{
getAnotherPerson = false;
}
} while (getAnotherPerson);
And as for shortest person: it will not work with only one person inserted because your using if-else. So you either update highest or shortest person info. Remove the else keyword and it should be fine.
Changes are mentioned in comments
String tallestName, shortestName;
double tallestHight = Double.MIN_VALUE, shortestHight = Double.MAX_VALUE;
while (true)
{
System.out.println("Do you want to enter another person? Y/N ");
answer = KB.next();
// this would loop infinitely if "Yes" or "yes" entered
// while ("yes".equals(answer) || "Yes".equals(answer));
// instead you might want this - exit if yes not entered
if (!(answer.equals("yes") || (answer.equals("Yes"))) {
break;
}
System.out.println("Enter a Name ");
name = KB.next();
System.out.println("Enter " + name + "'s hight in meters");
hight = KB.nextFloat();
while (hight <= 0.8 || hight >= 2.5)
{
System.out.println(name + "must be between 0.8 and 2.5 meters");
System.out.println("Enter " + name + "'s hight in meters");
hight = KB.nextFloat();
}
// compare within loop not outside
if (hight >= tallestHight)
{
tallestHight = hight;
tallestName = name;
}
// only if - not else if as they are 2 separate comparisons
if (hight <= shortestHight)
{
shortestHight = hight;
shortestName = name;
}
}
System.out.println("The tallest persone is " + tallestName + " at a hight of " + tallestHight);
System.out.println("And The shortest persone is " + shortestName + " at a hight of " + shortestHight);