I'm only a beginner, so I know data structure and code logic isn't very good at all.
So this is a portion of a project, but I am having difficulty formatting the for loop. I am pretty sure I have to create some kind of for each loop. I wasn't sure how to do it, so I created a very simplified and broken down version (I know most of the code is in practice, but I wanted to visualize it. I need help printing out the total sales for each category of product. Right now, I only have four values, but if I were to go up to 30 values, this code would not work obviously. So any tips on how to create the for loop?
public static int[] totalSale( int[] mac, int[] iphone, int[] ipad, int[] ipod ){
int[] totalSale = {0,0,0,0};
for (int i = 0; i < mac.length ; i++) {
totalSale[0] = totalSale[0] + mac[i];
totalSale[1] = totalSale[1] + iphone[i];
totalSale[2] = totalSale[2] + ipad[i];
totalSale[3] = totalSale[3] + ipod[i];
}
for (int i = 0; i < totalSale.length; i++) {
System.out.println("Total sale for category " + i + ": $" +
}
return totalSale;
}
Change
for (int i = 0; i < totalSale.length; i++) {
if (i == 0) {
System.out.println("Total sale for category " + i + ": $" + totalSale[0]);
}
if (i == 1) {
System.out.println("Total sale for category " + i + ": $" + totalSale[1]);
}
if (i == 2) {
System.out.println("Total sale for category " + i + ": $" + totalSale[2]);
}
if (i == 3) {
System.out.println("Total sale for category " + i + ": $" + totalSale[3]);
}
}
to
for (int i = 0; i < totalSale.length; i++) {
System.out.println("Total sale for category " + i + ": $ + totalSale[i]);
}
There's no need to create an if-statement for every single element in the array totalSale. Think about general cases for the array when dealing with loop statements involving arrays. Since you're printing out every single element in the array with the same line "Total sale for category", you can toy with it and think about what's changing and what isn't.
Clearly, the only things changing are i and the element in the array that's being printed out. What's changing can be represented by variables (i, totalSale[i]) and what's not changing can be represented by constants ("Total sale for category", "$"). Therefore, you only need one line in your for-loop to express this when printing out elements of an array.
EDIT: A way to deal with the problem of accepting a variable number of sales categories in your method is to instead make your method take in a 2D array, in which the number of rows is the number of categories and the number of columns ins the number of sales within each category. For example, int sales[][] = new int[30][20] represents an array of 30 categories with 20 sales in each category. So modify the header,
public static int[] totalSale( int[] mac, int[] iphone, int[] ipad, int[] ipod )
to
public static int[] totalSale(int[][] sales)
and change this,
int[] totalSale = {0,0,0,0};
for (int i = 0; i < mac.length ; i++) {
totalSale[0] = totalSale[0] + mac[i];
totalSale[1] = totalSale[1] + iphone[i];
totalSale[2] = totalSale[2] + ipad[i];
totalSale[3] = totalSale[3] + ipod[i];
}
to
int[] totalSale = new int[sales.length];//sales.length is the number of
//rows/categories in sales
for (int i = 0; i < sales.length ; i++) {
for (int j = 0; j < sales[i].length; j++) { //sales[i].length is the number
//of sales/columns per category
totalSale[i] = totalSale[i] + sales[i][j];//sales[i][j] is the jth
//sale in the ith category
}
}
And lastly in the main, those 4 arrays can now be replaced with a 2D array.
Replace,
int[] mac = {200,9000,13000,900};
int[] iphone = {500,5000,200,0};
int[] ipad = {900,4300,0,800};
int[] ipod = {0,300,120,500};
with
int[][] sales = { {200,9000,13000,900},
{500,5000,200,0},
{900,4300,0,800},
{0,300,120,500}}; //how you define a 2D array
Above is a 4x4 array but it can be flexible. You can make it 10x10, 20x20, 30x30, etc.
Lastly, don't forget to change the method call to take in only one parameter now, the 2D array.
Change
popularDay(days,mac,iphone,ipad,ipod);
to
popularDay(sales);
Here, i can see that you are assuming mac, iphone, ipad and ipod arrays will always have the same number of elements (length). Your code can break in the case one of them have a different length.
I would rather suggest this approach:
public static int[] totalSale( int[] mac, int[] iphone, int[] ipad, int[] ipod ){
int[] totalSale = {0,0,0,0};
for (int i = 0; i < mac.length ; i++) {
totalSale[0] = totalSale[0] + mac[i];
}
for (int i = 0; i < iphone.length ; i++) {
totalSale[1] = totalSale[1] + iphone[i];
}
for (int i = 0; i < ipad.length ; i++) {
totalSale[2] = totalSale[2] + ipad[i];
}
for (int i = 0; i < ipod.length ; i++) {
totalSale[3] = totalSale[3] + ipod[i];
}
System.out.println("Total sale for category mac: $" + totalSale[0]);
System.out.println("Total sale for category iphone: $" + totalSale[1]);
System.out.println("Total sale for category ipad: $" + totalSale[2]);
System.out.println("Total sale for category ipod: $" + totalSale[3]);
return totalSale;
}
First, calculate the total sale for each category by its own, using a for loop for each of them. Then writing the result back to the console without the for loop, since it has no reason to be used.
Varargs will help you:
https://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
public static int[] totalSale(int[]... categories) {
int[] totalSale = new int[categories.length];
for (int i = 0; i < totalSale.length; i++) {
for (int j = 0; j < categories[i].length; j++) {
totalSale[i] = totalSale[i] + categories[i][j];
}
System.out.println("Total sale for category " + i + ": $" + totalSale[i]);
}
return totalSale;
}
So, in this case you can either to pass any amount of parameters:
int[] totalSales = totalSale(mac, iphone, ipad, ipod, ipod2, iphone3, iphone4);
int[] totalSales2 = totalSale(ipod, ipod2, iphone3, iphone4);
Or make an array to pass only one parameter using the same method:
int[][] categories = {mac, iphone, ipad, ipod, ipod2, ipod3, iphone100500};
int[] totalSales2 = totalSale(categories);
And if you want use only the second way, then you can just define the method as:
public static int[] totalSale(int[][] categories)
I suppose you requirement is SUM all array data as below and store the result into the array too?
int[] mac = {200,9000,13000,900};
int[] iphone = {500,5000,200,0};
int[] ipad = {900,4300,0,800};
int[] ipod = {0,300,120,500};
int[] result equal to {macSUM, iphoneSUM, ipadSUM, ipodSUM}
So we can use two loops one if for each device, and other one is for each element in the array the code show below as example
public static int totalSale(int[] devices){
int sum;
for (int i = 0; i < devices.length ; i++) {
sum += devices[i];
}
return totalSale;
}
public static void main(String[] arguments) {
int[] days = {1,2,3,4};
int[] mac = {200,9000,13000,900};
int[] iphone = {500,5000,200,0};
int[] ipad = {900,4300,0,800};
int[] ipod = {0,300,120,500};
numberOfDays(days);
int[]totalSales = new int[4];
for(int i = 0; i < 4; i++) {
totalSales[i] = totalSale(mac);
}
}
Related
I'm pretty sure I've done most of the code correctly but I'm returning the wrong thing? I've tried using copyOf() but still had the same issue. It looks like I'm returning the object of an array rather than the elements? I need the method treble to return the original array repeated in order, three times in one array. So [1,2,3,] should look like [1,2,3,1,2,3,1,2,3] when trebled.
Any help would be much appreciated.
import java.util.Scanner;
import java.util.Arrays;
public class ArrayExercises
{
public static void main(String[] args)
{
final int SIZE = 5;
int[] array = new int[SIZE];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < array.length; i++)
{
System.out.print("Please enter whole number " + (i + 1) + ": ");
int input = scanner.nextInt(); // get input from the user
array[i] = input; // store the value in the array
}
printArray("Input array:", array);
// call method sum and print out the result
int sum = sum(array);
System.out.println("The sum of elements is " + sum);
// call method repeat and print out the result
int[] trebled = repeat(array);
System.out.println("The repeated array is " + trebled);
}
public static void printArray(String msg, int[] array)
{
System.out.println(msg + " " + Arrays.toString(array));
}
public static int sum(int[] array)
{
int s = 0;
for (int i = 0; i < array.length; i++)
s += array[i];
return s;
}
public static int[] repeat(int[] array) //this is the part I'm having trouble with
{
int len = array.length;
int[] multiplied = new int[len*3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < len; j++)
{
multiplied[i * len + j] = array[j];
}
}
return multiplied;}
}
Try using:
System.out.println("The repeated array is " + Arrays.toString(trebled));
to print your array instead of printing using the array variable name, because otherwise that will print the address of the array rather than the content.
your method is ok, the issue is how you print it because as mentioned in the comments you do not use your printArray() method in this case.
So try changing this line :
System.out.println("The repeated array is " + trebled);
to :
printArray("The repeated array is " , trebled);
I'm trying to let my code print numbers I put in output but using array method.
package pkg11;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = 0;
System.out.println("How many number do you want to put?");
int b = in.nextInt();
for (int z = 1; z <= b; z++) {
System.out.println("Input your" + " " + z + " " + "number");
x = in.nextInt();
}
System.out.println();
int[] a = new int[x];;
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
The problem is when it's printing it only prints the last value, for example, I put that I want to put 3 numbers, the first was 1 the second was 2 the third was 3, it prints the third without putting the first 2.
Have a close look at the following code fragment of yours and try to spot the error:
for (int z = 1; z <= b ; z++) {
System.out.println("Input your" +" " +z +" " +"number");
x = in.nextInt();
}
// here you create the array
int [] a = new int [x];
If you didnt spot it: You create the array you want to save each integer in after you have read all values from the console. There is no way you can store the users input in the array, since it is not known at that time.
Then, what did you actually do?
You used the same variable x all the time x = in.nextInt();, overriding each input.
What can i do to solve the problem?
Scanner in = new Scanner(System.in);
int x = 0;
System.out.println("How many number do you want to put?");
int b = in.nextInt();
int[] a = new int[b];
for (int z = 0; z < b; z++) {
System.out.println("Input your" + " " + (z + 1) + " " + "number");
a[z] = in.nextInt();
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
First, declare int[] a = new int[b]; before you read the values and assign each input the the array with a[z] = in.nextInt();. Also, i modified your loop index a little bit to make things easier.
Ok, what else can i do?
Apart from the user entering non numbers, this code is a little bit more bullet-proof! If you are looking for even more, you can use in.nextLine() and Integer.valueOf() to prevent the user from entering strings instead of numbers.
Scanner in = new Scanner(System.in);
int amountOfNumers;
System.out.println("How many number do you want to put? Amount: ");
amountOfNumers = in.nextInt();
while (amountOfNumers < 1) {
System.out.println("Please enter a number greater than one:");
amountOfNumers = in.nextInt();
}
int[] numbers = new int[amountOfNumers];
for (int i = 0; i < amountOfNumers; i++) {
System.out.println("Input your " + (i + 1) + " number: ");
numbers[i] = in.nextInt();
}
System.out.println("Your numbers are:");
Arrays.stream(numbers).forEach(System.out::println);
The variable "num" is a 2D array. I'm trying to check in that array, if there are any duplicates. "num" is a user-input.
I have extensively looked through Java documentation and asked my lectures and I can't get a working answer. I understand the concept, what I'm meant to do, but just can't get the coding right.
Here is my code:
for(int i = 0; i < 3; i++){ //3 rows with 5 numbers each
for(int j = 0; j < 5; j++){
num[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value for line: " + i + " and position: "+ j ));
if((num[i][j] == num[i][0]) || (num[i][j] == num[i][1]) ||(num[i][j] == num[i][2]) || (num[i][j] == num[i][3]) || (num[i][j] == num[i][4])){
if(num[i][j] != 0){
num[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "ERROR. Enter value for line: " + i + " and position: "+ j ));
}
}
}
}
I have also tried using HashSet, but I think that only works with 1D arrays.
I would like to use something like this, as I feel this I understand the most:
secret = new Random().ints(1, 40).distinct().limit(5).toArray();
But obviously not with Random.
I've tried this:
Set<Integer> check = new HashSet<>();
Random gen = new Random();
for(int i = 0; i < 3; i++){ // 3 rows, 5 numbers
for(int j = 0; j < 5; j++){
num[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value for row " + i + " and position " + j));
check.add(gen.nextInt(num[i][j]));
}
}
This last section of coding (directly above this) compiles and runs, but doesn't check for duplicates.
There are alternative ways to checking for duplicates (e.g. you could loop back through the data you've entered previously into the 2D array in order to check for duplicate values) however here's how I'd go about using a Set to check for duplicates in order to, Are you trying to populate the 2d array with all unique values, where each value is from the user?? (also - knowing this explicitly in the original post would be very helpful, thanks to Michael Markidis for specifying that)
With a little UX knowledge here, separating the ERROR is def helpful to the end-user, as ERROR + re-input at the same time is confusing.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JOptionPane;
public class App {
public static void main(String[] args) {
int[][] num = new int[3][5];
System.out.println("Before:");
for (int i = 0; i < 3; ++i)
System.out.println(Arrays.toString(num[i]));
Set<Integer> data = new HashSet<Integer>();
for (int i = 0; i < 3; i++) { // 3 rows with 5 numbers each
for (int j = 0; j < 5; j++) {
boolean isGoodInput = false;
while (!isGoodInput) {
String input = JOptionPane.showInputDialog(null, "Enter value for line: " + i + " and position: " + j);
Integer n = Integer.parseInt(input);
if (data.contains(n)) {
JOptionPane.showMessageDialog(null, "ERROR: Try again");
} else {
num[i][j] = n;
isGoodInput = data.add(n);
}
}
}
}
System.out.println("After:");
for (int i = 0; i < 3; ++i)
System.out.println(Arrays.toString(num[i]));
}
}
Note: the 2D array is limited to your specification in the original post as a 3x5, so you'd have to change these values in multiple places to make different sized arrays - perhaps making these more dynamic could speed up further development of this application in the future.
Here's one way to accomplish this where you use the hashset to track what has already been inserted into the 2D array:
int[][] num = new int[3][5];
Set<Integer> check = new HashSet<>();
for (int i = 0; i < 3; i++)
{ // 3 rows, 5 numbers
for (int j = 0; j < 5; j++)
{
int n = 0;
do
{
n = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value for row " + i + " and position " + j));
} while (!check.add(n)); // keep looping if it was in the hashset
// add it to the array since we know n is not a duplicate at this point
num[i][j] = n;
}
}
My problem is based on the compound interest formula. A = P(1 + r)^n. I have a number of values for r and n which I must store as an array. I also must output my range of final values A as an array also. I think I have stored r and n correctly as an array. However my problem is with the final values of A and storing each value A. SO far this is what I have written.
import java.util.Scanner;
import javax.swing.*;
public class Prin {
public static void main (String [] args){
System.out.println("Please enter the Principal you wish to invest =>");
Scanner stdio = new Scanner (System.in);
int principal = stdio.nextInt();
stdio.nextLine();
System.out.println("This program will now calculate the final amount A for (years) n = 1,2,3,4 and the rate r = 1%, 1.5%, 2%, 2.5%, 3%");
int yearsarray[] = {1,2,3,4};
double ratearray[] = {0.010, 0.015, 0.020, 0.025, 0.030};
double amountarray[];
amountarray = new double[19];
for(int i=0; i<=3; i++)
{
for(int j=0; j<=5; j++){
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" answer " + amountarray[k] );
}
}
Do I need another for loop to increase the values of k in amountarray[]?
I would like to have all values of amountarray i.e amountarray[0], amountarray[1], amountarray[2], .......and so on.
Thanks in advance for any help.
amountarray = new double[19];
The code above is false because you need to have 4x5 = 20 double values
This code will always work properly, You should use this and you need to learn write your codes like this:
public class Prin {
public static void main (String [] args){
//...
int[] yearsarray = {1,2,3,4};
double[] ratearray = {0.010, 0.015, 0.020, 0.025, 0.030};
double[] amountarray = new double[yearsarray.length * ratearray.length];
int k = 0;
for(int i=0; i<yearsarray.length; i++){
for(int j=0; j<ratearray.length; j++){
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" answer " + amountarray[k] );
k++;
}
}
"This program will now calculate the final amount A for (years) n = 1,2,3,4 and the rate r = 1%, 1.5%, 2%, 2.5%, 3%"
... this implies your answer comes in the form of a 2-dimensional matrix.
Hence your amountarray needs to be defined as:
double amountarray[][] = new double[yearsarray.length][ratearray.length];
Then you would calculate:
amountarray[i][j] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
No, you don't
int k=0; // initialization
for(int i=0; i<=3; i++)
{
for(int j=0; j<=5; j++){
// use post-increment
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" answer " + amountarray[k] );
// now we can increment k
k = k+1;
}
Also this: as you seem to be using yearsarray just to get a value that's i+1, why just not do
amountarray[k] = principal * Math.pow((1 + ratearray[j]), i+1);
That way you can get rid of yearsarray, at least in this case
EDIT: a reworked version that also handles a couple of other minor issues and reduced usage of "magic numbers"
public class Prin {
public static void main(String[] args) {
System.out.println("Please enter the Principal you wish to invest =>");
Scanner stdio = new Scanner(System.in);
int principal = stdio.nextInt();
stdio.nextLine();
System.out.println("This program will now calculate the final amount A for (years) n = 1,2,3,4 and the rate r = 1%, 1.5%, 2%, 2.5%, 3%");
int yearsarray[] = {1, 2, 3, 4};
double ratearray[] = {0.010, 0.015, 0.020, 0.025, 0.030};
double amountarray[];
// this way the array will follow the size of yearsarray and ratearray
amountarray = new double[yearsarray.length * ratearray.length];
int k = 0; // initialization
for (int i = 0; i <= yearsarray.length; i++) {
System.out.println("years=" + yearsarray[i]);
for (int j = 0; j < ratearray.length; j++) {
// use post-increment
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" " + ratearray[j] + " answer " + amountarray[k]);
k+=1;
}
}
}
}
Try to store your data in a Map, this is an example of your loop
for(int i=0; i<=yearsarray.length; i++) {
for(int j=0; j<=ratearray.length; j++) {
double answer = (yearsarray, principal * Math.pow((1 + ratearray[j]), yearsarray[i]));
Collection<Double> aux;
if (!answers.containsKey(yearsarray[i])){
aux = new ArrayList<Double>();
aux.add(answer);
} else {
aux = answers.get(yearsarray[i]);
aux.add(answer);
}
answers.put(yearsarray[i], aux);
// include the answers in a Map
}
}
Thanks
First of all, I have seen a similar question relating to C++, but I didn't quite understand it - plus my question is about Java.
Basically I have coded two methods that can use SelectionSort and BubbleSort on an array parsed in. While I believe I have the methods working correctly (I have run tests and they all have sorted the numbers in ascending order), I am not sure if I am counting the number of comparisons and number swaps correctly. If someone is able to test my code below and offer some feedback, I will be very grateful.
Note: I can zip up my Java project files and send them to anyone if needed.
BubbleSort method:
public String bubbleSort(int[] numbers)
{
System.out.println("******|Bubble Sort|******");
StringBuilder originalArray = new StringBuilder();
for(int i = 0; i <= numbers.length - 1; i++)
{
originalArray.append(numbers[i] + " ");
}
System.out.println("Original array: " + originalArray);
int temp; // temporary variable
//Set boolean variable to true,
//to allow the first pass.
boolean pass = true;
int comparisons = 0;
int swaps = 0;
//While a pass can be made,
while(pass)
{
//Set the boolean value to false,
//indicating a number swap could
//be made.
pass = false;
for(int i = 0; i < numbers.length - 1; i++)
{
//increment the number of comparisons by 1.
comparisons++;
if(numbers[i] > numbers[i+1])
{
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i+1] = temp;
//increment the amount of swaps made by 1,
//to put numbers in correct order.
swaps++;
pass = true;
}
}
}
//Create a StringBuilder object - to hold
//the output of sorted numbers.
StringBuilder sb = new StringBuilder();
//Loop through the now sorted array - appending
//each subsequent number in the array to the
//StringBuilder object.
for(int i = 0; i < numbers.length; i++)
{
sb.append(numbers[i] + " ");
}
//Return the final results of the sorted array.
return "Sorted Array (asc): " + sb.toString() + "\nComparisons made: " + comparisons
+ "\nSwaps made: " + swaps;
}
SelectionSort method
public String selectionSort(int[] numbers)
{
System.out.println("******|Selection Sort|******");
StringBuilder originalArray = new StringBuilder();
int comparisons = 0;
int swaps = 0;
for(int i = 0; i <= numbers.length - 1; i++)
{
originalArray.append(numbers[i] + " ");
}
System.out.println("Original array: " + originalArray);
//Declare variable to hold first element
int first;
//declare temporary variable, to be used in
//swapping integers.
int temp;
for(int x = numbers.length - 1; x > 0; x--)
{
first = 0;
comparisons++;
for(int y = 1; y <= x; y++)
{
//comparisons++;
if(numbers[y] > numbers[first])
{
first = y;
//comparisons++;
swaps++;
}
temp = numbers[first];
numbers[first] = numbers[x];
numbers[x] = temp;
//swaps++;
}
}
//Create a StringBuilder object - to hold
//the output of sorted numbers.
StringBuilder sb = new StringBuilder();
//Loop through the now sorted array - appending
//each subsequent number in the array to the
//StringBuilder object.
for(int i = 0; i < numbers.length; i++)
{
sb.append(numbers[i] + " ");
}
//Return the final results of the sorted array.
return "Sorted Array (asc): " + sb.toString() + "\nComparisons made: " + comparisons
+ "\nSwaps made: " + swaps;
}
For BUBBLE SORT:
Key comparisons -> (n*(n-1))/2
Item assignments (swaps) -> 3*(n-1)
For SELECTION SORT:
Key comparisons -> (n*(n-1))/2 (same as bubble)
Item assignments (swaps) -> (n*(n-1))/4
(Note that n is the number of your array size)