How to call a function once for all objects? - java

I'm having trouble understanding how I can call a function with multiple objects only once (within a for loop).
I'm trying to write a code where information of the objects should be passed to another function.
Take the following program for example where, instead of once, the function is being called multiple times.
import java.util.Scanner;
class Attraction {
String name;
int open;
}
public class attractionGuide {
public static void main(String[] args) {
attractionDetails();
System.exit(0);
}
public static Attraction createAttraction(String attractionName, int openingTime) {
Attraction a = new Attraction();
a.name = attractionName;
a.open = openingTime;
return a;
}
public static void attractionDetails() {
Attraction TheEdenProject = createAttraction("The Eden Project", 9);
Attraction LondonZoo = createAttraction("London Zoo", 10);
Attraction TateModern = createAttraction("Tate Modern", 10);
attractionInfo(TheEdenProject);
attractionInfo(LondonZoo);
attractionInfo(TateModern);
// This is where the problem is^
}
public static Attraction attractionInfo(Attraction a) {
Scanner scanner1 = new Scanner(System.in);
System.out.print("Welcome. How many attractions do you need to know about? ");
final int howMany = scanner1.nextInt();
for (int i = 1; i <= howMany; i++) {
System.out.print("\nName of attraction number number " + i + "?: ");
Scanner scanner2 = new Scanner(System.in);
String attraction_name = scanner2.nextLine();
if (attraction_name.equalsIgnoreCase(a.name)) {
System.out.println(a.name + " opens at " + a.open + "am.");
} else {
System.out.println("I have no information about that attraction.");
}
}
return a;
}
}
Example output:
Welcome. How many attractions do you need to know about? 3
Name of attraction number number 1?: the eden project
The Eden Project opens at 9am.
Name of attraction number number 2?: tate modern
I have no information about that attraction.
Name of attraction number number 3?: london zoo
I have no information about that attraction.
Welcome. How many attractions do you need to know about?
It seems since the function is being called three times within the loop, it will only take one argument at a time, whereas the desired output should look something like this:
Expected output:
Welcome. How many attractions do you need to know about? 3
Name of attraction number number 1?: the eden project
The Eden Project opens at 9am.
Name of attraction number number 2?: tate modern
Tate Modern opens at 10am.
Name of attraction number number 3?: london zoo
London Zoo opens at 10am.
so how do I go about calling the function once so it takes all the arguments at once?
Any help is appreciated. Thanks.

Create a List of attractions as in
List<Attraction> attractions = new ArrayList<>();
Add each attraction to the list:
attractions.add(TheEdenProject);
attractions.add(LondonZoo);
attractions.add(TateModern);
Pass the List to attractionInfo
attractionInfo(attractions);
Define attractionInfo as
// Didn't see why you needed to return Attraction
public static void attractionInfo(List<Attraction> allKnown)
And use it as such:
Scanner scanner1 = new Scanner(System.in);
System.out.print("Welcome. How many attractions do you need to know about? ");
final int howMany = scanner1.nextInt();
for (int i = 1; i <= howMany; i++) {
System.out.print("\nName of attraction number number " + i + "?: ");
Scanner scanner2 = new Scanner(System.in);
String attraction_name = scanner2.nextLine();
Attraction lookup = createAttraction(attraction_name,0);
if (allKnown.contains(lookup)) {
Attraction ofInterest = allKnown.get(allKnown.indexOf(lookup));
System.out.println(ofInterest.name + " opens at " + ofInterest.open + "am.");
} else {
System.out.println("I have no information about that attraction.");
}
}
The contains assumes the equals of Attraction is implemented as the desired name comparison. If you need help with that just ask. Or search on [java] equals in SO.

You need some collection to iterate over, like a List.
List<Attraction> attractions = Arrays.asList(
createAttraction("The Eden Project", 9),
createAttraction("London Zoo", 10),
createAttraction("Tate Modern", 10)
);
for (Attraction attraction : attractions) {
attractionInfo(attraction);
}
Or, more advanced
Stream.of(
createAttraction("The Eden Project", 9),
createAttraction("London Zoo", 10),
createAttraction("Tate Modern", 10)
)
.forEach(attractionGuide::attractionInfo);

The problem is you are calling your loop three times.
attractionInfo(TheEdenProject); // This creates a loop
attractionInfo(LondonZoo); // Ditto
attractionInfo(TateModern); // Ditto
If you want to loop once, you must call the loop only once. Try creating the loop and having it call the method that checks the attraction.
// Closer to main()
Attraction a;
for (int i = 1; i <= howMany; i++) {
System.out.print("\nName of attraction number number " + i + "?: ");
Scanner scanner2 = new Scanner(System.in);
String attraction_name = scanner2.nextLine();
// Add this
if ( (a = attractionInfo(a.name)) != null ) {
System.out.println(a.name + " opens at " + a.open + "am.");
} else {
System.out.println("I have no information about that attraction.");
}
}

Pass an array or collection to iterate over. the simplest change is below, but you could also use a Map to get the info by name rather than iterating over the entire collection .
import java.util.Scanner;
public class AttractionGuide {
static class Attraction {
String name;
int open;
Attraction(String name, int open) {
this.name = name;
this.open = open;
}
}
public static void main(String[] args) {
attractionDetails();
System.exit(0);
}
public static void attractionDetails() {
Attraction TheEdenProject = new Attraction("The Eden Project", 9);
Attraction LondonZoo = new Attraction("London Zoo", 10);
Attraction TateModern = new Attraction("Tate Modern", 10);
queryAttractionInfo(TheEdenProject, LondonZoo, TateModern);
}
public static void queryAttractionInfo(Attraction ... attractions) {
Scanner scanner1 = new Scanner(System.in);
System.out.print("Welcome. How many attractions do you need to know about? ");
final int howMany = scanner1.nextInt();
for (int i = 1; i <= howMany; i++) {
System.out.print("\nName of attraction number number " + i + "?: ");
Scanner scanner2 = new Scanner(System.in);
String attraction_name = scanner2.nextLine();
boolean found = false;
for (Attraction a : attractions) {
if (attraction_name.equalsIgnoreCase(a.name)) {
System.out.println(a.name + " opens at " + a.open + "am.");
break;
}
}
if (!found) {
System.out.println("I have no information about that attraction.");
}
}
}
}

well, there so many answers.
i think this is your mean:
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Welcome. Enter attractions count:");
int count = scanner.nextInt();
System.out.println("count: " + count);
attractionInfo(count, "Jim", 10);
attractionInfo(count, "Tom", 2);
attractionInfo(count, "Jack", 4);
scanner.close();
}
public static void attractionInfo(int count, String name, int open) {
for (int i = 1; i <= count; i++) {
System.out.print("Enter a name:");
Scanner scanner = new Scanner(System.in);
String attraction_name = scanner.nextLine();
if (attraction_name.equalsIgnoreCase(name)) {
System.out.println( name + " opens at " + open + "am.");
} else {
System.out.println("I have no information about that attraction.");
}
}
System.out.println("=================");
}

Related

Sorting Arrays In Java soicanpost

my question is how would I sort the arrayofnames and arrayofdownloads so they're in ascending order and each name matches with it corresponding number of downloads. i've been trying for 4 hours and i can't seem to wrap my head around it
thanks
import java.util.*;
import java.util.stream.*;
public class short6
{
public static void main(String[] args)
{
String[] arrayofnames = new String[4];
int[] arrayofdownloads = new int[4];
printmessage(arrayofnames, arrayofdownloads);
details(arrayofnames, arrayofdownloads);
System.exit(0);
}
public static void printmessage(String[] arrayofnames, int[] arrayofdownloads)
{
Scanner scanner = new Scanner(System.in);
int totalDownloads = 0;
for (int i = 0; i < arrayofnames.length; i++)
{
System.out.println("What is track " + (i + 1));
arrayofnames[i] = scanner.nextLine();
System.out.println("How many thousands of times has it been downloaded? ");
arrayofdownloads[i] = Integer.parseInt(scanner.nextLine());
}
Arrays.sort(arrayofnames);
Arrays.sort(arrayofdownloads);
System.out.println("The track downloaded the most is " + arrayofdownloads[0]+".");
}
public static void details(String[] arrayofnames, int[] arrayofdownloads)
{
int totaldownloads = IntStream.of(arrayofdownloads).sum();
System.out.println("The track downloaded the most is " + arrayofdownloads[0]+".");
System.out.println("The total number of downloads of these 4 tracks was " + totaldownloads * 1000 +".");
System.out.println("\nThe details of the downloads are");
for (int i = 1; i < arrayofnames.length; i++)
{
System.out.println(arrayofnames[i]);
System.out.println((arrayofdownloads[i]));
}
}
}
I'd start creating a Song (e.g.) class that contains both the song name, and the number of downloads:
public class Song {
private String name;
private int downloads;
public Song(String name, int downloads) {
this.name = name;
this.downloads = downloads;
}
public String getName() {
return this.name;
}
public int getDownloads() {
return this.downloads;
}
}
And then, create an array of songs:
Song[] arrayOfSongs = new Song[4];
And load it from the input:
arrayOfSongs[i] = new Song(scanner.nextLine(), Integer.parseInt(scanner.nextLine()));
Now you just need to sort it using a comparator:
Arrays.sort(arrayOfSongs, new Comparator<Song> () {
public int compare(Song o1, Song o2) {
// Sorting by name
return o1.getName().compareTo(o2.getName());
}
});
Or, as #Benoit has said in the comments, it would be even easier this way (Java 8 or up):
Arrays.sort(arrayOfSongs, Comparator.comparing(Song::getName));
And your done, just printing the objects (a toString method can be helpful here) you have the information sorted.
Edit: to read the input writing the questions, you just need to store the values in variables e.g.
System.out.println("What is track " + (i + 1));
String songName = scanner.nextLine();
System.out.println("How many thousands of times has it been downloaded? ");
int songDownloads = Integer.parseInt(scanner.nextLine());
arrayOfSongs[i] = new Song(songName, songDownloads);
Or you can just implement setter methods in the Song class and create a constructor with no parameters, so you can set the values as you are reading them.
thanks for the reply, so I've figured that i can use a for loop to ask the questions for song name and number of downloads. what im finding hard is putting their response in each array from 1-4 and saving dong name in the correct field of the song record and same for number of downloads?
public static void printmessage(song[] arrayOfSongs)
{
Scanner scanner = new Scanner(System.in);
int totalDownloads = 0;
for (int i = 0; i < arrayOfSongs.length; i++)
{
System.out.println("What is track " + (i + 1));
// store in array x name field
System.out.println("How many downloads does this track have? ");
//store in array x downloads field
}

Counting actors and storing and displaying their name and role

I'm new to Java and I'm attempting to learn off different sites and videos and I've been stuck on a problem for a couple of days now and I'm wondering can anyone help out. What I'm trying to do is ask the user how many key actors are in a film. Then i want to ask the actors name and the role they play in the film, this should be asked for each actor for however many the user specified are in the film before finally displaying the actors name and his role?
import java.util.Scanner;
public class rough {
public static void main(String[] args) {
// TODO Auto-generated method stub
int actorCount;
Scanner input = new Scanner(System.in);
Scanner kb = new Scanner(System.in);
System.out.println("How many actors are in the film? ");
actorCount = kb.nextInt();
for (int k = 1; k <= actorCount ; k++)
{
float actor, character;
System.out.println("What is the actors name? ");
actor = kb.nextFloat();
System.out.println("What is " + actor + "'s character?");
character = kb.nextFloat();
System.out.print(actor + " - " + character);
}
kb.close();
input.close();
}
}
This is what I would have done:
import javax.swing.*;
public class rough {
public static void main(String[] args) {
// TODO Auto-generated method stub
int actorCount;
String output = "";
actorCount = Integer.parseInt(JOptionPane.showInputDialog(null,"How many actors are in the film? "));
for (int k = 1; k <= actorCount ; k++)
{
String actor, character;
actor = JOptionPane.showInputDialog(null, "What is the actors name?");
character = JOptionPane.showInputDialog(null, "What is " +actor + "s character?");
output += actor + " - " + character + "\n";
}
JOptionPane.showMessageDialog(null, output);
}
}
Remember that if you want all of the roles/actors to be printed at the same time you must put the print outside the for loop and store the roles/actors to some output String. Moreover, I cannot see why you have used a float variable for the roles/actors a String would be the most logical.
So you should do it in this way:
public static void main(String[] args) {
int actorCount;
Scanner input = new Scanner(System.in);
Scanner kb = new Scanner(System.in);
System.out.println("How many actors are in the film? ");
actorCount = kb.nextInt();
String[][] actorValues = new String[actorCount][2];
for (int k = 0; k < actorCount ; k++)
{
String actor, character;
System.out.println("What is the actors name? ");
actor = kb.next();
System.out.println("What is " + actor + "'s character?");
character = kb.next();
System.out.print(actor + " - " + character +"\n");
actorValues[k][0] = actor;
actorValues[k][1] = character;
}
//Printout the Characters in the List
System.out.println("All Actors:");
for (int i = 0; i < actorValues.length; i++) {
String[] strings = actorValues[i];
System.out.println("Actorssname: "+strings[0]+" Character:"+strings[1]);
}
kb.close();
input.close();
}

Copy Constructor Test not Working (Java)

I'm working on CS homework and have run into a problem. The end of the homework asks about using a copy constructor. The goal is to "make one Payroll object, instantiate it, make a second one, then print them both. Then, change values in the second Payroll object, and show that the changed values only appear in one and not both (that is, print out the original and the copy with slightly changed values)." I tried changing the values in the second Payroll object, but it also changes it in the first. I've listed my code below:
import java.util.Random;
public class Payroll {
private int[] employeeId;
private int[] hours;
private double[] payRate;
public Payroll(){
this.employeeId = new int[0];
this.hours = new int[0];
this.payRate = new double[0];
}
public Payroll(Payroll obj){
this.employeeId = obj.employeeId;
this.hours = obj.hours;
this.payRate = obj.payRate;
}
public Payroll(int i){
this.employeeId = new int[i];
this.hours = new int[i];
this.payRate = new double[i];
}
public int getEmployeeIdAt(int index){
return employeeId[index];
}
public int getHoursAt(int index){
return hours[index];
}
public double getPayRateAt(int index){
return payRate[index];
}
public double getGrossPay(int index){
double grossPay = hours[index] * payRate[index];
grossPay = Math.round(grossPay * 100);
return grossPay/100;
}
public void setEmployeeIdAt(int index, int id){
this.employeeId[index] = id;
}
public void setHoursAt(int index, int hrs){
this.hours[index] = hrs;
}
public void setPayRateAt(int index, double pr){
this.payRate[index] = pr;
}
public void setHoursAt(int i){
Random rand = new Random();
int randHours = rand.nextInt((50 - 15) + 1) + 15;
this.hours[i] = randHours;
}
}
import java.util.Scanner;
public class PayrollDriver {
public static void main(String[] args) {
Payroll pr = new Payroll(5);
Scanner scan = new Scanner(System.in);
int empID = 1001;
for(int i = 0; i < 5; i++){
pr.setEmployeeIdAt(i, empID);
empID++;
}
for(int i = 0; i < 5; i++){
System.out.println("Enter the hourly pay rate for employee number " + pr.getEmployeeIdAt(i) + ": ");
double payRate = scan.nextDouble();
if(payRate < 7.50){
do{
System.out.println("ERROR: Enter 7.50 or greater for pay rate: ");
payRate = scan.nextDouble();
} while(payRate < 7.50);
}
pr.setPayRateAt(i, payRate);
pr.setHoursAt(i);
}
System.out.println("PAYROLL DATA");
System.out.println("======================");
for(int i = 0; i < 5; i++){
System.out.println("Employee ID: " + pr.getEmployeeIdAt(i) + " Hours: " + pr.getHoursAt(i) + " Rate: " + pr.getPayRateAt(i) +
" Gross Pay: $" + pr.getGrossPay(i));
}
System.out.println("Would you like to run the Copy Constructor Test? Enter 'y' (lowercase) if yes, enter any other letter if no: ");
char copyTestVerify = scan.next().charAt(0);
if(copyTestVerify == 'y'){
CopyConstructorTest ct = new CopyConstructorTest();
ct.CopyTest();
}
scan.close();
}
}
The following is my CopyConstructorTest class, the one that tests whether or not the copy constructor will change the original object's values:
public class CopyConstructorTest {
public void CopyTest(){
Payroll pay = new Payroll(5);
pay.setEmployeeIdAt(0, 1001);
Payroll payCopy = new Payroll(pay);
System.out.println("Original: " + pay.getEmployeeIdAt(0));
System.out.println("Copy: " + payCopy.getEmployeeIdAt(0));
payCopy.setEmployeeIdAt(0, 5000);
System.out.println("Original after changes: " + pay.getEmployeeIdAt(0));
System.out.println("Copy after changes: " + payCopy.getEmployeeIdAt(0));
}
}
I'm not positive on what I'm doing wrong. Any help or guidance is much appreciated.
You are just copying the references to the arrays, not the actual data. Therefore whenever you change the data in one of your objects, the changes are seen in both, since they point to the same array.
The easiest way to copy the data is probably using System.arraycopy():
public Payroll(Payroll obj) {
this.employeeId = new int[obj.employeeId.length];
System.arraycopy(obj.employeeId, 0, this.employeeId, 0, obj.employeeId.length);
...

Restaurant Menu: how to efficiently implement a nested loop to collect user input and conduct error checking

I have these two methods which I cant quite figure out the best way to go about their algorithm.
I am writing a program that acts like a restaurant menu and collects user order.
The implementation is,
welcome user and present him with the menu
while the user has not entered 'q', send the user input to a method called getGoodOrderLine(String str)
this method will then check the input for the following,
- First, it must check that a number is present before trying to read it; if there is no number, the entry is an error unless it starts with ‘q’ or ‘Q’, which tells the program to quit.
- then, determine which item the user is asking for by looking at just the first letter. So an input “2 Hello” means 2 hamburgers. the assumption is that if there is a digit in the string, the digit appears before the word, for simplicity
- finally, if the first letter is not (H,C,F or D), print an error message and ask that it be re-entered.
My problem is that, I created a while loop that should loop until the user input is valid, but it doesn't seem to be working, here is my code:
import java.util.*;
public class MenuApp
{
//global variables
public static double HAM = 3.75;
public static double CHEESE = 4.10;
public static double FRIES = 2.50;
public static double DRINKS = 1.75;
public static void main(String [] args)
{
//variables
String order;
double total = 0.0;
boolean stopLoop;
//print welcome message && collect order
welcomeCustomer();
order = collectItem();
order = getGoodOrderLine(order);
stopLoop = order.equalsIgnoreCase("q");
while(!stopLoop)//while user hasnt typed q
{
if(order.equalsIgnoreCase("q"))
{
break;
}
order = getGoodOrderLine(order);
//will add the value of user order to total here if order is valid
//leave loop if useer inputs q
}
//ending program
Date today = new Date();
System.out.println("Date: " + today);
System.out.println("Please pay " + total + "\n");
System.out.println("End of processing");
}
public static void welcomeCustomer()
{
System.out.println("Welcome to QuickieBurger!");
System.out.println("Hamburgers \t\t $" + HAM);
System.out.println("cheeseBurgers\t\t $" + CHEESE);
System.out.println("Fries\t\t\t $" + FRIES);
System.out.println("Drinks\t\t\t $" + DRINKS+"\n");
}
public static String collectItem()
{
String userInput = null;
Scanner kbd = new Scanner(System.in);
System.out.println("Please place your order (e.g., 3 ham). Enter Q to quit.");
userInput = kbd.nextLine();
System.out.println(userInput);
return userInput;
}
public static String getGoodOrderLine(String userInput)
{
String result = "";
boolean pass = false;
if(userInput.equalsIgnoreCase("q"))
{
return userInput;//early exit, return q
}
//check if it has at least a digit first
for(char c: userInput.toCharArray())
{
if(Character.isDigit(c))
{pass = true;}
}
//if it doesn't have a digit || string doesnt begin with a digit
if(!Character.isDigit(userInput.charAt(0)))
{
if(!pass)
System.out.println("Your entry "+ userInput + " should specify a quantity");
else
System.out.println("Your entry "+ userInput + " does not begin with a number");
}
else
{
//do the remaining tests here
}
return result;
}
}
I keep getting null pointer and index out of bounds exceptions when testing for Character.isDigit(userInput.charAt(0));
the problem is you are returning empty string so charAt(0) give error since char array has no elements.and if you want to collect items you need to use a collection type like list and u can't use a array since array has fixed length.and to get price of user input product you need to map prices with product names .so u can use map.but i used 2 arrays which act as a map.check this and it's output.
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Scanner;
public class myMenu {
public static String names[] = {"HAM", "CHEESE", "FRIES", "DRINKS"};
public static double prices[] = {3.75, 4.10, 2.50, 1.75};
public static ArrayList<List<String>> allitems = new ArrayList<>();
static double total = 0.0;
public static void main(String[] args) {
welcomeCustomer();
collectItem();
}
public static void welcomeCustomer() {
System.out.println("Welcome to QuickieBurger!");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + "\t\t\t" + prices[i]);
}
}
public static void collectItem() {
String userInput = "";
Scanner kbd = new Scanner(System.in);
System.out.println("Please place your order (e.g., 3 ham). Enter Q to quit.");
userInput = kbd.nextLine();
while (!getGoodOrderLine(userInput)) {
userInput = kbd.nextLine();
}
}
private static boolean getGoodOrderLine(String userInput) {
if (userInput.equalsIgnoreCase("q")) {
transaction();
} else if (!Character.isDigit(userInput.charAt(0))) {
System.out.println("quesntity should be specified. try again");
return false;
} else {
for (int i = 0; i < names.length; i++) {
String items = names[i];
//get the first charactor from userinput
char c = 0;
for(int z=0;z<userInput.length();z++){
c=userInput.charAt(z);
if(Character.isAlphabetic(c)){
break;
}
}
if (Character.toLowerCase(items.charAt(0)) ==Character.toLowerCase(c)) {
String s="";
int x=0;
while(Character.isDigit(userInput.charAt(x))){
s+=userInput.charAt(x);
x++;
}
int quentity=Integer.parseInt(s);
double pri = prices[i];
double sub = quentity * pri;
total += sub;
ArrayList<String> subitem = new ArrayList<>();
subitem.add(items);
subitem.add(String.valueOf(quentity));
subitem.add(String.valueOf(sub));
allitems.add(subitem);
return false;
}
}
System.out.println("this not a valid food item.try again");
}
return false;
}
private static void transaction() {
//ending program
Date today = new Date();
System.out.println("-------------------------------------");
System.out.println("Date: " + today);
for (List<String> menu : allitems) {
System.out.println(menu.get(0)+" "+menu.get(1)+" = "+menu.get(2));
}
System.out.println("Please pay " + total + "\n");
System.out.println("------------------------------------");
System.out.println("End of processing");
}
}
output>>
Welcome to QuickieBurger!
HAM 3.75
CHEESE 4.1
FRIES 2.5
DRINKS 1.75
Please place your order (e.g., 3 ham). Enter Q to quit.
2 Hello
4 CHEESE
q
-------------------------------------
Date: Sun Nov 02 02:59:56 PST 2014
HAM 2 = 7.5
CHEESE 4 = 16.4
Please pay 23.9
------------------------------------
End of processing
public class MenuApp
{
// global variables
public static double HAM = 3.75;
public static double CHEESE = 4.10;
public static double FRIES = 2.50;
public static double DRINKS = 1.75;
// you need to define errors
public static String noInput = "__MENUAPP_ERROR_1";
public static String invalidInput = "__MENUAPP_ERROR_2";
...
public static String getGoodOrderLine(String userInput)
{
String result = "";
boolean pass = false;
boolean startWithDigit = false;
// add this line to verify the input first
if (userInput == null || userInput.equalsIgnoreCase(""))
{
return MenuApp.noInput ;
}
if(userInput.equalsIgnoreCase("q"))
{
return "q"; // early exit, return q
}
//check if it has at least a digit first
for(char c: userInput.toCharArray())
if(Character.isDigit(c))
pass = true;
startWithDigit = Character.isDigit(userInput.charAt(0));
// if it doesn't have a digit || string doesnt begin with a digit
if(!startWithDigit)
{
if(!pass)
System.out.println("Your entry "+ userInput + " should specify a quantity");
else
System.out.println("Your entry "+ userInput + " does not begin with a number");
return MenuApp.invalidInput;
}
else
{
// do the remaining tests here
}
return result;
}
}

Basic Arrays in a Java Program

I am a beginner in Java and am working on a basic program that includes arrays and loops. The program must:
- ask the user to enter the name of a 'salesman' 5 times. These 5 names will be stored into a String array.
- another DOUBLE array is used to store the amount of sales each person has made.
- the data will be printed in the end.
Here's what I have so far:
public static void main (String[] args)
{
String[] names = new String[5];
System.out.println ("What is the name of the person?")
String name = scan.next();
double[] sales = new double[5];
sales[0] = 15000.00;
sales[1] = 10000.00;
sales[2] = 4500.00;
sales[3] = 2500.00;
sales[4] = 3500.00;
System.out.println(name1 + "sold " + sales[0]);
System.out.println(name2 + "sold " + sales[1]);
System.out.println(name3 + "sold " + sales[2]);
System.out.println(name4 + "sold " + sales[3]);
System.out.println(name5 + "sold " + sales[4]);
}
}
I know the first part is incorrect... as well as most of the output.
My instructor is not very interested in explaining much to our class. She is usually too busy working with a different part of the class. I basically know nothing about arrays.
I will certainly learn something if one of you is kind enough to tell me what I need to enter and where?
You need to use for loops to avoid having to repeat the lines of code for each instance. You want something more like this:
public static void main (String[] args)
{
String[] names = new String[5];
double[] sales = new double[5];
Scanner scan = new Scanner(System.in);
for (int i=0; i<5; i++) {
System.out.println ("What is the name of the person?");
name[i] = scan.next();
System.out.println ("How much did they sell?");
sales[i] = scan.nextDouble();
}
for (int i=0; i<5; i++) {
System.out.println (name[i] + " sold " + sales[i]);
}
}
look here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html for more on how to use the for loop. The loops that I wrote will execute the code inside when i=0, 1, 2, 3 and 4. i=0 tells the loop where to begin. i<5 tells the loop to execute the code inside as long as i is less than 5. And i++ is shorthand for i=i+1 and tells the loop what to do to i at the end (increase i by 1 and test the end condition again).
ETA: http://www.homeandlearn.co.uk/java/user_input.html shows how to use the Scanner class to get input.
It will be easier when you use collections.
Use this for simple implementation and better understanding for collections.
Scanner scanner = new Scanner(System.in);
List<String> list = new ArrayList<String>();
for (int i = 0; i < 5; i++) {
list.add(scanner.nextLine());
}
For printing use this.
for(String result : list){
System.out.println(result);
}
Simply use Scanner inside a loop.
String[] names = new String[5];
double[] sales = new double[5];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < names.length; i++){
System.out.print ("Please input name of sale " + (i+1) + ": ");
names[i] = scanner.nextLine();
System.out.print ("Please input sales of sale " + (i+1) + ": ");
sales[i] = scanner.nextDouble();
}
// following lines is for testing
for(int i=0; i < names.length; i++){
System.out.println(names[i]+" " + sales[i]);
}
Since Java is a Object oriented, so I recommend you to create a class named Salesman containing name and sale attributes.
// Salesman class
class Salesman{
private String name;
private double sales;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSales() {
return sales;
}
public void setSales(double sales) {
this.sales = sales;
}
}
And once again the main method.
public static void main (String[] args)
{
List<Salesman> salesmanList = new ArrayList<Salesman>(5);
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
Salesman salesman = new Salesman();
System.out.print ("Please input name of sale " + (i+1) + ": ");
salesman.setName(scanner.nextLine());
System.out.print ("Please input sales of sale " + (i+1) + ": ");
salesman.setSales(scanner.nextDouble());
salesmanList.add(salesman);
}
// following lines is for testing
for(Salesman salesman : salesmanList){
System.out.println(salesman.getName()+" " + salesman.getSales());
}
}
Try this:
public void getInput(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the total no of i/p :")
int count = scanner.nextInt();
List<String> collectionOfInput = new ArrayList<String>();
for (int i = 0; i < count; i++) {
collectionOfInput.add(scanner.nextLine());
}
}
public void printOutput(){
for(String outputValue : collectionOfInput){
System.out.println(result);
}

Categories