append int values in an emty array java - java

I wrote a programm to print out all the prime number up to a limit. Then put those prime numbers into an ArrayList, convert this ArrayList into an array, finally print the numbers out with their index.
Note: I couldnt print out an ArrayList with a for loop, it's possible with an array only, hence the conversion.
My question is:
Is there anyway to do it without pushing the numbers into an ArrayList first, instead put them right away into an emty array of a length < given limit.
Thanks for you help!
was browsing SO in the last 2 days and couldnt find anything
import java.util.Scanner;
import java.util.ArrayList;
public class test {
public static void main(String[] args){
//get input till which prime number to be printed
System.out.print("Enter the number till which prime number to be printed: ");
int limit = new Scanner(System.in).nextInt();
System.out.print("\n");
ArrayList<Integer> myArray = new ArrayList<Integer>();
//printing primer numbers till the limit ( 1 to 10)
System.out.println("Printing prime number from 1 to " + limit + "\n");
for(int number=2; number <= limit; number++){
if(isPrime.numberPrime(number)){
myArray.add(number);
}
}
System.out.println(myArray + "\n");
//Convert ArrayList into an Array
int[] newArray = new int[myArray.size()];
for(int i = 0; i < myArray.size(); i++) {
newArray[i] = myArray.get(i);
}
System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int counter = 0; counter<newArray.length; counter++){
System.out.println(counter+1 + "\t" + newArray[counter]);
}
}
here is the result:
Enter the number till which prime number to be printed: 10
Printing prime number from 1 to 10
[2, 3, 5, 7]
There were 4 prime numbers
Index Value
1 2
2 3
3 5
4 7

No need to do this
//Convert ArrayList into an Array
int[] newArray = new int[myArray.size()];
for(int i = 0; i < myArray.size(); i++) {
newArray[i] = myArray.get(i);
}
System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int counter = 0; counter<newArray.length; counter++){
System.out.println(counter+1 + "\t" + newArray[counter]);
}
In place of this, simply write
System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int i=0;i<myArray.size();i++)
System.out.println(i+1 + "\t" + myArray.get(i));

Related

Appending number values to an array in java

I'm solving a problem to find all the multiples of 3 and 5 within a number that is inputted from the user.
I want to show all the multiples and their sum to the user.
I can't find a way to add the values to the array containing the multiples.
Here is the code:
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.*;
public class application {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Input the number from user:
System.out.println("Enter a number to calculate the sum of all the multiples of 3 or 5 below it: ");
int number = input.nextInt();
int i = 1;
int[] arr = {};
System.out.println("The multiples of 3 and 5 below the number " + number + " are: ");
while(i < number) {
if (i % 3 == 0 || i % 5 == 0 ) {
System.out.print(i + ",");
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = i;
}
i++;
}
int sum = IntStream.of(arr).sum();
System.out.println("The sum of these multiples is: " + sum);
//Thank you :D
}
}
Try just adding the multiples together as they are found.
You do not need an array to store them since your code is a) printing out the multiple found and then b) printing out the sum of the multiples
instead of array you can direct sum of the multiple 3 and 5
int sum = 0
inside if statement
if (i % 3 == 0 || i % 5 == 0 ) {
System.out.print(i + ",");
sum += i;
//arr = Arrays.copyOf(arr, arr.length + 1);
//arr[arr.length - 1] = i;
}
and print out the sum

i want to find sum of array first and last element and 2nd and 2nd last element and 3rd and 3rd last element and so on

here remember array size and values is defined by user by the help of scanner class and i am using java
task is to find sum of first and last element and 2nd and 2nd last and so on
i already try research but failed
thanks in advance
int sum = 0;
int f = 0;
System.out.println("Your Array is even");
System.out.println("Kinldy enter Your Values of Array");
for(int i = 0 ; i<array.length ; i++)
{
array[i] = s.nextInt();
for(int j = 0 ; j< array.length-i-1 ; j++)
{
sum = j + array.length+1 ;
}
}
System.out.println("Your Sum " + sum);
You could just loop over your array and use the index to find the corresponding numbers from both sides.
The first element can be found by simply doing: array[i].
The corresponding element from the other side can be found by: array[array.length - 1 - i].
The complete code could be something like this:
public static void main(String[] args) {
int[] array = {1, 3, 6, 4, 1, 8};
for(int i = 0; i < array.length / 2; i++)
{
int firstNumber = array[i];
int secondNumber = array[array.length - 1 - i];
int sum = firstNumber + secondNumber;
System.out.println(firstNumber + " + " + secondNumber + " = " + sum);
}
}
Output:
1 + 8 = 9
3 + 1 = 4
6 + 4 = 10
I made the assumption that you only want to do this for half of the array. That's why the for loop is only executed as long as i<array.length / 2. This solution assumes that the length of your array is always an even number. If your array has an uneven length, the middle element will not be considered.
In case you do want to do this for the complete array, all you have to do is remove the / 2 from the for loop statement. The output will be:
1 + 8 = 9
3 + 1 = 4
6 + 4 = 10
4 + 6 = 10
1 + 3 = 4
8 + 1 = 9

Tallying dice rolls - array is printing wrong

Basically, two dice are rolled randomly a bunch of times and then the two dice values are added together (You roll a 6 and a 3, your total is 9).
The frequency of how many times the total is rolled is stored in totalTally[].
So say you roll 10 times, 3 of those times you roll a total of 9, totalTally[9] = 3.
Here's my code:
import java.util.Random;
public class dice
{
public static void main(String a[])
{
System.out.println("Creating arrays to store information. This might take a while.");
int[][] tally = new int[6][6]; //Creates an array called tally to keep track of how many times each number was rolled. [Dice1][Dice2]
int[] totalTally = new int[12]; //Creates an array called totalTally to keep track of frequency of totals rolled.
int[][] roll = new int[36000000][2]; //Creates an array to store dice roll info.
System.out.println("Rolling two 6-sided dice " + roll.length + " times...");
Random r = new Random(); //Creates a new random number generator
for (int i = 0; i < roll.length; i++) //For loop that rolls the dice to fill the length of the array.
{
roll[i][0] = (r.nextInt(6) + 1); //Assigns random number between 1 and 6 to the array for dice 1 result.
roll[i][1] = (r.nextInt(6) + 1); //Assigns random number between 1 and 6 to the array for dice 2 result.
tally[roll[i][0]-1][roll[i][1]-1]++; //Increments by 1 the respective result in the tally array.
totalTally[roll[i][0] + roll[i][1]-2]++; //Increments by 1 the respective result in the totalTally array.
}
System.out.println("All done. Results are below.");
//Following lines print first table header
System.out.println("\n ROLL SUMMARY:");
System.out.println("Dice 1 + Dice 2 Frequency");
System.out.println("---------------------------------");
for (int i = 1; i <= totalTally.length; i++)//for loop goes through totalTally values
{
System.out.println(" " + i + " " + totalTally[i-1]);
}
//Following lines print second table header
System.out.println("\n DETAILED VIEW:");
System.out.println("Dice 1 Dice 2 Total Frequency");
System.out.println("---------------------------------------------");
for (int j = 1; j <= 6; j++) //For loop goes through dice 1 values
{
for (int k = 1; k <= 6; k++) // Nested for loop goes through dice 2 values
{
System.out.println(j + " " + k + " " + (j+k) + " " + tally[j-1][k-1]); //Prints line for table with dice values
}
}
}
}
and here is the output I am getting for the first table with that code:
Dice 1 + Dice 2 Frequency
1 998639
2 1997209
3 2998118
4 4000336
5 4999210
6 6001277
7 5001144
8 4000794
9 3002596
10 2001501
11 999176
12 0
Here's my issue: It's not possible to roll a 1 if you are rolling two dice.
And it IS possible to roll a 12.
So all my values need to be shifted.
What am I doing wrong?
totalTally[roll[i][0] + roll[i][1]-2]++
Why you subtract 2 ?
you should subtract 1 instead
totalTally[roll[i][0] + roll[i][1]-1]++
This is how you "tally" a single die.
Random r = new Random();
int[] die1 = new int[5]; //Creates an array to tally die 1
for (int roll = 0; roll < totalRolls; roll++) {
die1[r.nextInt(6)] += 1; // increment the index of the random roll
}
Do that for each die.
Your total tally would look like this to count individual rolls
for (int side = 1; side <= 6; side++) {
System.out.printf("%d\t%d\n", side, die1[side-1] + die2[side-1]);
}
If you want to tally the total of the rolls, sure, start printing at 2, not 1
System.out.println("Dice 1 + Dice 2 Frequency");
System.out.println("---------------------------------");
/// See here
for (int i = 1; i <= totalTally.length; i++)//for loop goes through totalTally values
{
System.out.println(" " + i + " " + totalTally[i-1]);
}

Individually sum random numbers not in an array?

This is part of a school assignment which I've already turned in, I was graded down in one portion because the total sum of the random numbers was supposed to be adding the individual numbers together, not each line.
So if the lines read:
1 2 3
4 5 6
The total should be 21, not 579 as my program is doing now. I've really been struggling trying to figure this out. I tried generating a different random number object for each integer, for a total of three of them but that completely screwed up my output.
We're learning arrays next week, and after researching online I could do this easily with an array, but the assignment was to be done without arrays. How can I sum each entry individually? Thanks for any help!
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class lottery {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int gameType, gameTimes;
int randomNums, lotNum, sum = 0;
System.out.println("\t\t Welcome to\n \t\tJAVA LOTTERY!\n\n\n");
System.out.print(" Would you like to play with 3, 4, or 5 numbers? ");
gameType = input.nextInt();
System.out.println("\n\n Now think about a number with " + gameType + " digits and remember it!\n\n\n");
System.out.print(" How many games should we play? ");
gameTimes = input.nextInt();
System.out.println("\n\n We're all done! We played " + gameTimes + " games!\n\n" +
" The numbers randomly selected were: ");
for(int i = 0; i < gameTimes; i++)
{
lotNum = 0;
for(int j = 0; j < gameType; j++)
{
randomNums = (new Random()).nextInt(10);
lotNum = (lotNum * 10) + randomNums;
System.out.print(" " + randomNums);
}//end nested for loop
System.out.println();
sum += lotNum;
}//end for loop
System.out.println("\n\nThe total of all of the numbers was " + sum );
input.close();
}//end main method
}//end lottery class
Change
lotNum = (lotNum * 10) + randomNums;
to
lotNum += randomNums;

Need help using random numbers and modulos

I'm trying to make a simple program that will display 20 random numbers between 1 and 100 and then print out which numbers are divisible by 3 and equivalent to 1%3 and 2%3. It seems to work just fine but I've noticed it only works with the very last number in the list. What am I missing to include all the numbers in the search for my math? Thank you in advance for any help I can get!
import java.util.Random;
public class Lab5 {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
for(int i=0;i<=repeat;i++){
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
}
System.out.println();
System.out.println("-------------------------------------");
if(n % 3 == 0){
System.out.println("Numbers divisible by three: "+n+(", "));
}else{
System.out.println("Numbers divisible by three: NONE");
}
System.out.println("-------------------------------------");
if(n == 1 % 3){
System.out.println("Numbers equivalent to one modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to one modulo three: NONE");
}
System.out.println("-------------------------------------");
if(n == 2 % 3){
System.out.println("Numbers equivalent to two modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to two modulo three: NONE");
}
}
}
It is only printing the last number because the check if the number is divisible, etc is not in your for loop at the top. Simply copy and paste all of the code below it into your for loop and it should work as you intended.
You also have an error here: if (n == 1 % 3), it is legal but will check if n is equal to the remainder of 1 / 3. I don't think that is what you wanted to achieve, so correct it like this: if (n % 3 == 1) as Ypnypn suggested.
Your n is declared outside of the loop body, so its value will persist. However, since you are overwriting n in each loop iteration, only the last value of n will persist and will be used by other parts of the program.
As Ypnypn has said, correct your use of modulo, and as Arbiter and deanosaur have suggested, move the rest of the program logic inside the for loop
The correct syntax for modulus is n % 3 == 2. The current code n == 2 % 3 means n == 0, since the order of operations in Java requires that modulus is evaluated before equality.
You are putting all the output statements (System.out.println()) outside your loop, so it only outputs the last value.
Move your output statements so they are inside your loop:
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
int[] numbers = new int[3]; // To hold how many numbers have modulo 0, 1 or 2
for(int i = 0; i <= repeat; i++) {
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
if(n % 3 == 0)
System.out.println("The number " + n + " is divisible by 3");
else
System.out.println("" + n + " modulo 3 = " + n % 3);
numbers[n % 3]++;
}
System.out.println("Numbers divisible by 3: " + numbers[0]);
System.out.println("Numbers with modulo 3 = 1: " + numbers[1]);
System.out.println("Numbers with modulo 3 = 2: " + numbers[2]);
}
Well .. you did not calculate anything in the loop, so your print statements work the last value of n after you exited the loop. Try something like
package com.example.modulo;
import java.util.Random;
public class Modulo {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
int[] nMod = new int[3];
nMod[0] = 0;
nMod[1] = 0;
nMod[2] = 0;
for (int i = 0; i <= repeat; i++) {
n = rnd.nextInt(100) + 1;
nMod[n%3] = nMod[n%3] + 1;
System.out.print(n + " (" + n%3 + "), ");
}
System.out.println();
System.out.println("-------------------------------------");
System.out.println("Numbers divisible by three: " + nMod[0] + (", "));
System.out.println("Numbers equivalent to one modulo three: " + nMod[1] + (", "));
System.out.println("Numbers equivalent to two modulo three: " + nMod[2] + (", "));
}
}

Categories

Resources