I've been working on a small bit of code that helps me calculate performance of a movie's Box-Office weekend. I want it to require the
Name of the movie
How much it'll cost to use
How much it's predicted to make that weekend
Then I want it to output all the above information, with the addition of each movie's performance. Well, I'm having issues with it saving multiple String[] values as well as int[] values. I can remove the String lines, and all the int[]'s (both the price and the prediction) work fine, or I can remove the int[]'s and the String[] works fine. Can anyone help me find my errors?
import java.util.*;
public class FMLArrays {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] movieName = new String[15];
int[] moviePrice = new int[15];
int[] moviePrediction = new int[15];
int[] moviePreformance = new int[15];
for (int i = 0; i < movieName.length; i++) {
System.out.print("Enter the name of movie " + (i+1) + ": ");
movieName[i] = console.nextLine();
System.out.print("Enter the price of movie " + (i+1) + ": ");
moviePrice[i] = console.nextInt();
System.out.print("Enetr the prediction of movie " + (i+1) + ": ");
moviePrediction[i] = console.nextInt();
moviePreformance[i] = Math.round(((moviePrediction[i] * 1000000) / moviePrice[i]) * 100) / 100;
System.out.println();
}
for (int i = 0; i < movieName.length; i++) {
System.out.println();
System.out.println("Name: " + movieName[i]);
System.out.println("Price: $" + moviePrice[i]);
System.out.println("Prediction: $" + moviePrediction[i] + " million");
System.out.println("Preformance: $" + moviePreformance[i]);
}
}
}
When you used nextInt() and entered a number you also enterd a new line character, so the next time you called nextLine() this new line character was your next input waiting.
You could fix this by always using nextLine, or by adding a call for nextLine.
import java.util.*;
public class FMLArrays {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String[] movieName = new String[2];
int[] moviePrice = new int[2];
int[] moviePrediction = new int[2];
int[] moviePreformance = new int[2];
for (int i = 0; i < movieName.length; i++) {
System.out.print("Enter the name of movie " + (i+1) + ": ");
movieName[i] = console.nextLine();
System.out.print("Enter the price of movie " + (i+1) + ": ");
moviePrice[i] = Integer.parseInt(console.nextLine());
System.out.print("Enetr the prediction of movie " + (i+1) + ": ");
moviePrediction[i] = Integer.parseInt(console.nextLine());
moviePreformance[i] = Math.round(((moviePrediction[i] * 1000000) / moviePrice[i]) * 100) / 100;
System.out.println();
}
for (int i = 0; i < movieName.length; i++) {
System.out.println();
System.out.println("Name: " + movieName[i]);
System.out.println("Price: $" + moviePrice[i]);
System.out.println("Prediction: $" + moviePrediction[i] + " million");
System.out.println("Preformance: $" + moviePreformance[i]);
}
}
}
This should fix the issue:
moviePrice[i] = console.nextInt();
console.nextLine();
moviePrediction[i] = console.nextInt();
console.nextLine();
console.nextInt() only reads the number, not the rest of the line, like carriage return.
Related
I have to write a Java program with do while loop. Basically it's like self-checkout register in grocery stores. At first program prompts user to enter Item 1 name and price, after we enter it asks "do you want to add more?" and prompts user. if we say yes then it repeats, add Item 2 (item number increments) name and price. So it goes like this till we say "no" or till entering 10 items. And after that program prints all item numbers correspondingly their names, and prices one by one. Also calculates total of all items. My code prints only last item number, name, price and total. I don't know how to merge array to do while.
Example how it should look:
_output: Enter Item1 and its price:_
_input: Tomatoes_
_input: 5.5_
_output: Add one more item?_
_input: yes_
_output: Enter Item2 and its price:_
_input: Cheese_
_input: 3.5_
_output: Add one more item?_
_input: yes_
_output: Enter Item3 and its price:_
_input: Apples_
_input: 6.3_
_output: Add one more item?_
_input: no_
_output: Item1: Tomatoes Price: 5.5, Item2: Cheese Price: 3.5, Item3: Apples Price: 6.3_
_output: Total price: 15.3_
Here's my code. It prints only last item's number, name and price with total. But can't manage to print all of them one by one as in example.
Scanner scan = new Scanner(System.in);
String item;
double price;
int i=1;
double total=0;
String quest;
String items [] = {};
do {
System.out.println("Enter item " + i + " and it's price:");
item = scan.next();
price=scan.nextDouble();
i++;
total=total+price;
System.out.println("Add one more item?");
quest=scan.next();
} while (quest.equalsIgnoreCase("yes")) ; {
System.out.println("Item "+i+": " + item + " Price: " + price + ",");
System.out.println("Total price: " + total);
}
You need to store each input in an array or collection, such as ArrayList.
If you choose to use an array, you can ask the user how many items will be entered then use that value for the length of the array:
System.out.print("Enter the number of items in your cart: ");
int arraySize = scan.nextInt();
String[] itemNames = new String[arraySize];
double[] itemPrices = new double[arraySize];
If you decide you use a list, you do not need to ask the user for the list size, since lists are dynamically expanding data types:
List<String> itemNames = new ArrayList<String>();
List<Double> itemPrices = new ArrayList<Double>();
Then for every iteration of your loop, you save the values into the arrays/lists:
System.out.print("Enter the number of items in your cart: ");
int arraySize = scan.nextInt();
String[] itemNames = new String[arraySize];
double[] itemPrices = new double[arraySize];
for(int i = 0; i < ararySize; i++) {
System.out.println("Enter item " + (i + 1) + " and it's price:");
itemNames[i] = scan.next();
itemPrices[i] = scan.nextDouble();
// ...
}
// ...
Or for the list approach:
List<String> itemNames = new ArrayList<String>();
List<Double> itemPrices = new ArrayList<Double>();
do {
System.out.println("Enter item " + i + " and it's price:");
itemNames.add(scan.next());
itemPrices.add(scan.nextDouble());
// ...
} while (quest.equalsIgnoreCase("yes")); {
// ...
}
Then you can iterate over the list/array to print your output:
for(int i = 0; i < itemNames.length; i++) {
String name = itemNames[i];
double price = itemPrices[i];
System.out.println("Item " + i + ": " + name + " Price: " + price + ",");
}
For list:
for(int i = 0; i < itemNames.size(); i++) {
String name = itemNames.get(i);
double price = itemPrices.get(i);
System.out.println("Item " + i + ": " + name + " Price: " + price + ",");
}
I finally solved the task. Thanks everybody who helped, really appreciated. Here's the code:
Scanner scan = new Scanner(System.in);
String itemName;
double price;
String[] items = new String[10];
double[] prices = new double[10];
int itemNumbers[] = new int[10];
String answer;
double total = 0;
int i = 1;
int index = 0;
do {
System.out.println("Enter item " + i + " and it's price:");
itemName = scan.next();
price = scan.nextDouble();
scan.nextLine();
total = total + price;
items[index] = itemName;
prices[index] = price;
itemNumbers[index] = i;
index++;
System.out.println("Add one more item?");
answer = scan.next();
i++;
} while (answer.equalsIgnoreCase("yes") && i <= 10); {
for (int j = 0; j < index; j++) {
System.out.print("Item " + itemNumbers[j] + ": " + items[j] + " price: " + prices[j] + ",");
}
}
System.out.println("\nTotal price: " + total);
This version works too. Without arrays.
String shoppingList = "";
String item = "";
String addMore = "";
double price = 0;
int count = 1;
double totalPrice = 0;
do {
System.out.println("Enter Item"+ count + " and its price:");
item = scan.next();
price = scan.nextDouble();
shoppingList += ("Item" + count + ": " + item + " Price: " + price + ", ");
totalPrice += price;
System.out.println("Add one more item?");
addMore = scan.next();
count++;
} while (addMore.equalsIgnoreCase("yes"));
System.out.println(shoppingList.substring(0, shoppingList.length()-2));
System.out.println("Total price: " + totalPrice);
I'm trying to make a code that takes a users input and prints their schedule, but I'm running into a problem with my do-while loop.
My program will not rerun. I'm getting an error that says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 at com.company.Main.main(Main.java:25)
Here is my code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String rerun;
do {
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("How many courses do you have?");
int numCourse = input.nextInt();
input.nextLine();
String[][] timetable = new String[numCourse][2];
for (int j = 0; j < numCourse; j++) {
System.out.println("What is the name of your course #" + (j + 1) + "?");
String course = input.nextLine();
timetable[j][0] = course;
System.out.println("What is your teachers name for " + course + "?");
String teacher = input.nextLine();
timetable[j][1] = teacher;
}
System.out.println("Hello " + name + ", here is your timetable:");
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
System.out.println("Would anyone else like to print their schedule? (yes/no)");
rerun = input.next();
}while(rerun.equalsIgnoreCase("yes"));
System.out.println("Goodbye!");
}
}
Problem is in second for loop where you display your from array. put next() inplace of nextLine() because sometimes it skip the position.
Change
for (int i = 0; i <= numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
To
for (int i = 0; i < numCourse; i++) {
System.out.format("\n%-30s%-30s", "Course #" + (i+1) + ": " + timetable[i][0],"Teacher: " + timetable[i][1]);
}
Suppose your numCorse is 2. In your code, loop start from 0 and terminate after 2 so, Your loop working right while i is 0 and 1 but if i is going to 3 you get exception ArrayIndexOutOfBound.
String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
String[] array2 = new String [10]; // New array that saves up to 10 elements(treatments)
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
System.out.println("Control" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
int n = array.length;
for (int i=0; i<n; i++) {
for (int j=0; i<n ; j++) {
System.out.println();
treatment = input.nextInt();
if (treatment==1) {
cost += Integer.parseInt(array[i][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==2) {
cost += Integer.parseInt(array[i+1][1]);
System.out.print("Total cost so far: " + cost);
}
if (treatment==3) {
cost += Integer.parseInt(array[i+2][1]);
System.out.print("Total cost so far: " + cost);
}
}
}
How do I move on from here? I figured that I have to store the input in the new array and exit the loop after 10 treatments or add an option to the user to print out the receipt when they're done.
The receipt needs to print all the chosen treatments along with the cost for each individual treatment. I will also need to add a variable to add a total amount for all the chosen treatments.
Here it is what you are trying to do, As the treatments are fixed so you can just index them as 0, 1, 2. One thing you can do is to make a hashmap in which you can store the treatment name and its cost (String,int) every time the user wants to enter.
Look at the code below
import java.util.*;
import java.util.HashMap;
public class treatment {
public static void main(String []args) {
String[][] array = {{"Checkup", "60"},
{"Repairing tooth", "150"},
{"Cleaning", "30"}}; // Menu of treatments
// New array that saves up to 10 elements(treatments)
HashMap<String, Integer> treat = new HashMap<String, Integer>();
int cost = 0;
int treatment = 0;
Scanner input = new Scanner(System.in);
int n = array.length;
int i =0;
char c = '\0';
do {
System.out.println("\n\nControl" + " " + "1");
System.out.println("Repair tooth:" + " " + "2");
System.out.println("Cleaning:" + " " + "3");
System.out.println("Exit: " + "-1");
System.out.println();
System.out.print("Enter treatment value (1, 2, 3): ");
treatment = input.nextInt();
if (treatment==1){
i = 0;
cost += Integer.parseInt(array[0][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==2) {
i = 1;
cost += Integer.parseInt(array[1][1]);
System.out.println("\nTotal cost so far: " + cost);
}
else if (treatment==3) {
i = 2;
cost += Integer.parseInt(array[2][1]);
System.out.println("\nTotal cost so far: " + cost);
}
treat.put(array[i][0], cost);
} while (treatment != -1);
System.out.println("Total COst is : " + cost);
System.out.println("The treatements you opt for are:\n");
System.out.println(treat);
System.out.println("\n");
}
}
Essentially i've isolated the issue, the int numpersons begins as 0. I take a user input to make it a particular number which is the array size, when the second method begins it takes the 0 again and then the array has an out of bounds exception. I want to pass it from one method to the next, or make them more successive, idk how to do this
thanks in advance
import java.util.Scanner;
public class BankApp {
Scanner input = new Scanner(System.in);
int numpersons = 0;
private SavingsAccount[] clients = new SavingsAccount[numpersons];
public BankApp() {
while (numpersons < 1) {
System.out.println("How many people are there?");
numpersons = input.nextInt();
if (numpersons < 1 || 2147483647 < numpersons) {
System.out.println("invalid number, please enter again");
}
}
input.nextLine();
}
public void addClients() {
int i = 0;
while (i < numpersons) {
System.out.println("enter account id " + (i + 1));
String AccountID = input.nextLine();
System.out.println("enter account name " + (i + 1));
String AccountName = input.nextLine();
System.out.println("enter account balance " + (i + 1));
Double AccountBalance = input.nextDouble();
clients[i] = new SavingsAccount(AccountID, AccountName, AccountBalance);
input.nextLine();
i++;
}
}
public void displayClients() {
int i = 0;
while (i < numpersons) {
System.out.println("======================================");
System.out.println("Account ID " + (i + 1) + ": " + clients[i].getID());
System.out.println("Account Name " + (i + 1) + ": " + clients[i].getName());
System.out.println("Account Balance " + (i + 1) + ": " + clients[i].getBalance());
System.out.println("======================================");
i++;
}
}
public static void main(String args[]) {
BankApp ba = new BankApp();
ba.addClients();
ba.displayClients();
}
}
Am unable to still get this program working like it should. Most of it works, see code below:
import java.io.*;
import java.util.*;
public class demo {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String str[] = { "Bananas", "Apples", "Oranges" };
double price[] = { 2.09, 3.99, 2.19};
int i = 0;
int j = 0;
System.out.print("Enter type of product: ");
String string = sc.next();
if ("fruit".equals(string)) {
while (i < str.length) {
while (j < price.length) {
System.out.print(str[i++] + ": " + "£" + (price[j++]) + "p per bag \n");
}
}
}
System.out.print("\n");
System.out.print("Enter which type of " + string + ": ");
String string1 = sc.next();
boolean strs = "bananas".equals(string1);
boolean strs1 = "apples".equals(string1);
boolean strs2 = "oranges".equals(string1);
if (strs){
System.out.print("Enter qty of " + str[0] + " (by bag): ");
}
if (strs1) {
System.out.print("Enter qty of " + str[1] + " (by bag): ");
}
if (strs2) {
System.out.print("Enter qty of " + str[2] + " (by bag): ");
}
int qty = sc.nextInt();
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int h = 1;
int[] g = {0,1,2};
if ((a[h] == (qty)) || (strs) || (strs1) || (strs2)) {
System.out.print("\n"+ qty + " bag(s) of " + string1 + " have been added to your basket, "
+ "total costing £"+ (qty) * (price[g[0]]) + "p");
}
}
}
How can I get this code to work...any ideas?(ie the type of product(fruit), the type of fruit(bananas or apples or oranges), and the qty of them (between 1-10), but when it comes to working out Total cost, it comes out wrong...
One logic is this.
double itemCost = 0;
if (strs){
System.out.print("Enter qty of " + str[0] + " (by bag): ");
itemCost = price[0];
}
if (strs1) {
System.out.print("Enter qty of " + str[1] + " (by bag): ");
itemCost = price[1];
}
if (strs2) {
System.out.print("Enter qty of " + str[2] + " (by bag): ");
itemCost = price[2];
}
int qty = sc.nextInt();
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int h = 1;
int[] g = {0,1,2};
if ((a[h] == (qty)) || (strs) || (strs1) || (strs2)) {
System.out.print("\n"+ qty + " bag(s) of " + string1 + " have been added to your basket, "
+ "total costing £"+ (qty) * (itemCost) + "p");