when my program gets to the part where it asks for the name of the fruit, it will output the string asking for the name, then immediately go to the next string output without waiting for the user input.
This seems to automatically assign a value of null to my name variable.
Fruit.java
public class Fruit {
String Name;
int Quantity;
double Mass;
public Fruit(String Name, int Quantity, double Mass) {
this.Name = Name;
this.Quantity = Quantity;
this.Mass = Mass;
}
public void Information() {
System.out.println("This fruit is an " + Name + ", there's " + Quantity
+ " of it and it weighs " + Mass + " grams");
}
}
Fruits.java
import java.util.Scanner;
public class Fruits {
public static void main(String[] args) {
Fruit menu[];
int number;
String name;
int quantity;
double mass;
System.out
.print("How many fruits would you like to add to the menu?: ");
Scanner input = new Scanner(System.in);
number = input.nextInt();
input.nextLine();
menu = new Fruit[number];
for (int i = 0; i < menu.length; i++) {
System.out.println("What would you like to name the fruit?: ");
name = input.nextLine();
System.out.println("How much fruits are there?: ");
quantity = input.nextInt();
System.out.println("What is the mass of the Fruit in grams?: ");
mass = input.nextDouble();
menu[i] = new Fruit(name, quantity, mass);
menu[i].Information();
}
input.close();
}
}
instead of input.nextInt(); use Integer.parseInt(input.nextLine()). it might solve your issue.
When you use input.nextInt() there is a %n char in hub. You need to use a input.nextLine() after to remove the line-break charcater. You can also use input.nextLine() for each variables and then parse it yourself.
Warning! In java convention the method name, attribute name and parameter name must begin by an lower case character.
the problem is scanning for ints, then nextLine. When you run .nexInt() I believe there is a newline character not scanned in, so this immediately messes with the following .nextLine(), as it only takes in the newline and nothing after
The easiest fix I am aware of is
number = input.nextInt();
input.nextLine();
menu = new Fruit[number];
And then the rest of the code should work
As an aside, usually you would start the loop from 0, because arrays start from 0, and you will have a blank first entry, but I don't think it matters in this particular piece of code
Related
My problem is I want to input two numbers separated by a space and getting those two numbers and compute those two numbers. for example, i typed "10 20", they are separated by a space and then I want to get and compute them as separate: 10 * 20 = 200..
what I have is a getter and setter for this part
these are my code:
MY GETTER AND SETTER CLASS
import java.util.*;
public class LabExer2
{
private String itemName;
private double itemPrice;
private int itemQuantity;
private double amountDue;
public void setItemName(String newItemName)
{
itemName = newItemName;
}
public String getItemName()
{
return itemName;
}
public void setTotalCost(int quantity, double price)
{
itemQuantity = quantity;
itemPrice = price;
amountDue = itemQuantity * itemPrice;
}
public double getTotalCost()
{
return amountDue;
}
public void readInput()
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the item you are purchasing.");
itemName = s.nextLine();
System.out.println("Enter the quantity and price separated by a space.");
//itemQuantity = s.nextInt();
//itemPrice = s.nextDouble();
}
public void writeInput()
{
System.out.println("You are purchasing " + itemQuantity + " " + itemName + "(s) at " + itemPrice + " each.");
System.out.println("Amount due is " + getTotalCost());
}
}
MY MAIN CLASS
public class MainLabExer2
{
public static void main(String[]args)
{
LabExer2 le = new LabExer2();
//still not finished because I can't figure out the process in the other class.
}
}
The output I wanted to have:
Enter the name of the item you are purchasing.
pencil
Enter the quantity and price separated by a space.
3 15.50
You are purchasing 3 pencil(s) at 15.50 each.
Amount due is 46.50
I want to get the 3 and 15.50 and compute. I don't know what to use or something, I'm just a beginner in java.
You can create two prompts, one to take in the itemQuantity int and another to take the itemPrice Double.
But if you want the user to input both values at once, you need to write a code in the readInput() method that will extract the itemQuantity value and the itemPrice value.
Try this:
public void readInput() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the item you are purchasing.");
itemName = s.nextLine();
System.out.println("Enter the quantity and price separated by a space.");
String userInput = s.nextLine(); //String to collect user input
//code to loop through String in search for Whitespace
for (int x=0; x<String.length(); x++) {
if (userInput.charAt(x) == ' ') {
//whitespace found, set itemQuantity to a substring
//from the first char in UserInput to the char before whitespace
itemQuantity = Integer.parseInt(userInput.substring(0, x-1));
//convert String to int
itemPrice = Integer.parseInt(userInput.substring(x+1, userInput.length()));
x = String.length();
} else {
itemQuantity = Integer.parseInt(userInput);
}
}
}
Pardon me if my code is not properly formatted, I'm new here.
Only need to convert the string into Integer, and string into Double. Then, to put 2 numbers and separate them, use the one-dimensional array and the split function.
try this:
public void readInput(){
//Enter the product of item name
System.out.print("Enter the name of the item you are purchasing: ");
ITEM_NAME = input.nextLine();
//Enter the quantity and the price for the item
System.out.print("Enter the quantity and price separated by a space: ");
String userInput = input.nextLine();
String[] inputArray = userInput.split(" ");
ITEM_QUANTITY = Integer.parseInt(inputArray[0]);
ITEM_PRICE = Double.parseDouble(inputArray[1]);
}
I'm confused on what I'm doing wrong here. Anyone care to explain? It compiles and runs but I keep getting an error at line 50 which is the return line.
Also if I change the code below to "int max = (number1, number2) " i get the can not find symbol error. Any help will be greatly appreciated.
int max = max(num1, num2);
import java.io.*;
import java.util.Scanner;
public class MethodLab {
public static void main(String[] args) {
// variable declarations for part 1
String title;
String firstName;
String lastName;
Scanner in = new Scanner(System.in);
// prompt for input for part 1
System.out.print("Enter a title:");
title = in.next();
System.out.print("Enter your first name:");
firstName = in.next();
System.out.print("Enter a your last name:");
lastName = in.next();
// call the method for part 1
greeting(title, firstName, lastName);
// variable declarations for part 2
int number1;
int number2;
// user prompts for part 2
System.out.print("Enter first number:");
number1 = in.nextInt();
System.out.print("Enter second number:");
number2 = in.nextInt();
// call the method for part 2 inside the println statement
System.out.println("The largest number is " + max(number1, number2));
}
/******************** greeting method goes here*********************/
public static void greeting(String proper, String fname, String lname){
System.out.println();
System.out.printf("Dear " + proper +" "+ fname + " "+ lname);
System.out.println();
}
/***********************end of method*************************/
/******************** max method goes here*********************/
public static int max(int num1,int num2){
int max = max(num1, num2);
return max;
}
Use int max = Math.max(num1, num2) this will return the max number.
public static int max(int num1,int num2){
int max = max(num1, num2);
return max;
}
This method would never complete. This is going to call max again and again until you run out of stack space. And when you do, it throws a stack overflow error. You should change it to
public static int max(int num1,int num2){
int max = num1>num2?num1:numb2; // return the highest number.
return max;
}
EDIT: Since you mentioned that you are new to programming, let me add few more detail. If you are in a method A and you call a method B, some amount of space in the stack segment is reserved so that the control knows the line location in method A to resume execution after completing method B. In your case, the max method calls max method again and again. This directly means that more and more space in stack segment gets reserved for each method call. And at some point, it runs out of available space in stack memory and you would end up with such StackOverflow problem.
In general, any method calling itself without modifying the inputs is a red flag in most scenario. This is the case with your max method.
In your max(int num1, int num2) there is no logic, it's just calling itself so will never end:
use like below:
import java.io.*;
import java.util.Scanner;
public class MethodLab {
public static void main(String[] args) {
// variable declarations for part 1
String title;
String firstName;
String lastName;
Scanner in = new Scanner(System.in);
// prompt for input for part 1
System.out.print("Enter a title:");
title = in.next();
System.out.print("Enter your first name:");
firstName = in.next();
System.out.print("Enter a your last name:");
lastName = in.next();
// call the method for part 1
greeting(title, firstName, lastName);
// variable declarations for part 2
int number1;
int number2;
// user prompts for part 2
System.out.print("Enter first number:");
number1 = in.nextInt();
System.out.print("Enter second number:");
number2 = in.nextInt();
// call the method for part 2 inside the println statement
System.out.println("The largest number is " + max(number1, number2));
}
/******************** greeting method goes here*********************/
public static void greeting(String proper, String fname, String lname){
System.out.println();
System.out.printf("Dear " + proper +" "+ fname + " "+ lname);
System.out.println();
}
/***********************end of method*************************/
/******************** max method goes here*********************/
public static int max(int num1,int num2){
return num1 > num2 ? num1 : num2;
}
i am trying to enter a book title "hoopa doopa"into my object array. when i try it throws a java.util.InputMismatchException.If i enter a string that has no spaces like"hoopa" the code will run fine all of the way through. What is causing this and how can I fix it? please help thanks
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int counter = 0;
int numberOfProducts=0; //variable for when the user is asked to enter input the number of products to be entered
do { //this will validate the user input
System.out.println("How many products would you like to enter");
while (!input.hasNextInt()) {
System.out.println("That's not a number!");
input.next(); // this is important!
}
numberOfProducts = input.nextInt();
} while (numberOfProducts <= 0);
//end of the do while loop
Products[] products;
products = new Products[numberOfProducts+4];//create a array the size of the user input that was gathered
for (int i=0;i<numberOfProducts;i++)
{
products[i+4]= new Products(); // create each actual Person
System.out.println("What is the product #: ");
products[i+4].setItemNumber(input.nextInt());
System.out.println("What is the book name: ");
products[i+4].setNameOfProduct(input.next());
System.out.println("How many are in stock: ");
products[i+4].setUnitsInStock(input.nextInt());
System.out.println("What is the cost of the Item: ");
products[i+4].setPrice(input.nextDouble());
counter++;
}
products[0] = new Products(0001,"The Red Rose",1,29.99);
products[1] = new Products(0002,"The Bible",3,11.99);
products[2] = new Products(0003,"End of the Programm",2,29.99);
products[3] = new Products(0004,"WHAT!!! the....",1,129.99);
//____________________________________________________________4 products that are already made
for (int i=0;i<numberOfProducts+4;i++)
{
System.out.println(products[i].toString());
input.nextLine();
}
}
}
this is the other class
import java.text.NumberFormat;
public class Products
{
private int itemNumber;
private String nameOfProduct;
private int unitsInStock;
private double unitPrice;
public Products()
{
itemNumber = 0;
nameOfProduct = null;
unitsInStock = 0;
unitPrice = 0.0;
}
public Products(int num,String name,int inStock,double price)
{
itemNumber = num;
nameOfProduct = name;
unitsInStock = inStock;
unitPrice = price;
}
public int getItemNumber()
{
return itemNumber;
}
public void setItemNumber(int newValue)
{
itemNumber=newValue;
}
//----------------------------------------------
public String getNameOfProduct()
{
return nameOfProduct;
}
public void setNameOfProduct(String newValue)
{
nameOfProduct=newValue;
}
//----------------------------------------------
public int getUnitsInStock()
{
return unitsInStock;
}
public void setUnitsInStock(int newValue)
{
unitsInStock = newValue;
}
//-----------------------------------------------
public double getPrice()
{
return unitPrice;
}
public void setPrice(double newValue)
{
unitPrice = newValue;
}
//_______________________________________________
public double calculateTotalItemValue() //method that uses quantity on hand and price part3 1.A
{
return getUnitsInStock()* getPrice();
}//end of method
#Override
public String toString()
{
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
return"\nItem Number: "+getItemNumber() +
"\nItem Name: "+getNameOfProduct()+
"\nItem Quantity: " +getUnitsInStock()+
"\nItemPrice:" +currencyFormat.format(getPrice())
+"\nValue of Inventory: " +currencyFormat.format(this.calculateTotalItemValue());//part3 1.B
}
}
The Scanner sees the space in the book name as a delimiter since you are using the next() method. So when you go to read the nextInt() for the stock amount, the Scanner index is after the space in the book name String, and pulls in the remaining String data, which doesn't convert to an int. Instead, try something like this:
System.out.println("What is the book name: ");
input.nextLine();
products[i+4].setNameOfProduct(input.nextLine());
If you do not add the input.nextLine();, then it will appear as though the book name prompt gets skipped.
Scanner input = new Scanner(System.in);
Actually you are using scanner to get input and by default scanner delimiter is space. So you have to change the default delimiter of your code.
I think this is your problem:
products[i+4].setNameOfProduct(input.next());
What input.next() does is it reads the input from the user, until it reaches white space (the space between hoopa doopa). The function then passes hoopa to the setNameOfProduct method, and then passes doopa to the nextInt function, which gives a runtime error.
To fix your problem I would code
products[i+4].setNameOfProduct(input.nextLine());
Edit:
nextLine() function passes all characters up to the carriage return
Problem :
products[i+4].setNameOfProduct(input.next());
Solution 1 :
Just create another Scanner object for reading input with spaces
Scanner sc1=new Scanner(System.in);
products[i+4].setNameOfProduct(sc1.nextLine());
Solution 2 :
Or to use same scanner object
input.nextLine(); //Include this line before getting input string
products[i+4].setNameOfProduct(input.nextLine());
the question is :
A fruit shop sells several types of fruits each day. Write a program that reads from user several lines of input.Each line includes a fruit's name,price per kilogram (as an integer), number of kilograms sold (as an integer).
the program should calculate and print the earned money of all fruits sold and fruit that achieved largest profit.
hint: -you could assume that user will insert valid data -user could stop the program via entering the word "stop" as a fruit's name.
Sample input and out put:
in each line, insert a fruit's name, price per kilogram, number of kilograms sold. To halt the program,insert "stop" as a fruit's name
banana 2 11
mango 3 8
peach 4 5
stop
the earned money of all fruits sold: 66
fruit that achieved the largest profit: mango
what i wrote now:
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname= " ";
String maxfruit = " ";
int price = 0,number=0;
int sum=0;
int max=0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
if (fruitname.equals("stop"))
{
sum = sum+(price*number);
}
if (max<(price*number))
{
max = price*number;
maxfruit = fruitname;
}
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
the program is not reading what i submit to it, don't know why and not giving me the sum and the max fruit.. what is the problem of what i wrote?
As you can see your reads happen in the while loop:
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
Every time it loops - it overrides the values. Finally when you read stop and exit the loop - your fruitname is stop. So you need to fix your logic on how you would want to read in the input
Working variant:
public class FruitTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
String text = input.nextLine();
String[] words = text.split(" ");
List<Fruit> fruits = parseInput(words);
int sum = getSum(fruits);
String popular = getPopularFruitName(fruits);
System.out.println("Got fruits: " + fruits.toString());
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is " + popular);
}
private static String getPopularFruitName(List<Fruit> fruits) {
int max = 0;
String name = null;
for (Fruit fruit : fruits) {
int checkVal = fruit.getPrice() * fruit.getAmount();
if(checkVal > max) {
max = checkVal;
name = fruit.getName();
}
}
return name;
}
private static int getSum(List<Fruit> fruits) {
int result = 0;
for (Fruit fruit : fruits) {
result += fruit.getPrice() * fruit.getAmount();
}
return result;
}
private static List<Fruit> parseInput(String[] words) {
List<Fruit> result = new ArrayList<Fruit>();
int element = 1;
final int name = 1;
final int price = 2;
final int amount = 3;
Fruit fruit = null;
for (String word : words) {
if (word.equals("stop") || word.isEmpty()) {
break;
}
if(element > amount)
element = name;
switch (element) {
case name:
fruit = new Fruit(word);
result.add(fruit);
break;
case price:
if (fruit != null) {
fruit.setPrice(Integer.valueOf(word));
}
break;
case amount:
if(fruit != null) {
fruit.setAmount(Integer.valueOf(word));
}
break;
}
element++;
}
return result;
}
static class Fruit {
String name;
int price = 0;
int amount = 0;
Fruit(String name) {
this.name = name;
}
String getName() {
return name;
}
int getPrice() {
return price;
}
void setPrice(int price) {
this.price = price;
}
int getAmount() {
return amount;
}
void setAmount(int amount) {
this.amount = amount;
}
#Override
public String toString() {
return name + ". $" + price +
", amount=" + amount;
}
}
}
Comments to code - it's proper way to parse all the inputted string and parse it to an object that stores all the data - name, price and amount. Store all parsed objects into array or a list and then calculate max and popular fruit while looping your parsed fruit array
I found some mistake. The most important was in the while condition. Check this out.
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname = null;
String maxfruit = null;
int fruitSum = 0;
int totalSum = 0;
int max = 0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while(!(fruitname = input.next()).equals("stop")){
fruitSum = input.nextInt() * input.nextInt();
totalSum += fruitSum;
if(fruitSum > max){
maxfruit = fruitname;
max = fruitSum;
}
}
System.out.println("the earned money of all fruits is " + totalSum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
Oh it is reading it.
the problem is that it doesn't do what you want it to do.
the problems with the code I can see are this:
you are not storing the fruits quantities or prices anywhere, you need to store the values
in an array or something (maxFruit,MaxValue) to compare them later.
when you are reading the fruit values and a "stop" string is input the next step in your code is to wait for the price so it won't get out of the loop even if you input "stop", you need to restructure your scanner loop.
And if it is a beginner class it may be ok, but the code you are writing is not object oriented don't write the logic in the main.
You may want to learn to debug it is a very useful tool when you are learning to code, if you run this program in debug mode , you could see that the values are getting input and everything that is happening, Netbeans and Eclipse have very good debuggers and it would be worth to expend half an hour learning the basics of debugging It certainly helped me a lot when I was starting.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class FruitSells {
public static void main(String... args) {
BufferedReader bufer = new BufferedReader(new InputStreamReader(System.in));
try {
String str;
String[] inarr;
int sumMoney = 0;
do {
str = (String) bufer.readLine();
inarr = str.split(" ");
for(int i = 1; i < inarr.length; i += 3) {
sumMoney += Integer.parseInt(inarr[i]) * Integer.parseInt(inarr[i + 1]);
}
System.out.println(sumMoney);
sumMoney = 0;
} while (!str.equals("stop"));
} catch(IOException ex) {
System.out.println("Problems with bufer.readLine()");
}
}
}
something like this you can modernize it.sorry for eng i can not speak))and write correctly of course))
I have some trouble regarding my lab assignment:
When my program tries to prompt the user for input, the program outputs two questions on the same line and only takes the input for the second question.
The output of my program:
Please enter the name of the second employee:Please enter the number of the second employee:1
(They appear on the same line instead of separate lines)
Also the output for an array outputs like this:
0.00.00.00.00.00.00.00.00.00.0
instead of like this:
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
I'm not quite sure how to fix these two any help would be appreciated!
Here is my code:
Employee.java
//import java.util.*;
public class Employee
{
private String empName;
private int empNumber;
private String empAddress;
private double empSalary;
private double[] empBonus=new double[10];
public Employee(){}
public Employee(String empName_, int empNumber_, String empAddress_, double empSalary_, double[] empBonus_)
{
this.empName=empName_;
this.empNumber=empNumber_;
this.empAddress=empAddress_;
this.empSalary=empSalary_;
this.empBonus=empBonus_;
}
public String getName()
{
return this.empName;
}
public int getEmployeeNumber()
{
return this.empNumber;
}
public String getAddress()
{
return this.empAddress;
}
public double getSalary()
{
return this.empSalary;
}
public String changeAddress(String chAddress)
{
return empAddress=chAddress;
}
public double changeSalary(double chSalary)
{
return empSalary=chSalary;
}
public String addBonus(double[] empBonus)
{
String arrayBonus=new String("");
for(int i=0; i<empBonus.length;i++)
{
arrayBonus+=empBonus[i];
}
return arrayBonus;
}
public String toString()
{
return ("\nEmployee's name: "+empName+"\nEmployee's Number: "+empNumber+"\nEmployee's address: "+empAddress+
"\nEmployee's original salary: "+empSalary+ "\nEmployee's bonuses: "+addBonus(empBonus)+"\n");
}
}
EmployeeTester.java
import java.util.*;
public class EmployeeTester
{
public static void main(String[] args)
{
Scanner in1=new Scanner(System.in);
Scanner in2=new Scanner(System.in);
Scanner in3=new Scanner(System.in);
Employee emp1;
Employee emp2;
emp1=read_input("first", in1, in2, in3);
emp2=read_input("second", in1, in2, in3);
System.out.println(emp1.toString());
System.out.println(emp2.toString());
}
public static Employee read_input(String msg, Scanner scan1, Scanner scan2, Scanner scan3)
{
String name, address;
int num;
double salary;
double[] bonus=new double[10];
System.out.print("\nPlease enter the name of the "+msg+" employee:");
name=scan1.nextLine();
System.out.print("Please enter the number of the "+msg+" employee:");
num=scan2.nextInt();
System.out.print("Please enter the address of the "+msg+" employee:");
address=scan1.nextLine();
System.out.print("Please enter the salary of the "+msg+" employee:");
salary=scan3.nextDouble();
System.out.print("Please add a bonus for the "+msg+" employee:");
bonus[0]=scan3.nextDouble();
System.out.print("Add more bonuses to the "+msg+"employee? (y/n) \nNote: Enter 0.0 if you would like to terminate adding more bonuses: ");
if(scan1.next().startsWith("y"))
{
for(int i=1; i<bonus.length;i++)
{
System.out.print("Continue entering a bonus to "+msg+" employee:");
bonus[i]=scan3.nextDouble();
if(bonus[i]==0.0 || i==bonus.length)
{
break;
}
}
}
return new Employee(name, num, address, salary, bonus);
}
}
For your first problem just shift your Scanners inside your read_input method so they start fresh each time.
public static void main(String[] args) {
Employee emp1;
Employee emp2;
emp1 = read_input("first");
emp2 = read_input("second");
System.out.println(emp1.toString());
System.out.println(emp2.toString());
}
public static Employee read_input(String msg) {
Scanner scan1 = new Scanner(System.in);
Scanner scan2 = new Scanner(System.in);
Scanner scan3 = new Scanner(System.in);
...
For your second problem, in your addBonus method where you build the output string you are not adding any spaces or commas. Also it is a lot more efficient if you use a StringBuilder for this type of looped concatenation rather than repeatedly creating new string objects.
public String addBonus(double[] empBonus)
{
StringBuilder arrayBonus = new StringBuilder();
for(int i=0; i<empBonus.length;i++)
{
arrayBonus.append(empBonus[i] + ", ");
}
return arrayBonus.toString();
}
You do not need 3 different scanners, one will do.
For the printing part, you need println() or use '\n' for new lines.
E.g.:
System.out.println("Please enter the name of the "+msg+" employee:");
System.out.print("Please enter the name of the "+msg+" employee:\n");
In the first case, you are calling a function (println() instead of print()) that automatically appends a new-line to the outputes text. In the second case you are making the new-line part of the string (which you already used in the beginning of the first line printed)
The array output uses 0.0 because the values are floting point values (double in your case), which by default prints decimal parts. To only print the integer part, you will need to cast the value to an integer or use formatting for the double.
Casting:
double a = 0.0;
System.out.print("'a' as integer: " + ((int)a));
Formatting:
System.out.format("Here is a number: %.0f", a);
The number between the . and f specifies how many decimal places to output.