I have the code below:
package Main; import java.util.*;
public class Generator {
List <List<String>>masterList = new ArrayList<List<String>>();
ArrayList memberList = new ArrayList<String>();
String leaderName, memberName;
int numLeaders, numMembers;
double x;
Scanner scanner = new Scanner(System.in);
// This program takes in total number of people first
// Then takes in number of leaders to assign peoples to
// Then takes in people to be assigned
// And then assigns people to given leaders randomly
public int getNumLeader() {
System.out.println("How many leaders are there??");
numLeaders = scanner.nextInt();
return numLeaders;
}
public void setNumLeader(int numLeaders) {
this.numLeaders = numLeaders;
}
public int getNumMembers() {
System.out.println("How many members are there?");
numMembers = scanner.nextInt();
return numMembers;
}
public void setNumMembers(int numMembers) {
this.numMembers = numMembers;
}
public void genLeaders() {
System.out.println("Please type the name of the leader on the following:");
for (int i = 1; i <= numLeaders; i++) {
if (i == numLeaders) {
System.out.println("What is the last leader's name?");
leaderName = scanner.next();
List <String> leaderList = new ArrayList<String>();
masterList.add(leaderList);
} else {
System.out.println("What is the leader" + i + "'s name?");
leaderName = scanner.next();
List <String> leaderList = new ArrayList<String>();
masterList.add(leaderList);
}
}
}
public void genMembers() {
System.out.println("Please enter the members on the following:");
for (int i = 1; i <= numMembers; i++) {
if (i == numMembers) {
System.out.println("What is the last member's name?");
memberName = scanner.next();
memberList.add(memberName);
} else {
System.out.println("What is the member" + i + "'s name?");
memberName = scanner.next();
memberList.add(memberName);
}
}
}
public void /*should return arraylist*/ brackets() {
double y = 1.0/numLeaders;
for (double j = 0.0; j <= 1.0; y++) {
//Generate Linked list with initial element of 0.0
//then 0.0 + y, then 0.0 + y + y ... till 1.0
}
}
public void assignMembers() {
System.out.println("Shuffling members..");
Collections.shuffle(memberList);
System.out.println("Assigning members to leaders now..");
int cellSize = memberList.size()/numLeaders;
for (int i = 0; i <= memberList.size(); i++) {
double x = Math.random();
double y = 1.0/numLeaders;
if (x <= y) {
masterList.get(0).add((String) memberList.get(i));
}
else if (y < x && x <= y + y) {
masterList.get(1).add((String) memberList.get(i));
}
else if (y < x && y + y < x && x <= y + y + y) {
masterList.get(2).add((String) memberList.get(i));
}
// assign given element's name from the big linkedList to the first leader's
// arrayList
}
}
public static void main(String[] args) {
Generator x = new Generator();
x.getNumLeader();
x.getNumMembers();
x.genLeaders();
x.genMembers();
System.out.println(x.memberList);
System.out.println(x.masterList);
System.out.println(x.masterList.get(0));
System.out.println(x.masterList.get(1));
System.out.println(x.masterList.get(2));
}
}
And I made lists within an arraylist, called masterList. I try to assign people in a list within that arraylist, in this manner: masterList.get(0).add((String) memberList.get(i)); Nothing's being added to the list within the arrayList.. what would be the 'correct' way to do this, and is there a way to pinpoint the list within the arraylist, other than 'masterList.get(0)'? Thanks in advance.
You are calling 4 methods, 2 to get numbers of leader and member, and another 2 to generate them. In your generateLeader method, you read name from console but never used it within this method. You are just adding emptylist to master list in this method. The other method generateMembers looks fine as you are adding this in the expected list. I dont see anywhere else that main method calls to populate the emptylist inside the masterlist you added in generateLeaders method.
Also, use nextln to read input, there are scenarios where the linebreak character will still be in buffer when you use just "next" and that linebreak will be read read as next input.
Related
I am a beginner in Java and I am wondering if there is a way to use one input from the user in more than one method? I am making a program that is supposed to take some inputs (integers) from the user and control the inputs, then calculate the average and lastly count the occurrence of the inputs?
I have one main method + 3 different methods (one calculates the average etc). I have tried a lot of different things, but haven't seemed to understand the point with parameters and how they work.
So this is just a quick overview.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int value = sc.nextInt(); //Number of how many elements the user want to enter
int[] input = new int[value]; //An array with all the values
}
public int secureInt(int number, int[] input, int value) {
if (!Integer.parseInt(number)) {
System.out.println("Invalid input");
} else {
for (int i = 0; i < value; i++) { //Add all the inputs in the array
input[i] = sc.nextInt();
}
}
public double averageCalculator (int value, int[] in){
double average; // The average
double sum = 0; // The total sum of the inputs
if (int i = a; i < value; i++) {
sum = sum + in[i];
}
average = sum / value;
return average;
}
//Count the occurence of inputs that only occure once
public static int countOccurence(//what parameter should i have here?) {
int count = 0;
}
}
Here is some code that may be helpful to you. The idea is to try to emulate or imitate the style & best practices in this excerpt:
import java.util.Scanner;
public class ArrayFiller {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int input_element_count = sc.nextInt(); //Number of how many elements the user want to enter
int element_count = input_element_count;
int[] array = new int[element_count]; //An array with all the values
enter_elements_of_array(array, element_count, sc);
double average = averageCalculator(array, element_count);
printArray(array);
System.out.println("The average of the entered numbers is " + average);
}
public static void printArray(int[] array) {
System.out.print("The array you entered is : [");
for (int element : array) {
System.out.print(" " + element + " ");
}
System.out.print("]" + "\n");
}
public static void enter_elements_of_array( int[] array, int element_count, Scanner sc) {
for (int i = 0; i < element_count; i++) { //Add all the inputs in the array
System.out.println("Please enter element " + (i+1) + " of " + element_count + ":");
array[i] = sc.nextInt();
}
}
public static double averageCalculator ( int[] array, int element_count){
double average; // The average
double sum = 0; // The total sum of the inputs
for (int i = 0; i < element_count; i++) {
sum = sum + array[i];
}
average = sum / element_count;
return average;
}
//Count the occurence of inputs that only occur once
public static int countOccurence(int[] array) {
int count = 0;
// algorithm for counting elements with cardinality of 1
return count;
}
}
So I'm trying to write a program that stimulates the rise and fall of the Stock market 5 times.The user inputs a value to create a new Stock Market Object then with the value from the user, the stock market either is a bust(decrease) or a boom( increase). The issue I'm having is passing the value to each if statement with the change within the loop.When I run the program, It uses the same value I entered instead of using the value that was created after calling boom or bust. I'm thinking I should create a value outside the loop that holds it but I'm not sure how to do that with the user input.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a Starting Market Value:");
double mv = in.nextDouble();
StockMarket u = new StockMarket(mv);
for (int i = 0; i < 5; i++) {
System.out.println("Boom (1) or Bust(2)? ");
int t = in.nextInt();
if (t == 1) {
System.out.println("Enter a percentage of increase as a decimal ( eg .5 ):");
double r = in.nextDouble();
if (t == 1) {
double e = u.boom(r);
System.out.println("The Stock Market is now at: " + e);
}
} else if (t == 2) {
System.out.println("Enter number of points lost:");
double l = in.nextDouble();
if (t == 2) {
double f = u.bust(l);
System.out.println("The Stock Market is now at: " + f);
}
}
}
}
}
Below is the class
public class StockMarket {
//Instance Variable Points
private double Points;
// Default no Argument Constructor
public StockMarket(){
this(0.0);
}
// Constructor #2
public StockMarket(double Points){
this.Points = Points;
}
//
public double getPoint(){
return Points;
}
public double boom(double x){
x = Points * (1 + x);
return x;
}
public double bust( double h){
h = Points - h;
return h;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class P8 {
public static void main(String[] args) {
double runningTotal = 0.00;
double subTotal = 0.00;
int d = 0;
int d1 = 1;
ArrayList<String> menuItems = new ArrayList<String>();
ArrayList<Double> menuCost = new ArrayList<Double>();
ArrayList<Integer> menuQuantity = new ArrayList<Integer>();
int counter = 0;
String[] options = {
"Y", "y", "Yes", "yes", "YES"
};
boolean found = false;
while(d < d1) {
++counter;
Scanner order = new Scanner(System.in);
System.out.print("What would you like to order? "); //item order
String foodItem = order.nextLine();
menuItems.add(foodItem);
Scanner quantity = new Scanner(System.in);
System.out.print("How many orders of that item would you like? "); //item order quantity
int foodQuantity = quantity.nextInt();
menuQuantity.add(foodQuantity);
double randNum = (double)(System.currentTimeMillis() % 11);
menuCost.add(randNum);
runningTotal = randNum * foodQuantity;
subTotal += runningTotal;
Scanner response = new Scanner(System.in);
System.out.print("Would you like to order more items? ");
String response1 = response.nextLine();
for (String elements:options) {
if (response1.equals(elements)){
found = true;
break;
}
}
if (found == true) {
found = false;
d = 0;
}
else {
int counter2 = 0;
int counter3 = 1;
while (counter2 <= counter) {
for (String elements:menuItems) {
double itemQuantity = menuQuantity.get(counter2);
double itemCost = menuCost.get(counter2);
System.out.printf("%2d%10s%5d%10.2f%10.2f\n", counter3, elements, itemQuantity, itemCost, (itemQuantity * itemCost));
counter2 += 1;
counter3 += 1;
}
}
break;
}
}
}
}
An example of what one line of this output would look like is this:
1 -- Red Wine -- -- 2 -- -- -- -- 6.25 -- -- -- -- -- 12.50
I want my code to keep iterating until the loop terminates. In Python this is extremely simple as I can simply iterate all the objects at the same time under one while-loop using the index. Unfortunately, as this is my first day actually coding in Java for one of my classes, I can't help but feel lost and think it has a completely different set of rules that I'm unable to grasp yet.
Basically, I just need to know how I can iterate over multiple array lists of different types and print them on a single line.
By the way, I am sorry but I do not know how I can format my posts correctly on this website which is why I used the horizontal lines to indicate spaces that represent the "%d and %s" of my code. I always get notifications of someone editing my post and it feels like I am getting criticized without being provided an opportunity to prevent it from happening. If someone can direct me to somewhere that shows how I can properly format my code, I would greatly appreciate it.
I comment out some lines to understand and solve your problem. U can see below code ;
import java.util.ArrayList;
import java.util.Scanner;
public class P8 {
public static void main(String[] args) {
double runningTotal = 0.00;
double subTotal = 0.00;
int d = 0;
int d1 = 1;
ArrayList<String> menuItems = new ArrayList<String>();
ArrayList<Double> menuCost = new ArrayList<Double>();
ArrayList<Integer> menuQuantity = new ArrayList<Integer>();
int counter = 0;
String[] options = {
"Y", "y", "Yes", "yes", "YES"
};
boolean found = false;
while (d < d1) {
++counter;
Scanner order = new Scanner(System.in);
System.out.print("What would you like to order? "); //item order
String foodItem = order.nextLine();
menuItems.add(foodItem);
Scanner quantity = new Scanner(System.in);
System.out.print("How many orders of that item would you like? "); //item order quantity
int foodQuantity = quantity.nextInt();
menuQuantity.add(foodQuantity);
double randNum = (double) (System.currentTimeMillis() % 11);
menuCost.add(randNum);
runningTotal = randNum * foodQuantity;
subTotal += runningTotal;
Scanner response = new Scanner(System.in);
System.out.print("Would you like to order more items? ");
String response1 = response.nextLine();
for (String elements : options) {
if (response1.equals(elements)) {
found = true;
break;
}
}
if (found == false) {
found = false;
d = 0;
} else {
int counter2 = 0;
int counter3 = 1;
//i changed this with counter2+1 , because your logic as arraylist and starts from zero. you will get outofbound exception
while (counter2 + 1 <= counter) {
for (String elements : menuItems) {
//do it itemquantity as integer , if u want double quantity , change.
int itemQuantity = menuQuantity.get(counter2);
double itemCost = menuCost.get(counter2);
//and here format is wrong in itemQuantity, if your itemQuantity param is double write %2f , if integer write %5d
System.out.printf("%2d %10s %5d %10.2f %10.2f\n", counter3, elements, itemQuantity, itemCost, (itemQuantity * itemCost));
counter2 += 1;
counter3 += 1;
}
}
break;
}
}
}
}
This is the change I made
if (found) {
found = false;
d = 0;
} else {
int counter2 = 0;
int counter3 = 1;
while (counter2 < counter) {
String menuItem = menuItems.get(counter2);
int itemQuantity = menuQuantity.get(counter2);
double itemCost = menuCost.get(counter2);
System.out.printf("%2d%10s%5d%10.2f%10.2f\n", counter3, menuItem, itemQuantity, itemCost, (itemQuantity * itemCost));
counter2 += 1;
counter3 += 1;
if (counter2 == counter) {
System.out.printf("%2d%10s%12s%13.2f\n", counter3, "Subtotal:", ".....", subTotal);
double i = subTotal * 0.08625;
System.out.printf("%2d%10s%12s%13.2f\n", counter3 + 1, "Tax:", ".....", i);
System.out.printf("%2d%10s%12s%13.2f\n", counter3 + 2, "Total:", ".....", (subTotal + i));
break;
}
}
break;
}
I've looked around for answers for this but I cannot find it. My professor requires me to use an array.. not an arraylist
public static void main(String[] args) {
final int total = 30;
String[] animalType = new String[total];
Scanner input = new Scanner(System.in);
for (int x = 0; x < total; x++) {
System.out.println("Enter the type of animal " + x + 1);
animalType[x] = input.next();
for (int x1 = 0; x1 < total; x1++) {
System.out.println("Enter the weight of the animal " + (x1 + 1));
animalType[x1] = input.next();
}
input.close();
System.out.println("Your friends are");
for (int counter = 0; counter < total; counter++) {
System.out.println(animalType[counter] + "\n" + animalType[counter]);
}
}
}
The prompt is.. allow user to enter the type of the animal and the weight of the animal and then output the average weight by animal type.
I'm new to java and do not know how to use arrays properly.
I think you should create a class for this purpose.
First, create another file called Animal.java and write a class that stores a type and a weight:
public class Animal {
public String type;
public int weight;
}
Of course, it would be better if you add getters and setters, but that would be too hard for you I think. I'll show the code anyways, but I won't use it in the example below.
public class Animal {
private String type;
private int weight;
public String getType() {return type;}
public void setType(String value) {type = value;}
public int getWeight() {return weight;}
public void setWeight(int value) {weight = value;}
}
Now you have this class, you can create an array of it.
Animal[] animals = new Animal[total];
And you need to fill the array in with animals!
for (int i = 0 ; i < total ; i++) {
animals[i] = new Animal();
}
Actually, your for-loops are wrong. If you want to ask the user for the type first, then the weight, you should do it like this:
for (int x = 0; x < total; x++) {
System.out.println("Enter the type of animal " + x + 1);
animals[x].type = input.next();
}
for (int x1 = 0; x1 < total; x1++) {
System.out.println("Enter the weight of the animal " + (x1 + 1));
animals[x1].weight = Integer.parseInt(input.next());
}
Now you got the types and weights of the animals, hooray!
You need a second array to store the weight(s). Something like
String[] animalWeight = new String[total];
for(int x1 = 0; x1 < total; x1++){
System.out.println("Enter the weight of the animal "+(x1+1));
animalWeight[x1] = input.next();
}
Next, you print the values from your two arrays. And I would prefer calling println twice to embedding a \n (on some systems that can also cause issues, because they use other line termination characters such as \r\n). That might look something like,
// input.close(); // <-- Also closes System.in, can cause subtle bugs.
System.out.println("Your friends are");
for(int counter = 0; counter < total; counter++){
System.out.println(animalType[counter]);
System.out.println(animalWeight[counter]);
}
I've been working on this for a while but can't seem to get it. I need to store user input into an array from another object but I can't get it to work. I'm not sure if its my constructor or I'm missing something but any help is appreciated
Here is the output program
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 'p' to create a polygon");
String in = sc.next();
if (in.equals("p")) {
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side=0;
Polygon ps;
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
ps = new Polygon(side);
}
ps = new Polygon(side);
Here is the constructor of the other class
public class Polygon {
protected int[] sideLengths;
public Polygon(int sides){
sideLengths= new int[sides];
}
you need to do
ps=new Polygon(numSides+1); //adding 1 because for-loop starts with index 1
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
ps[i]=side;
}
by this what we do is assign the 'side' value entered by user to a particular index in array.
hope this helps!
Good luck
The way I understand your Program I think you are looking for this kind of logic
if (in.equals("p")) {
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side = 0;
Polygon ps;
int sideLengths[] = new int[numSides];// array to store length of polygon of sides `numSides`
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
sideLengths[i-1] = sc.nextInt();// creating array to store lengths
}
ps = new Polygon(sideLengths);// generating your pollygon by sending the array
}
And you Polygon class should look like this
class Polygon {
protected int[] sideLengths;// storing the lengths of all sides
public Polygon(int dimensions[]) {
sideLengths = dimensions ;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 'p' to create a polygon");
String in = sc.next();
if(in.equalsIgnoreCase("p")) {
Integer sides[];
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side=0;
if(numSides>0){
sides = new Integer[numSides];
}
Polygon ps;
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
sides[i] = side;
}
ps = new Polygon(sides);
}
}
public class Polygon {
private Integer[] sides;
public Polygon(Integer[] sides){
this.sides = sides;
}
}
Now we have created an array of size of sides and array is been passed as an argument to constructor for initializing Polygon's object
it should be like
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 'p' to create a polygon");
String in = sc.next();
if (in.equals("p")) {
System.out.println("How many sides?");
int numSides = sc.nextInt();
int side=0;
Polygon ps = new Polygon(numSides);
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
ps.addSide(side, i-1);
//ps = new Polygon(side);
}
//ps = new Polygon(side);
}}}
and Polygon class like
public class Polygon {
protected int[] sideLengths;
public Polygon(int sides){
sideLengths= new int[sides];
}
public void addSide(int side, int index){
sideLengths[index] = side;
}
}
You are calling the constructor correctly, but after for loop ends you are again creating a new instance of Polygon and assigning it to ps. Either create an array of int or ArrayList of Integer, and store each instance of Polygon side length in that just before the for loop ends.
ArrayList<int> psListpsSideLengthList = new ArrayList<int>;
for (int i = 1; i <= numSides; i++) {
System.out.println("Enter the length of side " + i);
side = sc.nextInt();
psListpsSideLengthList.add(side);
}