I am trying to populate my array with user input; however, I cannot get it to properly work. I am trying to get an int for the user for the number of products they want to enter. Then I want to populate the array with more user input of actual products (Strings) based on the number of products they said they wanted to enter. This is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class Practice {
public static void main(String[] args) {
bannerPrinter();
getNum();
int num = 0;
ArrayList<String> products = productBuilder(num);
boolean productGuess = getOrder(products);
if (productGuess) {
double price = getPrice();
double tax = getTax(price);
double total = getTotal(tax, price);
printTotal(total);
}
else {
System.out.print("Product not found.");
}
}
public static void bannerPrinter() {
System.out.println();
System.out.println("******************************************");
System.out.println("****** Welcome to my eCommerce app! ******");
System.out.println("******************************************");
System.out.println();
}
public static int getNum() {
Scanner scnr = new Scanner(System.in);
int num = 0;
System.out.print("Enter the number of products: ");
num = scnr.nextInt();
return num;
}
public static ArrayList<String> productBuilder(int num) {
Scanner scnr = new Scanner(System.in);
String arrayNames = "";
ArrayList<String> products = new ArrayList();
for (int i = 0; i <= num; i++) {
System.out.print("Enter the products: ");
products.add(arrayNames);
}
return products;
}
public static boolean getOrder(ArrayList<String> products) {
Scanner scnr = new Scanner(System.in);
String guess = "";
boolean productName = products.contains(guess);
System.out.print("Enter a product: ");
guess = scnr.nextLine();
if(productName) {
System.out.println();
System.out.print("This product has been found.");
System.out.println();
}
else {
System.out.println();
}
return productName;
}
public static double getPrice() {
double price = 0.0;
price = (int)(Math.random() * 100);
return price;
}
public static double getTax(double price) {
double tax = 0.0;
tax = price * 0.10;
return tax;
}
public static double getTotal(double price, double tax) {
double saleTotal = 0.0;
saleTotal = price + tax;
return saleTotal;
}
public static void printTotal(double saleTotal) {
System.out.println("You total is $" + saleTotal + "0");
}
}
I may not fully understand what you attempt to do but I did see some interesting lines... see my comments
public static ArrayList<String> productBuilder(int num) {
Scanner scnr = new Scanner(System.in);
String arrayNames = "";
ArrayList<String> products = new ArrayList();
for (int i = 0; i <= num; i++) {
System.out.print("Enter the products: ");
// I assume here scnr is supposed to read something
// and assign it to arrayNames?
products.add(arrayNames);
}
return products;
}
public static boolean getOrder(ArrayList<String> products) {
Scanner scnr = new Scanner(System.in);
String guess = "";
// I assume this line is supposed to be after
// guess = scnr.nextLine()?
boolean productName = products.contains(guess); // very confusing line
System.out.print("Enter a product: ");
guess = scnr.nextLine();
if(productName) {
System.out.println();
System.out.print("This product has been found.");
System.out.println();
}
else {
System.out.println();
}
return productName;
}
Related
I'm trying to convert the user input from the question of students name and score into a array.
I also need help to printout the array.
The while loop is using boolean loopNaming as its condition, and i is updated everytime the loop occurs.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
String[] name = new String[i];
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1;
}
System.out.println(name[i]);
}
}
You can simplify the logic of your program and write something like this,
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
List<String> nameList = new ArrayList<String>();
List<Double> scoreList = new ArrayList<Double>();
while (true) {
System.out.printf("Enter first name of student or done to finish: ");
String fname = keyboard.next();
if (fname.equals("done")) {
break;
}
System.out.printf("Enter last name of student: ");
String lname = keyboard.next();
nameList.add(fname + " " + lname);
System.out.println("Enter score: ");
scoreList.add(keyboard.nextDouble());
}
keyboard.close();
System.out.println("Names: " + nameList);
System.out.println("scores: " + scoreList);
}
I have changed the array to an arraylist and moved i=i+1; to inside else segment. Also changed the final print statement to print the list.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<String>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
name.add(keyboard.next());
if(name.get(i).equals("done"))
{
loopNaming = false;
}
else
{
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i=i+1;
}
}
System.out.println(name);
}
I would firstly recommend using a List data structure:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming = true;
List<String> name = new ArrayList<>();
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
}
System.out.println(name.toString());
}
However, if you very much would like to use an array, you could make your own method to increase the size of your array each time a new name is added:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double score;
int i = 0;
boolean loopNaming = true;
String[] name = {};
while (loopNaming) {
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if (input.equals("done")) {
loopNaming = false;
} else {
name = increaseArray(name);
name[i] = input;
System.out.println("Enter score: ");
score = keyboard.nextDouble();
i++;
}
}
System.out.println(Arrays.toString(name));
}
public static String[] increaseArray(String[] arr) {
String[] temp = new String[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
temp[i] = arr[i];
}
return temp;
}
I was unsure what your plan was with your score variable, but this would be two ways to achieve your desired result.
I hope this helps.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
double score;
boolean loopNaming=true;
int i=0;
ArrayList<String> name = new ArrayList<>();
while(loopNaming==true)
{
System.out.printf("Enter name of student or done to finish: ");
String input = keyboard.next();
if(input.equals("done"))
{
loopNaming = false;
}
else
{ name.add(input);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
}
i=i+1; //no need to use
}
System.out.println(name);
}
You should use a dynamic list because You can't resize an array in Java. The second point when the user gives "done", you should not put it in the list so check it before the insertion.
You declared your String array with size 0. that's why you cant add elements in to it.
import java.util.Scanner;
public class NameArray {
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
double score[] = new double[10];
boolean loopNaming=true;
int i=0;
String namae;
String[] name = new String[10];
int count = 0;
while(loopNaming==true){
System.out.printf("Enter name of student or done to finish: ");
name[i] = keyboard.next();
if(name[i].equals("done")){
loopNaming = false;
}
else{
System.out.println("Enter score: ");
score[i] = keyboard.nextDouble();
count++;
}
i=i+1;
}
for(int j = 0; j < count; j++) {
System.out.println(name[j]+" "+score[j]);
}
}
}
Try this code or you can go for any other data structures.
Can someone tell me why my baggage won't print?
For passenger name I enter, say, John.
For country code I enter: BI
For flight number I enter: 095
For number of baggage I can enter any amount.
Let's say I enter: John, BI, 095, 3.
This is what I get: [John with baggage(s) [, , ]] when I should be getting
[John with baggage(s) [BI0950, BI0951, BI0952]]
Sorry if the code is quite messy.
It's amended. Thanks guys.
import java.util.*;
public class baggageSys{
public static String getUser_command(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter command B-baggage, n-next, q-quit");
String s = keyboard.nextLine();
return s;
}
public static String getUser_flight(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the flight number");
String s = keyboard.nextLine();
return s;
}
public static String getPassenger(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter passenger name");
String s = keyboard.nextLine();
return s;
}
public static String getUser_country(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the country code");
String s = keyboard.nextLine();
return s;
}
public static int getUser_number(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter number of baggage");
int s = keyboard.nextInt();
return s;
}
public static String next(ListIterator<Passenger> passenger){
String k = "";
passenger.next();
return k;
}
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
public static void main(String args[]) {
LinkedList<Passenger> passenger = new LinkedList<Passenger>();
ListIterator<Passenger> iterator = passenger.listIterator();
LinkedList<String> baggage = new LinkedList<String>();
String command = "";
while (!command.equals("q")){
command = getUser_command();
if(command.equals("B") || command.equals("b")){
String p = "";
p = getPassenger();
passenger.add(new Passenger(p));
// command = getUser_command();
String country = "";
country = getUser_country();
String flight = "";
flight = getUser_flight();
int amount = 0;
amount = getUser_number();
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i]);
passenger.getLast().setBaggages(baggage);
}
System.out.println(passenger);
} else if(command.equals("n")){
next(iterator);
}
else
System.out.println("Enter 'q' to end the program");
}
}
public static class Passenger {
String passengers;
List<String> baggage;
public Passenger(String passengers) {
this.passengers = passengers;
baggage = Collections.emptyList();
}
public void setBaggages(List<String> baggage) {
this.baggage = baggage;
}
#Override
public String toString() {
return passengers + " with baggage(s) " + baggage;
}
}
}
You're not returning anything in your makeBaggage method, as you can see after the loop it returns the x variable which is not either set inside the loop, in this case your loop is useless.
public static String makeBaggage(String country, String flight, int num){
String x = "";
for(int i = 0; i < num; i++){
String[] bgs = new String[num];
bgs[i] = country + flight + i;
// System.out.println(bgs[i]);
}
return x;
}
I think this is the one you're looking for:
public static String makeBaggage(String country, String flight, int num){
return country + flight + num;
}
For this specific line in your code:
for(int i = 0; i < amount; i++){
String[] bg = new String[amount];
bg[i] = makeBaggage(country, flight, amount);
baggage.add(bg[i]);
System.out.println(bg[i]);
...
Move the String[] bg = new String[amount]; declaration outside of the for loop and instead of supplying the amount in the makeBaggage method, use the loop counter instead as follows: bg[i] = makeBaggage(country, flight, i);
String[] bg = new String[amount];
for(int i = 0; i < amount; i++){
bg[i] = makeBaggage(country, flight, i);
baggage.add(bg[i]);
System.out.println(bg[i])
..
I think that should do it. Also, your code could be greatly improved, and that would be your tasks.
I need both the String and double arrays to go from inputAccept to table:
inputAccept();
table(names, costs);
public static void inputAccept() {
Scanner scan = new Scanner(System.in);
String[] names = {"","","","","","","","","",""};
double[] costs = new double[10];
for (int i = 0; i < 10; i++)
{
System.out.println("Enter the name of item " + (i + 1) + ": ");
names[i] = scan.nextLine();
System.out.println("Enter item cost: ");
costs[i] = scan.nextDouble();
}
}
public static void table(String[] names, double[] costs) {
//insert code using the arrays
}
I know this is wrong, but I don't know what to do to fix it.
You can just create the two arrays in the main method, then first pass them into the inputAccept method, then pass the two arrays into the table method:
public static void main(String[] args) {
double[] costs = new double[10];
String[] names = {"","","","","","","","","",""};
inputAccept(names, costs);
table(names, costs);
}
public static void inputAccept(String[] names, double[] costs) {
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 10; i++)
{
System.out.println("Enter the name of item " + (i + 1) + ": ");
names[i] = scan.nextLine();
System.out.println("Enter item cost: ");
costs[i] = scan.nextDouble();
}
}
public static void table(String[] names, double[] costs) {
//insert code using the arrays
}
First it looks like you are creating "items" from user input. I think modeling a class Item should be a first step:
public final class Item {
private final String name;
private final double cost;
public Item(String name, double cost) {
this.name = name;
this.cost = cost;
}
public String getName() {
return name;
}
public double getCost() {
return cost;
}
}
Then inputAccept() becomes:
public static Item[] inputAccept() {
Item[] items = new Item[10];
try (Scanner scan = new Scanner(System.in)) {
for (int i = 0; i < items.length; i++) {
System.out.println("Enter the name of item " + (i + 1) + ": ");
String name = scan.next();
System.out.println("Enter item cost: ");
double cost = scan.nextDouble();
items[i] = new Item(name, cost);
}
}
return items;
}
Therefore, table(...) becomes
public static void table(Item[] items) {
// insert code using the arrays
}
And the final usage is
public static void main(String[] args) {
table(inputAccept());
}
public class Main {
static String[] names = {"","","","","","","","","",""};
static double[] costs = new double[10];
public static void main(String[] args) {
inputAccept();
table(names, costs);
}
public static void inputAccept() {
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 10; i++)
{
System.out.println("Enter the name of item " + (i + 1) + ": ");
names[i] = scan.next();
System.out.println("Enter item cost: ");
costs[i] = scan.nextDouble();
}
}
public static void table(String[] names, double[] costs) {
for (String name: names) {
System.out.println(name);
}
for (double value: costs) {
System.out.println(value);
}
}
}
This approach is as clean as a baby's bottom
private class InputResult {
//generate constructor with both fields
String[] names; //generate getter
double[] costs; //generate getter
}
then
public static InputResult inputAccept()
...
return new InputResult(names, costs);
public static void table(InputResult input)
String[] names = input.GetNames();
...
So I am trying to figure out how to get my code to work, but I keep on getting a nullError. Am I not storing my data correctly? Here is my code:
public class ProductTesterPart1{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter the product number, name, stock, and price in that order.");
List<ProductPart1> products = new ArrayList<ProductPart1>();
String line = userInput.nextLine();
while (!line.equals("quit")) {
if (line == null || line.trim().isEmpty()) {
products.add(new ProductPart1());
}
else {
try {
Scanner s = new Scanner(line);
int number = s.nextInt();
String name = s.next();
int stock = s.nextInt();
double price = s.nextDouble();
products.add(new ProductPart1(number, name, stock, price));
}
catch (NoSuchElementException e) {
System.out.print("Error: " + e.getMessage());
}
}
}
for (ProductPart1 p : products) {
System.out.println(p.toString());
}
}
And of course, that is the driver class, here is my object:
public class ProductPart1 {
//Declares variables
private int productNumber;
private String productName;
private int productStock;
private double productPrice;
//Constructor
public ProductPart1(){
setNumber(0);
productName = "Null";
productStock = 0;
productPrice = 0.0;
}
//Overload constructor
public ProductPart1(int number, String name, int stock, double price){
productNumber = number;
productName = name;
productStock = stock;
productPrice = price;
}
//set the number of the object
public void setNumber(int newNumber){
productNumber = newNumber;
}
//set the name of the object
public void setName(String newName){
productName = newName;
}
//set the stock of an object
public void setStock(int newStock){
productStock = newStock;
}
//set the price of an object
public void setPrice(double newPrice){
productPrice = newPrice;
}
//get the number of an object
public int getNumber(){
return getNumber();
}
//get the name of an object
public String getName(){
return productName;
}
//get the stock of an object
public int getStock(){
return productStock;
}
//get the price of an object
public double getPrice(){
return productPrice;
}
//toString to bring the object together.
public String toString(){
return new String("Number: " + getNumber() + " Name: " + productName + " Price: " + productPrice + " Stock: " + productStock);
}
try this updated code:
public class ProductTesterPart1{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter the product number, name, stock, and price in that order.");
List<ProductPart1> products = new ArrayList<ProductPart1>();
String line = userInput.nextLine();
while (!line.equals("quit")) {
if (line == null || line.trim().isEmpty()) {
products.add(new ProductPart1());
}
else {
try {
Scanner s = new Scanner(line);
int number = s.nextInt();
String name = s.next();
int stock = s.nextInt();
double price = s.nextDouble();
products.add(new ProductPart1(number, name, stock, price));
} catch (NoSuchElementException e) {
System.out.print("Error: " + e.getMessage());
}
}
if(userInput.hasNext()){
line = userInput.nextLine();
} else {
break;
}
}
for (ProductPart1 p : products) {
System.out.println(p.toString());
}
}
}
Your code creates an infinite loop. First you read line of product number, name, stock, and price. Then you go into a while loop, where you read this line out, but never again change the line variable, so it gets read again and again infinitely.
I was having some trouble with a program where I am suppose to allow a user to enter any amount of numbers into a program until they do not want to anymore. The program then should calculate the average and maximum of the numbers inputed. Where did I go wrong?
import java.util.Scanner;
public class DataSet
{
//Instance Variables
private double newValue;
private double sum;
private int count;
Scanner scan = new Scanner(System.in);
//Constructors
public DataSet()
{
double newValue = 0;
double sum = 0;
int count = 0;
}
public void run()
{
}
public double getaddValueToSet()
{
System.out.println("Please enter a number");
newValue = scan.nextDouble();
count += 1;
return newValue;
}
public double getSum()
{
sum += newValue;
return sum;
}
public double getAverage()
{
double average;
average = sum/count;
return average;
}
public double getMaximum()
{
double max=newValue;
if(newValue >= max)
{
max = newValue;
}
return max;
}
public String toString()
{
String str;
str = "Average: " + getAverage() + "\n" +
"Maximum: " + getMaximum();
return str;
}
}
import java.util.Scanner;
public class DataSetRunner
{
public static void main(String [] args)
{
String answer = "yes";
Scanner scan = new Scanner(System.in);
{
System.out.println("Do you want to enter another number?");
answer = scan.next();
}
while(answer.equals("yes"))
{
DataSet d1 = new DataSet();
double sum, number;
d1.run();
number = d1.getaddValueToSet();
sum = d1.getSum();
answer = scan.nextLine();
System.out.println(d1);
}
}
}
DataSet d1 = new DataSet();
do {
System.out.println("Do you want to enter another number?");
answer = scan.next();
if (answer.equalsIgnoreCase("YES")) {
double sum, number;
d1.run();
number = d1.getaddValueToSet();
sum = d1.getSum();
answer = scan.nextLine();
System.out.println(d1);
} else {
break;
}
} while (true);