Calculate the total price of acquiring multiple cars - Java - java

Here is my code:
double carsPrice = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of cars you would like to drive");
String [] numberOfCars = new String[sc.nextInt()];
while (numberOfCars.length > 5) {
System.out.println("Enter a number that is less than 5 and try again");
numberOfCars = new String[sc.nextInt()];
}
System.out.println("Enter the names of cars you would like to hire");
String [] chosenCarNames = new String[5];
sc.nextLine();
for (int i=0; i<numberOfCars.length; i++) {
int nameA = i+1;
System.out.println("Enter name of car " + nameA);
chosenCarNames [i] = sc.nextLine();
while ("lamborghini".equals(chosenCarNames[i]) && "toyota".equals(chosenCarNames[i]) && "audi 5".equals(chosenCarNames[i])) {
if (!"lamborghini".equals(chosenCarNames[i]) && !"toyota".equals(chosenCarNames[i]) && !"audi 5".equals(chosenCarNames[i])) {
System.out.println("Name of car " + nameA + " is invalid. Please try again");
chosenCarNames[i] = sc.nextLine();
}
}
}
if ("lamborghini".equals(chosenCarNames[i])) {
carsPrice = 59;
}
else if ("toyota".equals(chosenCarNames[i])) {
carsPrice = 49;
}
else {
carsPrice = 39;
}
I have made a java program that asks customers to enter the number of cars they would like to hire and after that the program should allow the user to enter the names of cars they would like to hire depending on the number of cars they would like to hire. My problem is that if the customer wants to hire more than one car, I am not able to calculate the total price the customer has to pay. If the customer wants to hire only one car, I have used if statements to calculate and display the total number of money the customer has to pay

You could move the price calculation into the loop and accumulate it:
for (int i = 0; i < numberOfCars.length; i++) {
int nameA = i+1;
System.out.println("Enter name of car " + nameA);
chosenCarNames [i] = sc.nextLine();
// Input validation omitted for brevity
if ("lamborghini".equals(chosenCarNames[i])) {
carsPrice += 59;
}
else if ("toyota".equals(chosenCarNames[i])) {
carsPrice += 49;
}
else {
carsPrice += 39;
}
}

This is some interesting logic here:
while ("lamborghini".equals(chosenCarNames[i]) && "toyota".equals(chosenCarNames[i]) && "audi 5".equals(chosenCarNames[i])) {
If the entered value was "lamborghini", then the first part would be true, but then how could it also be equal to "toyota" and "audi" at the same time?
If the intention was to only allow "lamborghini", "toyota", or "audi 5", then move that compound boolean expression from the inner if statement out to the while loop, and get rid of the inner if:
System.out.println("Enter name of car " + nameA);
chosenCarNames [i] = sc.nextLine();
while (!"lamborghini".equals(chosenCarNames[i]) && !"toyota".equals(chosenCarNames[i]) && !"audi 5".equals(chosenCarNames[i])) {
System.out.println("Name of car " + nameA + " is invalid. Please try again");
chosenCarNames[i] = sc.nextLine();
}

Related

Using do-while loop to send an error message when input is out of bounds

Here I am using a do while loop to execute a program that allows the user to score student scores in an array and then print them. I am struggling with implementing a system that sends an error message when the user inputs a number below 0 or above 100 and then lets the user try again.
import java.util.Scanner;
public class storeScore {
public static void main(String [] args) {
Scanner input = new Scanner (System.in);
int scores [] = new int [7];
int numberOfStudents = 7;
//User input all scores. For loop works by asking for user input until it reaches the number as input in numberOfStudents.
do
{
for(int i = 0; i<numberOfStudents; i++) {
scores[i] = input.nextInt();
if (i == 0) {
System.out.print("Enter the score for the 1st student: ");
}
else if (i == 1) {
System.out.print("Enter the score for the 2nd student: ");
}
else if (i == 2) {
System.out.print("Enter the score for the 3rd student: ");
}
else if (i >= 3) {
System.out.print("Enter the score for the " + (i+1) + "th student: ");
}
}
//Error output if input is incorrect
}
while (scores[i] < 0 || scores[i] > 100) {
System.out.println("Input out of bounds. Score can only be between 0 and 100");
}
//Printing all scores.
System.out.println("Thank you for your input. Your entered scores are: ");
for (int i=0; i<numberOfStudents; i++)
{
System.out.print(scores[i] + ", ");
}
input.close();
}
}
You have your error message printing in a while loop without any way of breaking out of that loop.
Try capturing your user's input as an int variable first that you can check to see if it's valid before assigning it to scores[].
for(int i = 0; i<numberOfStudents; i++) {
String message;
if (i == 0) {
message = "Enter the score for the 1st student: ";
}
else if (i == 1) {
message = "Enter the score for the 2nd student: ";
}
else if (i == 2) {
message = "Enter the score for the 3rd student: ";
}
else if (i >= 3) {
message = "Enter the score for the " + (i + 1) + " student: ";
}
System.out.println(message);
int score = input.nextInt();
//Now check if the input value is valid
while (score < 0 || score > 100) {
System.out.println("Input out of bounds. Score can only be between 0 and 100");
System.out.println(message);
score = input.nextInt();
}
score[i] = score;
}
Now, the loop will print the message for student i, then take in the score. If the score is invalid, the while loop will print out the error message, and take input again. If the input is valid this time, the while loop breaks and assigns the new score to student i, otherwise it reprints the error message and takes input again.

How would I use a while loop to get multiple inputs?

I'd like to make a program that asks the user to enter the number of customers for booking tickets, reads the entered number, performs the loop to ask the age of each customer, and decide the unit price for each customer.
my code so far only has the if else statements:
if (customerP <4){
System.out.println("The unit Price of customer 1 is: 0");
}else {
if(customerP <13) {
System.out.println("The unit price of customer 1 is: 5");
}else {
if(customerP <19) {
System.out.println("The unit price of customer 1 is: 8");
}else {
System.out.println("The unit price of customer 1 is: 10");
}
}
}
How do I add a while loop to ask the to ask the age for each customer?
Here you go:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter No of Customers: ");
int noCustomers = scanner.nextInt();
if (noCustomers < 1) {
throw new IllegalArgumentException("No of Customers has to be 1 or greater");
}
int[] customerAges = new int[noCustomers];
for (int i = 0; i < noCustomers; i++) {
System.out.println("Enter age for customer: " + i);
customerAges[i] = scanner.nextInt();
}
System.out.println("Ages: " + Arrays.toString(customerAges));
Below provides code using while loop
Scanner sc = new Scanner(System.in);
int customerCount = sc.nextInt();
int[] ageOfCustomers = new int[customerCount];
int i=0;
while(customerCount-- > 0) {
ageOfCustomers[i++] = sc.nextInt();
}
System.out.println(Arrays.toString(ageOfCustomers));

My program is breaking out of the first for loop after one iteration

Here is my code. It asks user for terms and definitions, then quizzes the user. (It tells the user the term, and the user types in the answer.) The program uses arrays to store the terms and definitions. If the user doesn't get the definition correct, the program asks the user whether they want to study it again. If so, they will type in yes, and the program will store it on a separate array. After the program quizzes the users on all the terms and definitions, round 2 starts, where the program will quiz the user only on the starred definition. The problem is, the code is only running the for loop (that quizzes the user on round 1) once, and then skips onto round 2. Why is that so? I already tried looking at other people's questions and answers, but I can't seem to find the problem in my code.
import java.util.*;
public class Ptcreate {
public static void main(String[] args) {
String term;
String definition;
Scanner userInput = new Scanner(System.in);
System.out.println("How many terms would you like to study?");
int number_terms = userInput.nextInt();
String[] term_array = new String[number_terms];
String[] def_array = new String[number_terms];
String[] star_array = new String[number_terms];
String[] stardef_array = new String[number_terms];
System.out.println("Now, enter the " + number_terms + " terms now.");
for (int i = 0; i < number_terms; i++) {
term_array[i] = userInput.next();
}
System.out.println(
"Now, enter all the definitions, in the correct order such that it matches the order of the terms you entered.");
for (int i = 0; i < number_terms; i++) {
def_array[i] = userInput.next();
}
System.out.println("Ok. Now for the testing!");
for (int i = 0; i <= number_terms; i++) { // the for loop that isn't
// working.
System.out.println("What is definition " + (i + 1));
String answer = userInput.next();
if (answer.equals(def_array[i])) {
System.out.println("Correct");
star_array[i] = "null";
stardef_array[i] = "null";
} else if (!answer.equals(def_array[i])) {
do {
System.out.println("Incorrect.");
System.out.println("Would you like to study this term again? Type y or n.");
String bool = userInput.next();
if (bool.equals("y")) {
star_array[i] = term_array[i];
stardef_array[i] = def_array[i];
} else if (bool.equals("n")) {
star_array[i] = "null";
stardef_array[i] = "null";
}
System.out.println("What is the definition " + (i + 1));
answer = userInput.next();
} while (!answer.equals(def_array[i]));
if (answer.equals(def_array[i])) {
System.out.println(
"Correct"); /*
* when the user finally enters the
* right definition, the program skips
* to the code below
*/
}
}
System.out.println("Now, time for testing definitions you starred!");
for (int z = 0; z < number_terms; z++) {
if (star_array[z].equals("null")) {
break;
} else {
System.out.println("What is the definition of " + star_array[z] + " ?");
String star_answer = userInput.next();
if (star_answer.equals(stardef_array[z])) {
System.out.println("Correct.");
} else if (!star_answer.equals(stardef_array[z])) {
do {
System.out.println("Incorrect. Please try again.");
System.out.println("What is the definition of " + star_array[z] + " ?");
star_answer = userInput.next();
} while (!star_answer.equals(stardef_array[z]));
}
}
}
}
}
}
for (int i = 0; i <= number_terms; i++)
You have number_terms + 1 iterations. Replace with
for (int i = 0; i < number_terms; i++)
The bug is that the for-loop that you have tagged with the comment "the for loop that isn't working" is not looping through all the definitions. This for-loop after handling the first definition it moves on to handling round 2 instead of continuing the loop to the 2nd definition and so on. The fix requires that you place the closing bracket of this for-loop before the print statement "Now, time for testing definitions you starred!" as shown below. I have added the comment "end for-loop to ensure looping of all definitions" at the for-loop closing bracket that I have moved up in the code below. In addition this for loop's iteration condition should be 'i < number_terms' as the previous posters have indicated.
import java.util.*;
public class Ptcreate {
public static void main(String[] args) {
String term;
String definition;
Scanner userInput = new Scanner(System.in);
System.out.println("How many terms would you like to study?");
int number_terms = userInput.nextInt();
String[] term_array = new String[number_terms];
String[] def_array = new String[number_terms];
String[] star_array = new String[number_terms];
String[] stardef_array = new String[number_terms];
System.out.println("Now, enter the " + number_terms + " terms now.");
for (int i = 0; i < number_terms; i++) {
term_array[i] = userInput.next();
}
System.out.println(
"Now, enter all the definitions, in the correct order such " +
"that it matches the order of the terms you entered.");
for (int i = 0; i < number_terms; i++) {
def_array[i] = userInput.next();
}
System.out.println("Ok. Now for the testing!");
for (int i = 0; i < number_terms; i++) { // the for loop that isn't
// working.
System.out.println("What is definition " + (i + 1));
String answer = userInput.next();
if (answer.equals(def_array[i])) {
System.out.println("Correct");
star_array[i] = "null";
stardef_array[i] = "null";
} else if (!answer.equals(def_array[i])) {
do {
System.out.println("Incorrect.");
System.out.println("Would you like to study this term again? Type y or n.");
String bool = userInput.next();
if (bool.equals("y")) {
star_array[i] = term_array[i];
stardef_array[i] = def_array[i];
} else if (bool.equals("n")) {
star_array[i] = "null";
stardef_array[i] = "null";
}
System.out.println("What is the definition " + (i + 1));
answer = userInput.next();
} while (!answer.equals(def_array[i]));
if (answer.equals(def_array[i])) {
System.out.println(
"Correct"); /*
* when the user finally enters the
* right definition, the program skips
* to the code below
*/
}
}
} // end for-loop to ensure looping of all definitions
System.out.println("Now, time for testing definitions you starred!");
for (int z = 0; z < number_terms; z++) {
if (star_array[z].equals("null")) {
break;
} else {
System.out.println("What is the definition of " + star_array[z] + " ?");
String star_answer = userInput.next();
if (star_answer.equals(stardef_array[z])) {
System.out.println("Correct.");
} else if (!star_answer.equals(stardef_array[z])) {
do {
System.out.println("Incorrect. Please try again.");
System.out.println("What is the definition of " + star_array[z] + " ?");
star_answer = userInput.next();
} while (!star_answer.equals(stardef_array[z]));
}
}
}
}
}

Java scanner - allowing a certain number of ints

Really struggling to find the answer to this.
I'm creating a game where it asks how many players there are and the max number of players the user can enter is 3 (either 1, 2 or 3). Is this creating a for loop or can I just enter a parameter in the scanner function?
Code below:
System.out.println(" How many players are there? ");
int numberOfPlayers = scan.nextInt();
Player[] players = new Player[numberOfPlayers]; //this is where the players scores are stored
int currentPlayer = 0; //because arrays start at 0: +1 is added
for (int i = 0; i < numberOfPlayers; i++) {
System.out.println("What is player " + (i + 1) + " called?");
String playerName = scan.next();
players[i] = new Player(playerName);
You can use Scanner's nextLine() which reads the newline instead of next() as shown below:
System.out.println(" How many players are there? ");
int numberOfPlayers = Integer.parseInt(scan.nextLine());
Player[] players = new Player[numberOfPlayers];
for (int i = 0; i < numberOfPlayers; i++) {
System.out.println("What is player " + (i + 1) + " called?");
String playerName = scan.nextLine();
players[i] = new Player(playerName);
}
I suggest to use Integer.parseInt(scan.nextLine()) with a loop for example :
int numberOfPlayers = 0;
boolean correct = false;
do {
try {
System.out.println(" How many players are there? ");
numberOfPlayers = Integer.parseInt(scan.nextLine());
if (numberOfPlayers >= 1 && numberOfPlayers <= 3) {
correct = true;
}
} catch (NumberFormatException e) {
}
} while (!correct);
So if the user enter incorrect number or a number > 3 or < 1 it will ask the user to enter the number again until the the user enter the correct number 1,2,3

Array is only printing the last stored value and array element removal only replaces element

Does anyone know why is that when I print the last message ("report header..etc etc") the count on the list updates, but I'm only printing the last person's input values?
Also, how can I make so that only if the person has 30 or more credits or less than 90 will their name and credits be stored in the array, otherwise do nothing with the inputs?
Lastly, in the 'admin review' prompt portion, if I type in a name that matches an input, it should remove that name, but in my current code it only replaces the name with what I entered..
final int MAX_ON_LIST = 50;
String[] stuName = new String[1];
int[] numCredits = new int[1];
int currentSize = 0;
String question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
while (question.equalsIgnoreCase("n")) {
for (int i = 0; i < stuName.length; i++) {
do {
try {
stuName[i] = JOptionPane.showInputDialog("Enter student name:");
currentSize++;
}
catch (NumberFormatException e) {
stuName[i] = "";
}
if (stuName[i].equals("")) {
JOptionPane.showMessageDialog(null, "Name cannot be blank");
}
} while (stuName[i].equals(""));
}
for (int i = 0; i < numCredits.length; i++) {
do {
try {
numCredits[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter # of completed credits:"));
}
catch (NumberFormatException e) {
numCredits[i] = -1;
}
if (numCredits[i] < 0) {
JOptionPane.showMessageDialog(null, "# of credits can't be less than 0");
}
} while (numCredits[i] < 0);
}
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
}
String nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
while (nxtQuestion.equalsIgnoreCase("n")) {
String searchValue = JOptionPane.showInputDialog("Enter a name:");;
int position = 0;
boolean found = false;
while (position < stuName.length && !found) {
if (stuName[position].equalsIgnoreCase(searchValue)) {
found = true;
}
else {
++position;
}
}
if (found) {
stuName[1] = stuName[currentSize - 1];
--currentSize;
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
}
else {
JOptionPane.showMessageDialog(null, "Name not on list");
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
}
nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
}
if (nxtQuestion.equalsIgnoreCase("y"));
{
JOptionPane.showMessageDialog(null,
"Report Header\n\n" + "# of student's on list: " + currentSize + "\nNames: " + Arrays.toString(stuName) +
"\nCredits: " + Arrays.toString(numCredits));
}
I'm not sure why you go through all the pain of using arrays here while List (ArrayList or LinkedList) would suit your needs much better. I'm assuming this is some sort of a task where you must use arrays. Otherwise the whole code should be rewritten.
As correctly mentioned above, arrays don't change size - both of your arrays always have size of 1 all the time. This also results in index out of bounds exception if you enter more than one student and then in admin you enter the name of last student.
The name of last student is the only name saved, that's why it's the only name printed.
In order to only store person with credit >=30 and <=90 you can use a simple if.
Also note the code in the final part of your program:
if (nxtQuestion.equalsIgnoreCase("y"));
{
// Do something
}
Due to semicolon right after if the if is doing nothing.
The part in curly braces (where I've put "Do something" comment) will always get executed, it's separate from the if. (Java allows you to put blocks of code in curly braces in order to limit scope of local variables).
P.S. Here's a slightly better version (at least it works):
public static void main(String[] args) {
final int MAX_ON_LIST = 50;
final int bottomCreditsLimit = 30;
final int topCreditsLimit = 90;
String[] stuName = new String[0];
int[] numCredits = new int[0];
String question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
while (question.equalsIgnoreCase("n") && stuName.length < MAX_ON_LIST) {
String stuNameInput = "";
do {
stuNameInput = JOptionPane.showInputDialog("Enter student name:").trim();
if (stuNameInput.equals("")) {
JOptionPane.showMessageDialog(null, "Name cannot be blank");
}
} while (stuNameInput.equals(""));
int numCreditsInput = -1;
do {
try {
numCreditsInput = Integer.parseInt(JOptionPane.showInputDialog("Enter # of completed credits:").trim());
if (numCreditsInput < 0) {
JOptionPane.showMessageDialog(null, "# of credits can't be less than 0");
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Please input integer value");
}
} while (numCreditsInput < 0);
if (numCreditsInput >= bottomCreditsLimit && numCreditsInput <= topCreditsLimit) {
stuName = Arrays.copyOf(stuName, stuName.length + 1);
stuName[stuName.length - 1] = stuNameInput;
numCredits = Arrays.copyOf(numCredits, numCredits.length + 1);
numCredits[numCredits.length - 1] = numCreditsInput;
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
}
question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
}
String nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
while (nxtQuestion.equalsIgnoreCase("n")) {
String searchValue = JOptionPane.showInputDialog("Enter a name:").trim();
int position = -1;
for (int i = 0; i < stuName.length; i++) {
if (stuName[i].equalsIgnoreCase(searchValue)) {
position = i;
break;
}
}
if (position >= 0) {
stuName[position] = stuName[stuName.length - 1];
stuName = Arrays.copyOf(stuName, stuName.length - 1);
numCredits[position] = numCredits[numCredits.length - 1];
numCredits = Arrays.copyOf(numCredits, numCredits.length - 1);
} else {
JOptionPane.showMessageDialog(null, "Name not on list");
}
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
}
JOptionPane.showMessageDialog(null, "Report Header\n\n" + "# of student's on list: " + stuName.length + "\nNames: " + Arrays.toString(stuName)
+ "\nCredits: " + Arrays.toString(numCredits));
}
Each of your arrays has a single element. Every time you add a name, you're putting it into the same position in the array.
String[] stuName = new String[1];
int[] numCredits = new int[1];
This loop always has exactly one pass, with i = 0.
for (int i = 0; i < stuName.length; i++) {
Alternatives include:
Create a java.util.List of students, which grows as needed with each call to List.add().
Create a java.util.Map of students from name to value.
The for loop pre-compiles so you need to set stuName to something before engaging the loop.

Categories