Need a way to associate strings with individual array elements - java

I am a complete beginner in programming and I'm working on a program for my mother that tracks her employee's monetary intake through a "horse race", with each employee having a horse and the program tracking their input to a UI made to look like a racetrack. After the help from my last inquiry, I've greatly simplified my mess of code but I am now faced with a new problem in that, after sorting the values largest to smallest, I have no way of associating the sorted values with the correct horse. I understand this explanation is confusing so I hope my code will do most of the talking for me here.
I honestly have no idea where to start with this. As I said in my last inquiry, I'm a complete beginner and severely lack the terminology or knowledge to find an answer here.
public class HorseRace {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String horse1 = "#5 Gitty-Up";
String horse2 = "#7 Lady Simmons";
String horse3 = "#6 Burning Peanutbutter";
String horse4 = "#10 White Lightning";
String horse5 = "#3 Bella";
String horse6 = "#1 Meg The Stallion";
float h1val;
float h2val;
float h3val;
float h4val;
float h5val;
float h6val;
System.out.println("Input amount for " + horse1 + ":");
h1val = sc.nextFloat();
System.out.println("Input amount for " + horse2 + ":");
h2val = sc.nextFloat();
System.out.println("Input amount for " + horse3 + ":");
h3val = sc.nextFloat();
System.out.println("Input amount for " + horse4 + ":");
h4val = sc.nextFloat();
System.out.println("Input amount for " + horse5 + ":");
h5val = sc.nextFloat();
System.out.println("Input amount for " + horse6 + ":");
h6val = sc.nextFloat();
Float[] values = new Float[]{h1val, h2val, h3val, h4val, h5val, h6val};
Arrays.sort(values, Collections.reverseOrder());
//currently displays horses with the wrong number. Need a way to tie the horse name strings to their respective float elements
System.out.println("The current race progress is :");
System.out.println(horse1 + " with $" + values[0]);
System.out.println(horse2 + " with $" + values[1]);
System.out.println(horse3 + " with $" + values[2]);
System.out.println(horse4 + " with $" + values[3]);
System.out.println(horse5 + " with $" + values[4]);
System.out.println(horse6 + " with $" + values[5]);
}
}
my desired result is printing the correct horse with the correct value. For example, if I put that #5 brought in $11 and #7 brought in $14, the program would print that #7 is in the lead with $14 and #5 is in second place with $11.
Currently, the program always prints #5 as being in the lead with the highest value, #7 being in second with the second highest, etc.
I understand this is because I am hard calling the horse1-horse6 values meaning they don't change, but these are acting more as placeholders while I figure out how to associate the right horse with the right value

This is where you should create a Horse class and store the data as instances of Horse.
class Horse {
private String name;
private float value;
public String getName() { return name; }
public float getValue() { return value; }
public void setName(String name) { this.name = name; }
public void setValue(float value) { this.value = value; }
}
And then in your main method:
Horse[] horses = new Horse[6] {
new Horse(), new Horse(), new Horse(), new Horse(), new Horse(), new Horse()
};
horses[0].setName("#5 Gitty-Up");
horses[1].setName("#7 Lady Simmons");
horses[2].setName("#6 Burning Peanutbutter");
// and so on...
// you should use a for loop here instead of writing similar lines over and over again!
for (int i = 0 ; i < 6 ; i++) {
System.out.println("Input amount for " + horses[i].getName() + ":");
horses[i].setValue(sc.nextFloat());
}
Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());
System.out.println("The current race progress is :");
for (int i = 0 ; i < 6 ; i++) {
System.out.println(horses[i].getName() + " with $" + horses[i].getValue());
}
By using a class, you are essentially grouping data that belongs together, together. On the line Arrays.sort(horses, Comparator.comparingDouble(Horse::getValue).reversed());, I am sorting the whole array of horses together, by their values.
If the concepts of classes and objects are new to you, that just means it's time to learn about some new concepts. Classes and objects are very important.

Step 1, create a Horse class. It should have two fields, amount and name. It should implement Comparable because you want to sort it. And looking at your desired output, I would override toString().
class Horse implements Comparable<Horse> {
private String name;
private float amount;
public Horse(String name, float amount) {
this.name = name;
this.amount = amount;
}
#Override
public String toString() {
return String.format("%s with $%.2f", name, amount);
}
#Override
public int compareTo(Horse o) {
return Comparator.comparing((Horse h) -> h.amount)
.thenComparing((Horse h) -> h.name).compare(this, o);
}
}
Step 2, create an array of horseNames and iterate that populating an array of Horses (with amounts). Then sort it, and I would prefer Comparator.reverseOrder() to Collection.reverseOrder() when sorting an array.
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String[] horseNames = { "#5 Gitty-Up", "#7 Lady Simmons",
"#6 Burning Peanutbutter", "#10 White Lightning",
"#3 Bella", "#1 Meg The Stallion" };
Horse[] horses = new Horse[horseNames.length];
for (int i = 0; i < horseNames.length; i++) {
System.out.printf("Input amount for %s:%n", horseNames[i]);
float amt = sc.nextFloat();
horses[i] = new Horse(horseNames[i], amt);
}
Arrays.sort(horses, Comparator.reverseOrder());
System.out.println("The current race progress is :");
for (int i = 0; i < horses.length; i++) {
System.out.println(horses[i]);
}
}

Related

How do I populate a String array using a for loop [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
Please bear in mind that I am a beginner.
I have written the following code to try to populate a String array. It runs but will not print out the contents of the String array positions. (The same thing seems to work no problem for the double Array!)I do not understand why this is. If anyone could help me solve this problem I would be extremely grateful. See below for the code of the Main Class and a class called Fruit which contains the methods I am using.
`enter code here`Main class:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Fruit fruit = new Fruit();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of items in your shopping list:");
int listSize = scanner.nextInt();
String[] sl = new String[listSize];
double[] price = new double[listSize];
//Loop asking user to enter items and prices
for(int i = 0; i <= listSize - 1; i++)
{
System.out.println("Enter item " + (i+1) + ":");
fruit.setName(scanner.nextLine());
sl[i] = fruit.getName();
scanner.next();
System.out.print("Price of " + sl[i] + ":");
fruit.setPrice(scanner.nextDouble());
price[i] = fruit.getPrice();
}
//Loop printing items and their prices
for(int i = 0; i <= listSize - 1; i++)
{
System.out.println(sl[i] + " cost " + price[i]);
}
//Order the array in ascending order so as to be able to easily
identify the most and least expensive
Arrays.sort(price);
//Print out the most expensive and cheapest prices
System.out.println("The most expensive item costs: " +
price[price.length-1]);
System.out.println("The least expensive item costs: " + price[0]);
}
}
Fruit Class:
public class Fruit {
private String name;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
The problem is that the Scanner.readInt() and Scanner.readDouble() methods do not read the newline character after you press enter. However, the readLine() method reads the input that is skipped, so it reads the newline character. To fix the problem, you need to call scanner.readLine() after you call scanner.readInt() and scanner.readDouble() to get rid of the newline. Please see the code below.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Fruit fruit = new Fruit();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of items in your shopping list:");
int listSize = scanner.nextInt();
scanner.nextLine(); //calling nextLine() to get rid of the newline character
String[] sl = new String[listSize];
double[] price = new double[listSize];
//Loop asking user to enter items and prices
for(int i = 0; i <= listSize - 1; i++)
{
System.out.println("Enter item " + (i+1) + ":");
fruit.setName(scanner.nextLine());
sl[i] = fruit.getName();
System.out.print("Price of " + sl[i] + ":");
fruit.setPrice(scanner.nextDouble());
scanner.nextLine(); //calling nextLine() to get rid of the newline character
price[i] = fruit.getPrice();
}
//Loop printing items and their prices
for(int i = 0; i <= listSize - 1; i++)
{
System.out.println(sl[i] + " cost " + price[i]);
}
//Order the array in ascending order so as to be able to easily
Arrays.sort(price);
//Print out the most expensive and cheapest prices
System.out.println("The most expensive item costs: " + price[price.length-1]);
System.out.println("The least expensive item costs: " + price[0]);
}
}
class Fruit
{
private String name;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
I have compiled and run this code, and here is the output it produces:
Enter the number of items in your shopping list:2
Enter item 1:
apple
Price of apple:1.25
Enter item 2:
bread
Price of bread:3.45
apple cost 1.25
bread cost 3.45
The most expensive item costs: 3.45
The least expensive item costs: 1.25
Hope this helps!!

Variable Scope and Visibility in Java

I am making a vacation and vacationdriver. The vacation file will serve as my blueprint and the driver will be the interactive portion of the program creating instances of vacation. I have everything working perfectly, but when I add in the one value I am missing to my print statement of line 47 of the vacation driver class I break the program.
I need to call the value for numSales which I thought is declared in line 42. When I type in numSales on line 47 at the beginning and in the middle of the output as shown I get a red line underneath and Eclipse tells me "numSales cannot be resolved into a variable". What do I need to do to get the value of numSales to be actively output in the print statement on line 47 of the vacation driver?
Here is the vacation class:
package cbrownmod4;
import java.text.NumberFormat;
public class Vacation {
// money formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
// instance variables
private String vacationName;
private int numSold;
private Double priceEach;
// empty constructor
public Vacation() {
}
// partial constructor
public Vacation(String n, int s, double e) {
vacationName = n;
numSold = s;
priceEach = e = 0;
}
// updatSales method
public int updateSales() {
int updateSales = 0;
updateSales = updateSales + numSold;
return updateSales;
}
// totalValue method
public double totalValue() {
double totalValue = 0;
totalValue = totalValue + (numSold * priceEach);
return totalValue;
}
// toString method
public String toString() {
return vacationName + " has been sold " + numSold + " times for " + money.format(priceEach) +
" each for a total value of " + money.format(numSold*priceEach);
}
// getters and setters
public String getVacationName() {
return vacationName;
}
public void setVacationName(String vacationName) {
this.vacationName = vacationName;
}
public int getNumSold() {
return numSold;
}
public void setNumSold(int numSold) {
this.numSold = numSold;
}
public Double getPriceEach() {
return priceEach;
}
public void setPriceEach(Double priceEach) {
this.priceEach = priceEach;
}
}
Here is the vacation driver:
package cbrownmod4;
import java.text.NumberFormat;
import java.util.Scanner;
public class VacationDriver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
NumberFormat money = NumberFormat.getCurrencyInstance();
// ask for the number of vacations and read it into numVacations
System.out.println("How many vacations are there?:");
int numVacations = input.nextInt();
// ask for the number of sales people and read it into numPeople
System.out.println("How many sales people are there?: ");
int numPeople = input.nextInt();
// beginning of loop for number of vacations
for(int i = 0; i < numVacations; i++) {
//ask for the name and price and read these into variables
System.out.println("What is the name of vacation #" + Integer.toString(i+1) + "?:");
String name = input.next();
System.out.println("How much does " + name + " cost?: ");
Double price = input.nextDouble();
// create a Vacation instance using the data obtained above
Vacation vacay = new Vacation (name, i, price);
// loop through the sales people
for(int j = 0; j < numPeople; j++) {
// ask for the sales for the current vacation and read it in
System.out.println("What are the sales for the current vacation by person #" + Integer.toString(j+1) + "?:");
int numSales = input.nextInt(); // line 42
// call updateSales with this number
numSales = vacay.updateSales();
} //end of inner loop
//where line 47 begins
//print out this vacation info
System.out.println(numSales + " trips to " + name + " were sold for " + money.format(price) + " for a total of " + money.format(numSales * price));
} //end of outer for loop
} //end of main
}
Due to requests to provide a snippet of the portion of the code not working here is the bit thats proving me problems:
//print out this vacation info
System.out.println(numSales + " trips to " + name + " were
sold for " + money.format(price) + " for a total of " +
money.format(numSales * price));
NOTE: If you take out the numSales in the snippet of the vacation driver, the program executes correctly but does not have the correct output because it is missing the necessary output variable
The clear concise question would be - why doesn't numSales work when I use it like shown in the short snippet. Again my problem is that Eclipse says "numSales cannot be resolved into a variable."
The problem is that you declare numSales inside a for {} block.
You need to declare it before the for block:
int numSales = 0; // set initial value in case numPeople is 0 and the loop never runs
// loop through the sales people
for(int j = 0; j < numPeople; j++) {
// ask for the sales for the current vacation and read it in
System.out.println("What are the sales for the current vacation by person #" + Integer.toString(j+1) + "?:");
numSales = input.nextInt(); // line 42; this value is never used? it is overwritten below
// overwrite the never-used value from line 42??
numSales = vacay.updateSales();
} //end of inner loop
// now numSales is still visible, because it was declared on this same 'level' and not in an inner block
System.out.println("numSales: " + numSales);
The value set in line 42 is never used, and is overwritten in line 45, so you might as well call input.nextInt(); without setting the value to numSales.

How to find average mark of an array list that comes from a csv file (JAVA) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a csv file that has a list with student id's, lastname, firstname, marks, phone number, etc. I have organized them into an array list so when you call stu[100].mark it will find the mark of the 100th student on the list of the csv file. There are 1000 students. I need to calculate the total overall average mark for all the students (each student only has one mark) I have put it in a loop, but it just prints out their mark. If you need more details, than I apologize.
Here is the code:
public class StudentRecs {
public static String user;
public int StuRec;
public static int numstu;
public static double average;
//public static StuRec[] stu;
static StuRec[] stu = new StuRec[1000];
public static void main(String[] args) throws IOException {
for (int i = 0; i < 1000; i++) {
stu[i] = new StuRec();
}
StuRec stu = new StuRec();
readFile(user);
menu();
}
public static String filename;
Scanner reader = new Scanner(filename);
public static Boolean readFile(String filename) throws IOException { //Constructor for filename
try {
Scanner userInput = new Scanner(System.in);
System.out.println("Type R To Read a File or Type Default for the default file");
user = userInput.nextLine();
if (user.equalsIgnoreCase("r")) {
user = userInput.nextLine();
}
filename = user;
if (user.equalsIgnoreCase("default")) {
filename = "newreg2.csv";
}
Scanner input = new Scanner(new FileReader(filename));
while (input.hasNext()) {
in(input.nextLine());
numstu++;
}
input.close();
return true;
} catch (IOException e) {
System.err.println(e.getMessage());
}
return false;
}
public static void in(String reader) {
String splitter[];
splitter = reader.split(",");
stu[numstu] = new StuRec();
stu[numstu].studentID = splitter[0];
stu[numstu].lastName = splitter[1];
stu[numstu].firstName = splitter[2];
stu[numstu].phoneNumber = splitter[3];
stu[numstu].courseCode = splitter[4];
stu[numstu].periodNumber = Integer.parseInt(splitter[5]); // parseInt turns a string of digits into an integer
stu[numstu].mark = Integer.parseInt(splitter[6]);
}
public static boolean menu() {
int total = 0;
String choice;
Scanner userInput = new Scanner(System.in);
System.out.println("=============================================");
System.out.println("Type R To Read Another File");
System.out.println("Type L To Print all File Records");
System.out.println("Type AA To Print The Average Of All The Marks");
choice = userInput.nextLine();
for (int i = 0; i < numstu; i++) {
if (choice.equalsIgnoreCase("L")) {
System.out.println(stu[i].lastName + ", " + stu[i].firstName + ", " + stu[i].studentID + ", " + stu[i].phoneNumber + ", " + stu[i].courseCode + ", " + stu[i].periodNumber + ", " + stu[i].mark);
}else if (choice.equalsIgnoreCase("R")){
} else if (choice.equalsIgnoreCase("AA")) {
total = total + stu[i].mark;
} else {
System.err.println("Unknown Key Try Again...");
}
average = total / 1000; // compute the average.
System.out.println(average);
} return menu();
}
}
Your average routine is computing incorrectly. It's simply taking the n'th mark and adding it to itself, divided by 1000. Since you're using integers, it will just round down, effectively giving you n'th mark + 0 for average on each iteration, leaving you with the last mark on the loop completion.
You need to keep adding to average, and divide by 1000 when you are done to get the value.
public static boolean menu() {
String choice;
Scanner userInput = new Scanner(System.in);
System.out.println("=============================================");
System.out.println("Type R To Read Another File");
System.out.println("Type L To Print all File Records");
System.out.println("Type AA To Print The Average Of All The Marks");
choice = userInput.nextLine();
for (int i = 0; i < numstu; i++) {
if (choice.equalsIgnoreCase("L")) {
System.out.println(stu[i].lastName + ", " + stu[i].firstName + ", " + stu[i].studentID + ", " + stu[i].phoneNumber + ", " + stu[i].courseCode + ", " + stu[i].periodNumber + ", " + stu[i].mark);
}else if (choice.equalsIgnoreCase("R")){
} else if (choice.equalsIgnoreCase("AA")) {
average += stu[i].mark; // keep adding to average
} else {
System.err.println("Unknown Key Try Again...");
}
}
// divide by zero protection
if ( numstu > 0 ) {
average = average/numstu; // compute the average. Always use the size in terms of a variable whenever possible.
System.out.println(average); // as noted below, if this is an integer value, < #of students computations will eval to 0.
// might be better to use double
}
else {
System.out.println("Oops! No students! :(");
}
return menu();
}
Note that your menu is a little inefficient, but the problem at hand should be solved.
Others have already pointed out the issue with not correctly calculating the sum of the scores, the numerator of the average calculation. I want to focus on the issue of the number of scores, the denominator of the average calculation.
Think real world. As others have mentioned, you cannot depend on the number of students in the file being fixed. File/class size can vary, so you cannot divide by a fixed number.
But neither can you depend on the number of scores being the same as the number of students, so you cannot simply divide by the number of students in that file. A student might not have a mark for a particular assignment (sickness, excused absence, or whatever). A good routine will account for the possibility of blanks (as well as invalid values), and thus I would expect you to need to count the valid, non-blank marks at the same time that you total them so that you can take the appropriate quotient at the end.
This statement is the problem
average = stu[i].mark + stu[i].mark / 1000;
This does not accumulate a total. Instead try
total = total + stu[i].mark;
And then at the end, outside the loop
average = total / 1000;

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

Add multiple values to arraylist from user input

I'm trying to add to my array list, then print out the list off all the programmers. Instead it just prints out the single programmer I just entered the details for. My question is. How do you correctly put the information entered into my Array list Programmer? Adding one array to another.
public Programmer(int id, String name, double pay, String time, int managerId) {
this.mId = id;
this.mName = name;
this.mPay = pay;``
this.mTime = time;
this.mManagerId = managerId;
this.mManager = null;
case 4:
String nameadd, time , manager;
double pay;
int manageradd;
System.out.println("Enter new car data:");
nameadd = in.getString("Name: ");
pay = in.getDouble("Wage: ");
time = in.getString("Part or Full Time: ");
manageradd = in.getInt("Manager ID: ");
p = ui.insert(nameadd, time, pay, manageradd );
System.out.println(p.getName() + ": WAGE: €" + p.getPay()+ " STATUS:" + p.getTime() + " MANAGER: " + p.getManager());
}
break;
And heres my View
public Programmer insert(String nameadd, String time, double pay, int manageradd) {
Programmer p;
p = new Programmer(0, nameadd, pay, time, manageradd);
return p;
}
At the start of your method or inside your class initialize the list.
List<Programmer> listOfProgrammers = new ArrayList<Programmer>();
Then you can add your programmers when they are created.
listOfProgrammers.add(p);

Categories

Resources