I am working on an assignment and I'm not sure how to add the indices together to get a sum that can be displayed. Mind you I'm only a high school student so my code is sloppier and less efficient than what any of you would likely create, but any help is appreciated. Here's what I have right now that's producing an index out of bounds exception:
System.out.println("Please enter the amount of workers you have");
Scanner userInput = new Scanner (System.in);
int workerAmount = userInput.nextInt();
int payroll[][]= new int [workerAmount][6];
for(int a = 0; a < payroll.length; a++){
for(int b = 0; b < payroll[a].length; b++)
{
System.out.println("How many hours did this worker work?");
Scanner use = new Scanner (System.in);
int user = use.nextInt();
payroll[a][b] = user;
}
}
for(int i = 0; i < payroll.length; i++){
for(int a = 0; a < payroll[i].length; a++){
System.out.println(payroll[i][a]);
int sum = (payroll[i + a][a]);
}
}
to sum all the values, try this:
int sum = 0;
for(int i = 0; i < payroll.length; i++){
for(int a = 0; a < payroll[i].length; a++){
sum += payroll[i][a];
}
}
System.out.println("the sum is: " + sum);
The code above simply iterates through all the arrays of arrays and adds the value of each element onto the sum variable which then gets printed to the console.
Related
I'm trying to add all the elements together in an array that was decided through user input, Every time I run the code that I've constructed below I get a number that is obviously not the sum of the elements. What am I doing wrong?
import java.util.Scanner;
public class SumProduct
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in);
int[] array1 = new int [input.nextInt()];
input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
for (int i = 0; i < array1.length; i++)
{
int j = array1[i];
int k = array1[i]+1;
int sum = j + k;
System.out.print(sum);
}
}
}
You probably want to prompt the user to enter the size of the array if you're going to do this.This line of code is allowing whatever the user enters to be the size of your array.
int[] array1 = new int [input.nextInt()]; //this sets the size of the array through user input
scan doesn't exist in the currrent context:
input = scan.nextInt(); // this is invalid syntax as scan is not the Scanner you created
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
I would do this to keep adding elements to the array:
// no need for this: input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
System.out.println("Enter integer to add:");
array1[i] = input.nextInt();
}
This code will give you the sum of the elements if you just add one element at a time instead of two to the sum variable:
int sum = 0;
for (int i = 0; i < array1.length; i++)
{
sum += array1[i];
System.out.print(sum); // this will print out sum after each addition
}
System.out.print(sum); // this will print out sum after the entire array is summed
Adding some logic to only allow the user to enter so many numbers to the array would be helpful as well. You will need to move on from them entering data into the array at some point. Then also remember to close the scanner when you're finished getting data from the user:
input.close();
Your problem is in the following lines of code:
for (int i = 0; i < array1.length; i++)
{
int j = array1[i];
int k = array1[i]+1;
int sum = j + k;
System.out.print(sum);
}
it should look something like
int sum = 0;
for (int i = 0; i < array1.length; i++)
{
sum = sum + array1[i];
}
System.out.print(sum);
The first change is to declare the variable "sum" outside of the loop. The way it's written, it will get declared, then disappear, then declared, then disappear for every loop iteration. You also probably want to initialize it to 0
The second change is to your summation logic. Lets assume your array contains the three numbers [1, 2, 3] and walk through your logic.
j = array1[0] //(j == 1)
k = array1[0] + 1 //(k == 1 + 1 == 2)
sum = j + k //(sum == 1 + 2 == 3)
You then throw out the variable "sum" like I mentioned earlier, and start over with the same logic on the second array element, then again on the third.
i.e. j = 2, k = 2+1, sum = 2 + 2 + 1. followed by j = 3, k = 3 + 1, sum = 3 + 3 + 1.
You can probably see how this isn't the sum, and results in you logging the three digits 3, 5, and 7 for this example case.
In my updated logic, we simply loop through each element and add it to the current running total.
hope this helps
I found an exercise in my textbook that makes this 2D array.
I have the input loop working, and the table prints successfully but I can't find a way to take the values in each row and column and print out the totals as shown in the exercise.
I have asked my professor and he said he couldn't remember how to do it with a string array. I hope there is a way to convert each number from string to an int. I assume that creating a double array would have been much easier than a String array but at this point I wouldn't know convert all my work over.
package Assignment2;
import java.util.*;
/**
*
* #author Lyan
*/
public class Exercise7_20
{
public static void sales2DArray(int salesPerson, int product, double value)
{
}
public static void main(String[] args)
{
int salesP = 0; //salesPerson set to 0
String[][] table = new String[5][5]; // A matrix of '5 rows and '5 Columns'
//For loop that replaces null values in table with 0.00
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (table[i][j] == null) {
table[i][j] = " 0.0";
}
}
}
//Input for salesPerson
Scanner inSales = new Scanner(System.in);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//While loop to ask for salesPerson, product, and sales amount (val)
while(salesP > 0 && salesP < 5)
{
//input for Product number
Scanner inProduct = new Scanner(System.in);
System.out.println("Enter product number");
int productNum = inProduct.nextInt();
//input for sales amount
Scanner inValue = new Scanner(System.in);
System.out.println("Enter Sales amount");
double val = inValue.nextDouble();
//sets the values onto the table.
table[productNum - 1][salesP] = " " + Double.toString(val);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//makes the 1-5 on the left hand side of the table
}
for(int i = 1; i < 6; i++)
{
table[i-1][0] = " " + i + "";
}
//Hardcoded header
System.out.println("Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson 4 Total");
//Makes the 2D array to print in a box format rather than a straight line.
System.out.println(Arrays.deepToString(table).replace("],","]\n"));
//Anything below is my testing to get the total to print out for each individual salesPerson (column)
//and the totals for the products for all salesPerson (rows)
System.out.print("Total ");
String total = "";
int sum = 0;
for(int down = 0; down < 5; down++)
{
//append
}
//successfully reads the last value of each column but does not print the total
//only successfully prints the last value
for(int c = 1; c < 5; c++)
{
for(int r = 0; r < 5; r++)
{
String temp = table[r][c];
total = temp;
}
System.out.print(total + " ");
}
}
}
You can use this simple logic to find the sum of each individual row and column of your 2D array.
double[] sumOfRows = new double[5];
double[] sumOfCols = new double[5];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
sumOfRows[i] = sumOfRows[i] + Double.parseDouble(table[i][j]);
sumOfCols[i] = sumOfCols[i] + Double.parseDouble(table[j][i]);
}
}
Here we declare 2 additional arrays to store the sum of each row and column respectively. You can print them according to your logic as desired.
Also note use Double.parseDouble(...) to convert a String to a double.
I need to write a program that asks for 20 numbers and outputs the amount of even numbers. I figured out the loop part (for-loop) but i don't have any idea how to collect the data if that makes any sense.
Here is the loop:
for (int num = 0; num < 20; num++) {
System.out.println("Anna luku");
num = input.nextInt();
}
If you want to give the numbers when you run the program you can use this:
public static void main(String[] args) {
int counter=0;
Scanner sc = new Scanner(System.in);
System.out.println("Write 20 numbers:");
for(int i=0; i<20; i++) {
System.out.print("Number " + i + ":");
int temp =sc.nextInt(); //this waits for you to write an int
if(temp%2==0)
counter++;
}
sc.close();
System.out.println("Even numbers:" + counter);
}
i've tested it ant it works, keep in mind that you need to press enter after you write each number
You can use the code like this:
int count = 0;
for (int num = 0; num < 20; num++) {
System.out.println("Anna luku");
if (input.nextInt() % 2 == 0)
count++;
}
You can use the modulo operator to check if a number is divisible by another number (in this case - by 2). Note, BTW, that your code overwrites the loop variable, which is probably not what you meant:
int evens = 0;
for (int i = 0; i < 20; i++) {
num = input.nextInt();
if (num % 2 == 0)
evens++;
}
}
System.out.prinf("You inputted %d even numbers%n", evens);
Do you mean some thing like this ?
Scanner input = new Scanner(System.in);
int inputs[] = new int[20];
System.out.printf("Please enter %d numbers\n",inputs.length);
for(int i = 0; i < inputs.length;i++){
System.out.println("Enter value number "+(i+1));
int value = input.nextInt();
inputs[i]=value;
}
I'm trying to create a program that finds the probability of two random students in a room to have the same birthday. Number of students and number of simulations is inputted. Whenever I run it though, with 23 students, I consistently get 0.69, which is inconsistent with the actual answer of about 0.50. I think it probbaly has something to do with the fact that, if there are 3 students with the same birthday, it will count it as 3 matches. But I'm not sure how to fix this problem and I've already tried multiple times. Can I get some help?
import java.util.Scanner;
public class bday{
public static void main(String[] args){
Scanner inp = new Scanner(System.in);
System.out.println("How many students?");
int num = inp.nextInt();
System.out.println("How many times?");
int times = inp.nextInt();
double x[] = new double[num];
int match = 0;
for(int i=0;i<times;i++){
for(int j=0;j<num;j++){
x[j] = (int)(Math.random()*365)+1;
}
for(int j=0;j<num;j++){
for(int k=j+1;k<num;k++){
if(x[j]==x[k]){
match++;
}
}
}
}
double prob = (double)match/times;
System.out.println("The probability for two students to share a birthday is "+prob+".");
}}
You messed up the logic. The logic should be like this:
whenever there is a occurrence of same birthday, you add one to the total matches and then break then start another time. After you finished all the times, divide the total matches by how many times.
here is the code:
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
Scanner inp = new Scanner(System. in );
System.out.println("How many students?");
int num = inp.nextInt();
System.out.println("How many times?");
int times = inp.nextInt();
int x[] = new int[num];
int matches = 0;
boolean out = false;
for (int i = 0; i < times; i++) {
for (int j = 0; j < num; j++) {
x[j] = (int)(Math.random() * 365) + 1;
}
for (int j = 0; j < num; j++) {
for (int k = j + 1; k < num; k++) {
if (x[j] == x[k]) {
matches++;
out = true;
break;
}
}
if (out) {
out = false;
break;
}
}
}
double prob = (double) matches / times;
System.out.println("The probability for two students to share a birthday is " + prob + ".");
}
}
The test result: 0.50557 for 100000, 0.507591 for 1000000. Should be close to your answer.
A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented