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);
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 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")
I cannot get the variable adjustedCharge to print out (the text is printed but not the value) I have tried to trace but still cannot get it to print properly. No errors are present either.
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
//Declare scanner
Scanner input = new Scanner(System.in);
//Prompt for information
System.out.print("Customer's name:");
String name = input.nextLine();
System.out.print("Customer's address:");
String address = input.nextLine();
System.out.print("Customer's phone number:");
String phone = input.nextLine();
System.out.print("Customer's licence number:");
String licence = input.nextLine();
System.out.print("Customer's credit card number:");
String ccard = input.nextLine();
System.out.print("Credit card expiry date (MM/YYYY):");
String expiry = input.nextLine();
System.out.print("Hire length (in days):");
int hire = Integer.parseInt(input.nextLine());
System.out.print("Make/Model:");
String model = input.nextLine();
System.out.print("Registration of car:");
String rego = input.nextLine();
System.out.print("Hire rate (per day) Either S, M, L:");
char inputRate = input.nextLine().charAt(0);
System.out.print("Total days hired out:");
int totalDays = Integer.parseInt(input.nextLine());
//
double dtotalDays = totalDays;
double surcharge = dtotalDays - hire;
//Daily hire rate / Stage 2
double rate = 0;
if (inputRate == 'S' || inputRate == 's'){
rate = (char) 80.0;
}
if (inputRate == 'M' || inputRate == 'm'){
rate= 110.0;
}
if (inputRate == 'L' || inputRate == 'l'){
rate= 140.0;
}
//Calculate late fees
double penalty = rate * (surcharge * 2);
//Start Stage 3
double dCost=0;
double tCost=0;
StringBuilder dDetail = new StringBuilder("The damage Details are:" + "\n");
StringBuilder tDetail = new StringBuilder("The traffic fines are:" + "\n");
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("<<<Enter one of the following commands:>>>");
System.out.println("A - Damage Repair");
System.out.println("B - Traffic Infringement");
System.out.println("X - Exit Menu");
String schoiceEntry = input.next();
char choiceEntry = schoiceEntry.charAt(0);
//Integer.parseInt(input.nextLine());
double damageCost = 0;
switch (choiceEntry){
case 'A':
case 'a':
input.nextLine();
System.out.println("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.println("Enter the damage cost:");
damageCost = input.nextInt();
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append("-" + damageDetail + "\n");
dCost = dCost + damageCost;
System.out.println("----------------------------------");
break;
case 'B':
case 'b':
input.nextLine();
System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.println("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append("-" + trafficDetail + "\n");
tCost = tCost + trafficCost;
System.out.println("----------------------------------");
break;
case 'X':
case 'x':
quit = true;
System.out.print("***Menu entry has been terminated***" + "\n");
//System.out.printf("Total traffic cost is: %75s\n", "$" + tCost + "\n");
//System.out.printf("Total Damage cost is: %77s\n", "$" + dCost + "\n");
//System.out.printf(tDetail + "\n");
//System.out.print(dDetail + "\n");
break;
default:
System.out.print("Please enter either a valid menu selection (A, B, or X):" + "\n");
break;
}
}
double dhire = hire;
double charge = dhire*rate;
double adjustedCharge = charge + penalty;
//Print summary
System.out.println("---------------------------------------------"+
"------------------------------------------------------\n" +
"***CUSTOMER DETAILS:***\n");
System.out.printf("Name: %93s\n", name);
System.out.printf("Address: %90s\n", address);
System.out.printf("Phone Number: %85s\n", phone);
System.out.printf("Licence Number: %83s\n", licence);
System.out.printf("Credit Card Number: %79s\n", ccard);
System.out.printf("Credit Card Expiry: %79s\n", expiry);
System.out.println( "\n***CAR HIRE DETAILS:***\n");
System.out.printf("Make/Model: %87s\n", model);
System.out.printf("Registration Number: %78s\n", rego);
System.out.printf("Hire Length (days): %79s\n", model);
System.out.printf("Daily Hire Rate: %82s\n", rate);
System.out.printf("Basic Hire Charge: %80s\n\n", charge);
System.out.printf("Days hired: %87s\n", totalDays);
if (totalDays == hire){
System.out.printf("Late Return Surcharge: %76s\n", "$0.00");
}
if (totalDays > hire){
System.out.printf("Late Return Surcharge: %76s\n", + penalty);
}
System.out.printf("Adjusted Hire Charge: %77s\n", "\n", "$" + adjustedCharge + "\n");
System.out.print(dDetail + "\n");
System.out.printf("Total damage cost is: %78" + "s\n", "$" + dCost + "\n");
System.out.printf(tDetail + "\n");
System.out.printf("Total traffic fines incurred: %70s\n", "$" + tCost + "\n");
System.out.printf("Final hire charge: %79s\n", "$" + (adjustedCharge + dCost + tCost));
}
}
I just changed the way you printed out the adjustedCharge so you can still use printf
System.out.printf("Adjusted Hire Charge: %77s","$");
System.out.printf("%.1f",adjustedCharge);
System.out.printf("\n");
With printf you need to format the value you're printing and in this case, because you're trying to print a double, you'll need to format it with %f
I also noticed that my previous answer messed up the spacing you had for the rest of your output. So here's the fixed solution! Just change up the spacing to however you'd like
Or you can
use
Pass two arguments to printf
System.out.printf("Adjusted Hire Charge: %77s\n", "$" + adjustedCharge + "\n")
instead of
System.out.printf("Adjusted Hire Charge: %77s\n", "\n", "$" + adjustedCharge + "\n");
Apologies for the silly question, I am currently struggling to learn java. I need this code to work so that it will repeat unless '0' is entered for the studentNumber, I'm unsure of how to get the "please enter student number" part to work when I have to declare the int for that before the if statement? I'm not sure if I've approached this completely wrong or what, but I need to be able to repeat the data entry unless "0" is entered as the studentNumber. Thanks for any help!
class Main {
public static void main( String args[] ) {
int studentNumber = BIO.getInt();
if(studentNumber > 0) {
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
}
Use while()
while(studentNumber > 0){
studentNumber = BIO.getInt();
.........
........
}
See also
while in Java
Use while() instead of if, along with the following changes:
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.getInt();
while(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
System.out.print("#Please enter the student number : ");
studentNumber = BIO.getInt();
}
System.out.print("#End of data");
This, as opposed to the other answers, will ensure that even in the first iteration, you perform the check (and promt the user for the student number).
Using Scanner to get the input from the user and process the input value
import java.util.Scanner;
public class ConditionCheck {
public static void main(String[] args) {
Scanner BIO = new Scanner(System.in);
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.nextInt();
if(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.nextInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.nextInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
You should be using a while statement and do something as below:
class Main
{
public static void main( String args[] )
{
int studentNumber = 1;
While(studentNumber > 0)
{
studentNumber = BIO.getInt();
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber + " ex = " + examMark + " cw = " + courseWork + " mark = " + average);
}
else
{
System.out.print("#End of data");
}
}
}
I have no idea on how to output a draw from a vote any help on with this would be appreciated.
At the moment it will allow a user to select the amount of candidates and then the user inputs details. Then the user will enter a vote, which is the candidate number, and type 999 to finish. The output will be the winner or winners(draw)the candidates with details and votes and the amount of spolit votes that is votes not in the range declared at the start.
int x;
char highestChar = '1';
char nextHighestChar = '1';
String alpha = "123456";
int largest=intVoteCount[1];
int nextLargest=intVoteCount[1];
for( x=1; x<=range; x++){
if(intVoteCount[x]>largest){
largest = intVoteCount[x];
highestChar = alpha.charAt(intLoopCount);
}
if(intVoteCount[x]>highestChar){
nextLargest = intVoteCount[x];
nextHighestChar = alpha.charAt(intLoopCount);
}
}
System.out.println("The winner is Candidate number "+ highestChar + " with " + largest + " votes.");
System.out.println("The winner is Candidate number "+ nextHighestChar + " with " + nextLargest + " votes.");
System.out.println("-----------------------------");
System.out.println("The Candidate votes are as follows.");
for (intLoopCount = 1; intLoopCount <= range; intLoopCount++) {
// Display all records.
// New Instance
System.out.println("");
System.out.println("Candidate " + intLoopCount + " "
+ strCandidateTitle[intLoopCount] + " "
+ strCandidateFirstname[intLoopCount] + " "
+ strCandidateSurname[intLoopCount] + " votes "
+ intVoteCount[intLoopCount]);
}
System.out.println("-----------------------------");
System.out.println("Vote Count Spolit: " + intVoteCountSpolit);
}
}
If largest == nextLargest you have a draw, so print out an appropriate message saying so; otherwise, you have an explicit winner.