Need Method Help for an Array List - java

For my homework, I had to write a program that prompts the cashier to enter all prices and names, adds them to two arrays lists, calls the method that I implemented, and displays the result and use 0 as the sentinel value. I am having difficulty coming up with a for loop in the method, I believe I have the condition right but I am having trouble with the statements. Any help would be greatly appreciated! Thanks.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Double> sales = new ArrayList<Double>();
ArrayList<String> names = new ArrayList<String>();
System.out.print("Enter Number of Customers");
double salesAmount;
System.out.print("Enter Sales for First Customers");
salesAmount = in.nextDouble();
while(salesAmount != 0)
{
sales.add(salesAmount);
System.out.println("Enter Name of Customer: ");
names.add(in.next());
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer(sales, names);
}
public static String nameOfBestCustomer(ArrayList<Double> sales, ArrayList<String> customers)
{
String name = "";
double maxSales;
for (int i = 0; i < sales.size(); i++)
{
sales.size(name.get); <== it keeps saying "cannot find the symbol variable get"
}
return name;
}

Don't use maxSales as the maximum in your loop. Use the count of number of customers. Inside the loop, check if sales.get(i) is greater than your current maxSales, and if it is...
(I will edit this and more if you still need. But this should go a long way.)

There are a couple possible issues here, but I'll stick to answering what I think is the question that you've asked.
In your nameOfBestCustomer method, you'll want to loop from 0 to the end of either of your ArrayLists (as they both should be the same size).
for (int i = 0; i < sales.size(); i++)
{
...
}

Related

Summing up an unknown number of Integers in groups of 4

my issue is that after running my code I realized that it's not going to cut it. It currently lists all elements of the studentName (string) arrayList and all elements of the studentGrade (double) arrayList.
The problem is, four grades are to be assigned to each student and each set of four grades must be summed up separately (then I will average them out). If I sum up all elements in the studentGrade arrayList... that's not going to be indicative of each student individually. Where should I go from here? I've been struggling to come up with options.
package arrayList;
import java.util.Scanner;
import java.util.ArrayList;
public class TestGrades {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> studentName = new ArrayList<String>();
ArrayList<Double> studentGrade = new ArrayList<Double>();
boolean loop = true;
while (loop) {
System.out.println(" Please Enter Student Name");
String student = scanner.nextLine();
if(student.equals("C"))
{
break;
}
else
{
studentName.add(student);
}
System.out.println("Please enter Student Grade");
for (int j = 0; j < 4; j++) {
Double grade = Double.parseDouble(scanner.nextLine());
studentGrade.add(grade);
}
System.out.println(studentName);
System.out.print(studentGrade);
}
}
}
It sounds like you are in need of a Student class, which holds a student name and an array of the grades for that student. Then you can create a method in that class that sums up all the grades for that student and call that method as you loop over the List of Students.
Either that or a multi dimensional array where the students are one index and the second dimension is an array of grades for each index. Don't go this route unless it's a school assignment and you haven't learned about classes and OOP, because it's terrible to maintain and read.

Trying to sort user input into alphabetical order with Java, why won't this code work?

For some reason when I try to ask a user for names so I can add them to a list and sort them alphabetically, this code will not print anything out. It will not even get past the while loop, does anyone have any idea what the problem is? Also another question; how can you execute some code if the user presses the enter button when asked for input value, would it just be null? Thanks!
import java.util.Scanner;
import java.util.*;
public class project16u
{
public static void main(String[] args)
{
int n;
String input = "nothing";
String temp;
ArrayList<String> names = new ArrayList<String>();
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
while(!input.equals("done")){
input = s1.nextLine();
names.add(input);
}
for (int i = 0; i < names.size()-1; i++)
{
if (names.get(i).compareTo(names.get(i+1))>0)
{
temp = names.get(i);
names.add(i, names.get(i+1));
names.add(i+1, temp);
i=0;
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < names.size() - 1; i++)
{
System.out.print(names.get(i).toString() + ",");
}
System.out.print(names.get(names.size()-1));
}
}
add inserts the name at the requested index. Thus, in your case, you will have two copies of the same name in the list, rather than the one you intended.
You probably want to use set instead.
You may need to change the loop condition to
s1.hasNextLine() && !input.equals("done")

Program not behaving correctly

I am trying to create a program for a user entering information on books (Name, Author, Publishing year and price). And then I want to be able to get a list of the books' names published after 2000 and their average price.
At first, I thought of using arrays in an array, but after going through similar questions I chose to make a Book class:
public class Books {
public static String name;
public static String author;
public static int year;
public static float price;
public static float sum = 0.0F;
public static float avrg = 0.0F;
I don't know if the following are necessary, but I did it as I've seen it in a lot of examples:
public String getName () {
return name;
}
public String getAuthor () {
return author;
}
public int getYear () {
return year;
}
public float getPrice () {
return price;
}
Then, I am trying to take the user input and store my new objects in an array.
public static void main(String[] args) {
System.out.println("Please enter details for five books!");
Scanner in = new Scanner (System.in);
Books [] book = new Books[5];
int i = 0;
int j = 0;
int count = 0;
for (i=0; i < book.length; i++) {
System.out.println("Enter Book Title, Author Last Name, Year and Price:");
String name = in.next();
String author = in.next();
int year = in.nextInt();
float price = in.nextFloat();
}
And here I want to find the exact books and calculate their average price:
for (j=0; j<book.length; j++){
if (Books.year >= 2000) {
System.out.println("Books published after 2000:"+ Books.name);
sum = sum + Books.price;
count = count + 1;
}
}
avrg = sum/count;
System.out.println("Average price of books published after 2000:"+avrg);
Everything seems to be running smoothly till the part I want the names of the books (and average price) published. I get this as a result:
Please enter details for five books!
Enter Book Title, Author Last Name, Year and Price:
...
Average price of books published after 2000:NaN
It doesn't even show the names.I'm quite confused and I have no idea if this is the best way to do what I want to do. I will appreciate some help.
NaN means "Not a Number" and it signals a bad math operation, like zero divided by zero, that is your case: if no book meets the criteria count=0 and sum=0.0F and there you have it.
1) Follow Java naming conventions. The class should be Book because it is a singlular object.
public class Book {
And your array should be plural.
Book [] books = new Book[5];
2) Use instance variables, not class variables, for the properties that belong to an individual book. This requires you to remove static from name, author, year, and price.
3) "I am trying to take the user input and store my new objects in an array." Your code that you posted does not store new objects in the array. This explains both why no names are printed and why NaN is in your output, because the array is empty.
Try to store a new Book() into the array.
System.out.println("Enter Book Title, Author Last Name, Year and Price:");
Book b = new Book();
b.name = in.next();
...
books[i] = b; // stored
4) You need to loop over the Book objects in the array to access their properties. You can use an enhanced for loop since you don't need the index variable anyway.
double sum = 0;
for (Book b : books){
if (b.year >= 2000) {}
sum += b.price;
}
System.out.println(sum);
if (books.length > 0) {
System.out.println(sum / books.length);
}
5) Take that loop and make it a method. For example, public static double totalPriceOfBooksAfterYear(Book[] books, int year) and have it return sum. You can use that value to calculate the average.
Maybe you didn't share this part of your code but do you actually store the inputs in an Book object and then store it in the array? When you create the array it creates 5 Book objects with all null values.
When you're finding the years, none of them qualify since they're all null. This means the count is also staying as a 0. Dividing by 0 is giving the NaN error. The error doesn't show up in the
sum = sum + Books.price;
line because it's never reaching that state.
Also,
if (Books.year >= 2000)
is checking if the class has a year >= 2000 and not checking a specific object.
Try something like:
if(book[j].year >= 2000)
NaN means "Not a Number" .
If there aren't any books (Books.year >= 2000) in this condition it causes a division by zero error.Because your count variable is getting 0 .
In
avrg = sum/count; is not checking weather you have a count more than 0.
Place a if condition to check that,
if(count>=0){
avrg = sum/count;
System.out.println("Average price of books published after 2000:"+avrg);
}
For the book name use getName method insted of Books.name
As an example :
Books books = new Books();
System.out.println(books.getName());
And check your books for year 2000 or more like this
if(book[j].year >= 2000)
instead of
if(Books.year >= 2000)
Because you are using and array type object you need to specify which index you want to look into

How can I return String inputs from a while loop?

In my code, I have the user enter the "number of titles". Then, I prompt the user to enter the title names until it equals the amount of titles there are that the user entered just before. What I want to do is return the title names when I call the method in my main method. But, when I try to return the variable I have that reads the title names, it can not be accessed because it is out of the loop. Here is that method:
public static String getTitles(){
Scanner numberOfTitles = new Scanner(System.in);
System.out.println("Enter number of titles: ");
int titlesAmount = numberOfTitles.nextInt();
int count = 1;
while (count <= titlesAmount){
Scanner titlesReader = new Scanner(System.in);
System.out.println("Enter title: ");
String titlesInput = titlesReader.next();
count++;
}
return titlesInput;
}
I want to return that variable titlesInput because that contains the names the user entered but I don't know how to access it outside of the loop. Would appreciate if someone could show me how to do that.
You must define the variable inside the method scope. Not in while loop scope if you wanna return that.
And it is always better not to use direct String objects and manipulating them inside loops since it will cause more memory. Better to use StringBuilder or StringBuffer based on your choice
public static String getTitles(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of titles: ");
int titlesAmount = scanner.nextInt();
int count = 1;
StringBuilder sbReturn = new StringBuilder();
while (count <= titlesAmount){
System.out.println("Enter title: ");
sbReturn.append(scanner.next()).append(",");
count++;
}
return sbReturn.toString();
}
If you want to return multiple strings from the method, you have to return a list of strings:
public static List<String> getTitles() { ... }
Then, inside the method, just add all strings you want to return to a list, and return the list at the end:
Scanner inputReader = new Scanner(System.in);
System.out.println("Enter number of titles: ");
int titlesAmount = inputReader.nextInt();
int count = 1;
List<String> titles = new ArrayList();
while (count <= titlesAmount){
System.out.println("Enter title: ");
titles.add(inputReader.next());
count++;
}
return titles;
Note that I only created one Scanner object. You don't need to create multiple Scanners for this task.
But an even better solution would be to have just one global Scanner object somewhere outside the method and just use that for all your input needs.
You need to return a list (or array) of Strings rather than a single String.
I changed your method to do this so you can get the general idea of what I mean. I'm not sure my syntax is 100% correct for Java, but it should get the gist across.
public static List<String> getTitles(){
Scanner numberOfTitles = new Scanner(System.in);
System.out.println("Enter number of titles: ");
int titlesAmount = numberOfTitles.nextInt();
int count = 1;
List <String> titles = new ArrayList<String>();
while (count <= titlesAmount){
Scanner titlesReader = new Scanner(System.in);
System.out.println("Enter title: ");
String titlesInput = titlesReader.next();
titles.add(titlesInput);
count++;
}
return titles;
}
In order to have the variable's scope be on the outermost level, you need to initialize the String outside of the while loop. The compiler can never know for sure if the code inside of a while loop statement will ever execute (even if the condition is true) so it does not leak any variables within a loop's block to the outer block.
In addition to that, there are three things you need to know. First, you only need one Scanner object for reading all of your input. Second, if you want to return a bunch of Strings, in this case, all of your titles, you need a List<String> object as your return type. Lastly, whenever you want to iterate x amount of times, a for loop is always more readable than a while loop that uses a counter variable.
I would rewrite your code like this:
public static List<String> getTitles() {
List<String> titles = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of titles: ");
int titlesAmount = sc.nextInt();
for (int i = 0; i < titlesAmount; i++) {
System.out.println("Enter title: ");
titles.add(sc.next());
}
return titles;
}

Expanding my program

So i got a programm that asks the user to type in the 3 favorite cities ,
it stores them in Array and prints them later out to the user. What im trying to do now is
making the programm ask the user for how many favorite cities he/she got?the user types in
a number wich will give the user the oppertunity to type in that ammount of favorit cities
and later on print them out.
Problem is i really have no idea how to do this could anyone help?
Please explain the code incase you help so i can understand :) , Sorry for my bad English not my
primary language!
My code atm looks like this :
package com.example.array.main;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
String[] favoritCity = new String [3];
Scanner scanner1 = new Scanner (System.in);
System.out.println("skriv in 3 favoritstäder");
String userIn1 = scanner1.nextLine();
String userIn2 = scanner1.nextLine();
String userIn3 = scanner1.nextLine();
favoritCity[0] = userIn1;
favoritCity[1] = userIn2;
favoritCity[2] = userIn3;
System.out.println(userIn1);
System.out.println(userIn2);
System.out.println(userIn3);
}
}
First take a integer input from user, that how many favorite cities does he/she have?
Scanner#nextInt(); which could help you get integer input from console. Create a array with that size Then write loop like -
String[] favoritCity = new String [noOfFabCities];
for(int i=0;i<maxFavCities;i++){
...
}
Now inside the loop get the input from user Enter your i+1 (as i starts with 0) favorite city and capture the input like Scanner#nextLine();. and keep the value into your array like -
favoritCity[i] = userInput;
Once you get all the user input, now can you print in console all the user's favorite cities.
That should be the code which are you looking for. I don't tested it, but it should works.
package com.example.array.main;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
int cityNumb;
Scanner scanner1 = new Scanner (System.in);
System.out.println("How many favorite cities do you have?");
cityNumb = scanner1.nextInt();
//creat the array with the size of cityNumb
String[] favoritCity = new String [cityNumb];
System.out.println("skriv in "+cityNumb+" favoritstäder");
//for loop for the input of the cities
for(int i = 0; i < cityNumb; i++)
{
String city = scanner1.nextLine();
favoritCity[i] = city;
}
//for loop for the output of the cities
for(int i = 0; i < cityNumb; i++)
{
System.out.println(favoritCity[i]);
}
}
}
Before to define your Array size, you can use your scanner to ask for the number of cities, for example:
Scanner scanner = new Scanner(System.in);
System.out.println("How many cities?");
int nberCities = scanner.nextInt();
String[] favoriteCities = new String[nberCities];
for(int i = 0; i < nberCities;i++){
favoriteCities[i] = scanner.nextLine();
}

Categories