Confused on making an array of a class [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So I have this code already pre-written for me
public class Car
{
private String make;
private int yearModel;
private double price;
private int mileage;
public Car (String mk, int year, double pr, int miles)
{
make = mk;
yearModel = year;
price = pr;
mileage = miles;
}
public String getMake()
{
return make;
}
public int getYearModel()
{
return yearModel;
}
public double getPrice()
{
return price;
}
public int getMileage()
{
return mileage;
}
public String toString()
{
return "Make: " + make+"\n"+"YearModel: " + yearModel +"\n"+
"Price: $" + price +"\n" + "Mileage: "+ mileage + " miles\n\n";
}
}
My task is to first prompt the user for the number of cars on a car lot. Then create an array of Car to hold the input number of cars. Then fill the array with the info of every car on the carlot. I know the general concept, but when I'm trying to input a String, it says a type mismatch with the array Cars only allowing for the type Car. I'm confused what that is and how to get around it. Here's my code.
import java.util.Scanner;
public class CarLot {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input number of cars: ");
Car [] Cars = new Car [input.nextInt()];
for(int i = 0; i < Cars.length; i++) {
System.out.println("Make");
Cars[i] = input.nextLine();
System.out.println("Model");
Cars[i] = input.nextLine();
System.out.println("Price");
Cars[i] = input.nextLine();
System.out.println("Mileage");
Cars[i] = input.nextLine();
System.out.println();
}
input.close();
}
}

It's important to note that Scanner .nextLine() does not return a Car, it returns a String. You need to make a Car out of the inputs.
So in the loop you should do something like this (I made the cars variable name lowercase to follow Java naming conventions):
System.out.println("Make");
String make = input.nextLine();
System.out.println("Model");
String model = input.nextLine();
System.out.println("Price");
double price = input.nextDouble();
System.out.println("Mileage");
int mileage = input.nextInt();
cars[i] = new Car(make, model, price, mileage);

Related

Why does the method only return 0 ? (Java) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
The idea of this program is to calculate the person's weight and age on each planet. and Life class is supposed to be the one who do the calculations and return the values correctly.
my problem is when i run the program it returns 0 ! but I want it to do the calculations and return different values.
Person Class
package solarsystemplanets;
public class Person {
private String name;
public int age;
public double weight;
//Constructors
public Person(String n, int a, double w) {
n = name;
a = age;
w = weight;
}
public Person(){
name = "";
age = 0;
weight = 0;
}
//Setters (Mutator)
public void setName(String n) {
n = name;
}
//Getters (Accessor)
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
//PrintDetails Method
public String toString() {
return "Person" + " name=" + name + ", age=" + age + ", weight="
+ weight;
}
}
Life Class
package solarsystemplanets;
public class Life extends Person {
private int earthDays;
public double []surfaceGravity;
public int []planetsDays;
//Constructors
public Life (int e, double []s, int []p){
earthDays = e;
surfaceGravity = s;
planetsDays = p;
}
public Life (int ee){
earthDays = 365;
surfaceGravity = new double[]{0.38,0.91,1.0,0.38,2.34,0.93,0.92,1.12};
planetsDays = new int[]{88,225,365,2,12,29,84,165};
}
public Life(){
this.surfaceGravity = new double[]{0.38,0.91,1.0,0.38,2.34,0.93,0.92,1.12};
this.planetsDays = new int[]{88,225,365,2,12,29,84,165};
}
//Setters (Mutator)
public void setEarthDays(int e) {
earthDays = e;
}
//Getters (Accessor)
public int getEarthDays() {
return earthDays;
}
public double[] getSurfaceGravity() {
double array1[] = new double[surfaceGravity.length];
for(int i =0; i < surfaceGravity.length; i++){
array1[i] = weight * surfaceGravity[i];
}
return array1;
}
public int[] getPlanetsDays() {
int array2[] = new int[planetsDays.length];
for(int i =0; i < planetsDays.length; i++){
array2[i] = (age * getEarthDays())/ planetsDays[i];
}
return array2;
}
//PrintDetails Method
public String toString(int i) {
return "surfaceGravity=" + getSurfaceGravity() + ", planetsDays=" + getPlanetsDays();
}
}
Main
package solarsystemplanets;
import java.util.*;
import java.io.*;
public class SolarSystemPlanets {
public static void main(String[] args) throws IOException {
Person person = new Person();
Life life = new Life();
Planet planet = new Planet();
Scanner input = new Scanner (System.in);
File file = new File ("Solar System Planets");
//User Info
System.out.println("What is Your Name ? ");
person.setName(input.nextLine());
System.out.println("Please Enter Your Age: ");
person.age = input.nextInt();
while (person.age <=0){
System.out.println("error. Please Enter Your Age Again: ");
person.age = input.nextInt();
}
System.out.println("Please Enter Your Weight: ");
person.weight = input.nextInt();
while (person.weight <=0){
System.out.println("error. Please Enter Your Weight Again: ");
person.weight = input.nextInt();
}
for(int i =0; i<planet.planetName.length; i++){
System.out.println(planet.planetName[i]);
System.out.println("Your Weight = " + life.getSurfaceGravity()[i] + "
Your Age = " + life.getPlanetsDays()[i]);
}
}
}
You are setting user inputs on person object and using life object to calculate and print data. As these objects are different fields in life object remains zero.
Life extends Person, so it has inherited person fields. Set all user inputs on life object.
Also, you've forgot to set earthDays on life object.

How do I get data into a constructor from two different loops

I have a homework assignment to Create an app that allows users to enter information about a collection of board games. The data entered by the user will be stored/accessed through a class. The steps I am given are to create the class, named BoardGame, for storing a collection of (analog or non-digital) board games with 8 fields. I then make a constructor that stores ONLY the first three fields. Then, for all fields, I create individual get and set methods, along with a toString method to print all the data for all the fields. Then within the main method there are 3 parts. Part 1, create an array called boardGames that has an array size of 4 (Right now I just have it set to 1 for testing). Create a loop to ONLY get the first three pieces of information. Part 2. AFTER the three basic pieces of the board game have been entered by the user, create a second loop to get the remaining five information from the user. Part 3. Once all the remaining data has been entered and stored by the user, create a third loop to print all the data in the array using the toString method (from the BoardGame class) for each object.
I think everything in BoardGame is set up correctly. I can also get Either step 1 or step 2 working with step 3. the issue is that I can't get step 1 AND step 2 to work at the same time. the Array either has the first 3 pieces of info or the last 5 pieces
I have tried making multiple constructors. I have tried a bunch of stuff that are probably all rookie errors XD
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
BoardGame[] boardGame = new BoardGame[1];
// Loop for first three peices of info
for (int i = 0; i < boardGame.length; i++) {
String gameName, publisherName, yearPublished;
System.out.print("What is the name of the board game? ");
gameName = scnr.nextLine();
System.out.print("Publisher name? ");
publisherName = scnr.nextLine();
System.out.print("Year published? ");
yearPublished = scnr.nextLine();
boardGame[i] = new BoardGame (gameName, publisherName, yearPublished);
}
// Loop for remaining peices of info
for (int i = 0; i < boardGame.length; i++) {
String genre;
double price;
int minPlayerNum, maxPlayerNum, playTime;
System.out.print("How much does " + boardGame[i].getGameName() + " cost? ");
price = scnr.nextDouble();
System.out.print("What is the minimum number of players for " + boardGame[i].getGameName() + "? ");
minPlayerNum = scnr.nextInt();
System.out.print("What is the maximum number of players for " + boardGame[i].getGameName() + "? ");
maxPlayerNum = scnr.nextInt();
System.out.print("What is the game genre? ");
scnr.nextLine();
genre = scnr.nextLine();
System.out.print("How long on average does it take to play " + boardGame[i].getGameName() + " (in minutes)? ");
playTime = scnr.nextInt();
boardGame[i] = new BoardGame (price, minPlayerNum, maxPlayerNum, genre, playTime);
}
for (int i = 0; i < boardGame.length; i++) {
System.out.println(boardGame[i].toString());
System.out.println();
}
}
}
public class BoardGame {
// Fields
private String gameName;
private String publisherName;
private String yearPublished;
private double price;
private int minPlayerNum;
private int maxPlayerNum;
private String genre;
private int playTime;
// Constructor 1
public BoardGame(String gameName, String publisherName, String yearPublished) {
this.gameName = gameName;
this.publisherName = publisherName;
this.yearPublished = yearPublished;
}
// Constructor 2
public BoardGame(double price, int minPlayerNum, int maxPlayerNum, String genre, int playTime) {
this.price = price;
this.minPlayerNum = minPlayerNum;
this.maxPlayerNum = maxPlayerNum;
this.genre = genre;
this.playTime = playTime;
}
// Get Methods
public String getGameName() {
return gameName;
}
public String getPublisherName() {
return publisherName;
}
public String getYearPublished() {
return yearPublished;
}
public double getPrice() {
return price;
}
public int getMinPlayerNum() {
return minPlayerNum;
}
public int getMaxPlayerNum() {
return maxPlayerNum;
}
public String getGenre() {
return genre;
}
public int getPlayTime() {
return playTime;
}
// Set Methods
public void setGameName(String gameName) {
this.gameName = gameName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
public void setYearPublished(String yearPublished) {
this.yearPublished = yearPublished;
}
public void setPrice(double price) {
this.price = price;
}
public void setMinPlayerNum(int minPlayerNum) {
this.minPlayerNum = minPlayerNum;
}
public void setMaxPlayerNum(int maxPlayerNum) {
this.maxPlayerNum = maxPlayerNum;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setPlayTime(int playTime) {
this.playTime = playTime;
}
// Prints the data FIX_ME if min and max number of players is the same, only print one number
public String toString() {
return "Game name: " + gameName + "\nPublisher Name: " + publisherName +
"\nYear Published: " + yearPublished + "\nPrice: " + price +
"\nMinimum number of players: " + minPlayerNum + "\nMaximum number of players: "
+ maxPlayerNum + "\ngenre: " + genre + "\nPlay time: " + playTime;
}
}
`
Depending on how I have it set up, either the first three won't have an assigned value, or the last 5 won't. It is currently set up in a way that makes the first three data pieces null.
In your second loop, instead of overriding the current BoardGame object by a new one like in your current code:
boardGame[i] = new BoardGame (price, minPlayerNum, maxPlayerNum, genre, playTime);
You should retrieve the BoardGame already stored in your array by the first loop, and call your setters on it:
boardGame[i].setPrice(price);
boardGame[i].setMinPLayerNum(minPlayerNum);
//etc...
Like so, you won't be overriding/replacing any values, you are just adding properties to the already created object.

Java passing class array into array

I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).
Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).
I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.
public class CollegeCourse {
private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
courseId=id;
creditHours = hours;
this.grade = grade;
}
public void setCourseId(String id)
{
courseId = id;//Assign course id to local variable
}
public String getCourseId()
{
return courseId;//Provide access to course id
}
public void setHours(int hours)
{
creditHours = hours;//Assign course id to local variable
}
public int getHours()
{
return creditHours;//Provide access to course id
}
public void setGrade(char grade)
{
this.grade = grade;//Assign course id to local variable
}
public char getGrade()
{
return grade;//Provide access to course id
}
}
Student Class
public class Student {
final int NUM_COURSES = 5;
private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];
//constructor using user input
public Student(int studentId)
{
this.studentId=studentId;
}
public void setStudentId(int id)
{
studentId = id;//Assign course id to local variable
}
public int getStudentId()
{
return studentId;//Provide access to course id
}
public void setCourse(int index, CollegeCourse course)
{
courses[index] = course;
}
public CollegeCourse getCourse(int index)
{
return courses[index];
//do I need code to return the courseId hours, grade
}
}
InputGrades Class
import java.util.Scanner;
public class InputGrades {
public static void main(String[] args) {
final int NUM_STUDENTS = 2;
final int NUM_COURSES = 3;
Student[] students = new Student[NUM_STUDENTS];
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
//String gradeInput;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + (s+1) + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
csIndex=c;
System.out.print("Enter course ID #" + (c+1) + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
System.out.println();
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}
After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
You should add a very simple length validation when you input the grade:
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
so the full main class code:
import java.util.Scanner;
/**
* Created by dkis on 2016.10.22..
*/
public class App {
public static void main(String[] args) {
final int NUM_STUDENTS = 10;
final int NUM_COURSES = 5;
Student[] students = new Student[NUM_STUDENTS];
//String name;
int s;//subscript to display the students
int c;//subscript to display courses
int stId;
int csIndex;
String courseId = "";
int hours = 0;
char grade = 'z';
CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly
Scanner input = new Scanner(System.in);
for(s = 0; s<NUM_STUDENTS; ++s)
{
students[s] = new Student(s);
System.out.print("Enter ID for student #" + s+1 + ":");
stId = input.nextInt();
input.nextLine();
students[s].setStudentId(stId);
for(c=0; c < NUM_COURSES; ++c)
{
//CollegeCourse course = students[s].getCourse(c);
csIndex=c;
System.out.print("Enter course ID#" + c+1 + ":");
courseId = input.nextLine();
course.setCourseId(courseId);
System.out.print("Enter hours:");
hours = input.nextInt();
input.nextLine();
course.setHours(hours);
String enteredGrade = "";
while(enteredGrade.length()!=1) {
System.out.print("Enter grade:");
enteredGrade = input.nextLine();
if(enteredGrade.length()==1) {
grade = enteredGrade.charAt(0);
} else {
System.out.println("Type only one character!");
}
}
course.setGrade(grade);
students[s].setCourse(csIndex, course);
}
}
for(s = 0; s<NUM_STUDENTS; ++s)
{
System.out.print("\nStudent# " +
students[s].getStudentId());
for(c=0;c<NUM_COURSES;++c)
System.out.print(students[s].getCourse(c) + " ");
System.out.println();
}
}
}

User enters what he wants, as well as price and amount [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My program should ask the user for the name, the price as well as the amount of what he wants, until he presses "x". At this point the program should print the receipt.
How can I save all the user inputs without knowing how many items he wishes to buy?
I am using three classes. I do not know how to give the names, amounts, prices from the Main-class to the class Eintrag.
How do I call the list from the Kassenzettel class in the main for me to print?
Also, I override the to String method, for my receipt to "supermarket-like", will this formatting be applied in the main class?
here is my main -class:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.println("What would you like? ");
String produkt = scanner.nextLine();
System.out.println("How many pieces do you want?");
int anzahl = scanner.nextInt();
System.out.println("How much does " + produkt + "cost?");
double preis = scanner.nextDouble();
//Im not even sure if that should be there
Kassenzettel list =new Kassenzettel();
Eintrag carrots = new Eintrag("carrots", 5, 0.40);
Kassenzettel.add(carrots);
System.out.println("__________________________________");
System.out.println(" IHRE RECHNUNG ");
System.out.println("__________________________________");
}
}
My Eintrag-class:
public class Eintrag {
private String produkt;
private double preis;
private int anzahl;
public Eintrag(String produkt, int anzahl, double preis) {
this.anzahl=anzahl;
this.produkt=produkt;
this.preis=preis;
}
public int getAnzahl(){
return this.anzahl;
}
public double getPreis(){
return this.preis * this.anzahl;
}
public String getProdukt() {
return this.produkt;
}
public void setAnzahl(int anzahl) {
this.anzahl = anzahl;
}
public String toString() {
return (String.format("%-9s %2d x %5.2f EUR",produkt , anzahl, preis
+ "%30.2f EUR", anzahl * preis));
}
}
My Kassenzettel class, which should consist of a list of Eintrag objects
import java.util.ArrayList;
public class Kassenzettel {
private static ArrayList<Eintrag> kassenZettel;
private double summe;
// Constructs a new empty grocery list.
public static void add(Eintrag item) {
kassenZettel.add(item);
}
#Override
public String toString() {
return (String.format("%-9s %2d x %5.2f EUR",kassenZettel
+ "%30.2f EUR"
+ "SUMME", summe));
}
}
Not sure, if i got, what you want, but you can use something like this:
change the toString method of Kassenzettel to:
double sum = 0;
String ret = "";
for(int i = 0; i< kassenZettel.size(); i++){
ret += kassenZettel.get(i).toString()+"\r\n";
sum += kassenZettel.get(i).getPreis();
}
ret += "\r\nSumme: "+sum;
The next point, you have to make a loop for user input:
Scanner scanner = new Scanner(System.in);
//create an instance of kassenzettel to add your produkts to
Kassenzettel list =new Kassenzettel();
//set variable to check if read or not (not needed if using break!)
boolean readOn = true;
//loop for reading until user inputs x or X
while(readOn){
System.out.println("What would you like? ");
String produkt = scanner.nextLine();
//check if produkt name is X or x => exit the loop
if(produkt.equalsIgnoreCase("x")){
readOn = false;
break;
}
System.out.println("How many pieces do you want?");
int anzahl = scanner.nextInt();
System.out.println("How much does " + produkt + "cost?");
double preis = scanner.nextDouble();
//add a new item to kassenzettel
list.add(new Eintrag(produkt, anzahl, preis));
}
//print the output of kassenzettel
System.out.println(list.toString());
EDIT:
and remove:
//Im not even sure if that should be there
Kassenzettel list =new Kassenzettel();
Eintrag carrots = new Eintrag("carrots", 5, 0.40);
Kassenzettel.add(carrots);
Working code:
http://pastebin.com/3acgm5St

Java assignment don't know what is the mistake

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))

Categories

Resources