Filling a int[] array - java

I must make a int array filled with 5000 numbers, and then take the value of each cell, which is a random number up to 1000, and multiply it by the square root of the cell index.
So far, my code is:
import java.util.*;
public class thousandArray{
public static void main (String args[]){
int numbers[] = new int[5000];
int r = 0 + (int)(Math.random()*1000);
double rt = numbers[r];
while(rt==numbers[r]){
r=0+(int)(Math.random()*1000);
double square = rt*Math.sqrt(numbers[r]);
System.out.println(square);
System.exit(0);
}
}
}
im pretty sure I did the code right, I cant figure out how to fill my array.

import java.util.*;
public class thousandArray{
public static void main (String args[]){
int numbers[] = new int[5000];
int r = 0 + (int)(Math.random()*1000);
double rt = numbers[r]; //you never assigned anything to numbers[r]
while(rt==numbers[r]){
r=0+(int)(Math.random()*1000);
double square = rt*Math.sqrt(numbers[r]);
System.out.println(square);
System.exit(0); //you exit the first time it loops
}
}
}

To fill an int array:
int[] numbers = new int[5000];
for (int i = 0; i < 5000; i++) {
numbers[i] = some_value;
}
To make the values be random, more or less as the problem states, you'd use:
numbers[i] = (int)(Math.random()*1000);
To multiply by the square root of the cell index:
numbers[i] = numbers[i] * (int)Math.sqrt(i);
Of course, that assumes that numbers should be an int array. It would make more sense for it to be a double array, in which case you'd remove the (int) casts.

public class ThousandArray {
public static void main (String args[]){
int MAX = 5000;
int numbers[] = new int[MAX];
for (int i = 0; i < MAX; i++) {
numbers[i] = (int)(Math.sqrt(i) * (Math.random()*1000));
}
}
}

Related

finding the average of array then finding the number above the average to print

import java.util.Scanner;
public class ProjectFour {
public static void main(String args[]) {
int[] firstArray = {1,2,3,2,1,6,3,4,5};
System.out.println("this is the average of array : "+analyzeNumbers(firstArray));
System.out.println("These are the numbers above the average : "+aboveAvg(firstArray));
}
//finding the average
public static int analyzeNumbers(int[] firstArray){
int avg;
avg=sumArray(firstArray);
avg=avg/firstArray.length;
return avg;
}
//suming the array method
public static int sumArray(int[] firstArray){
int sum = 0;
for(int x=0;x<firstArray.length;x++){
sum+=firstArray[x];
}
return sum;
}
**this is where im running into problems im kinda stumpted**
// this is my method i cant figure out trying to take the average and find all the numbers in the array above the average and printing them.
public static int aboveAvg(int[] firstArray){
int[] aboveAvg;
aboveAvg = new int[0];
int x;
for(x=analyzeNumbers(firstArray);x<firstArray.length;x++){
aboveAvg+=firstArray[x];
}
return aboveAvg;
}
}
Try using a for loop.
int sum = 0;
for(int i = 0; i < firstArray; i++) {
int getSum = firstArray.get(i);
sum + getSum;
}
int average = sum / firstArray.length;
int[] aboveAverage;
for(int c = 0; c < firstArray; c++) {
if(firstArray.get(c) > average) {
aboveAverage.add(firstArray.get(c));
}
}
This aboveAvg function is completly wrong.
public static List<Integer> aboveAvg(int[] firstArray){
List<Integer> aboveAvg = new ArrayList<Integer>();
int Avg = analyzeNumbers(firstArray);
for(int i = 0; i<firstArray.length; i++)
{
if(firstArray[i] > Avg)
{
aboveAvg.add(firstArray[i]);
}
}
return aboveAvg;
}
Check your for loop and more examples about it
+= will sum two values, won't add new element on any array.
you have to define your return value correctly.
You can use List for create arrays, it's more flexible.

Getting the size on an array from one method into another method where I will be filling the array with numbers

I must ask to the user for the size of the array. This method must be an integer. Then I must pass that value into another method where the user will fill the array, this method must be float.
It's throwing an error in this line float[] arraySize = new float [getLengthOfArray()]; In the second method.
The error says "Int[] cannot be converted to int".
I don't know what to do.
Here's the entire code
package Exercise;
import javax.swing.JOptionPane;
public class Exercise3 {
public static int[] arrayLenght(){
int arraySize = Integer.parseInt(JOptionPane.showInputDialog("Enter the array size"));
int[] totalArraySize = new int[arraySize];
return totalArraySize;
}
public static float[] fillArray(){
float[] arraySize = new float [arrayLenght()];
for (int i = 0; i < arraySize.length; i++) {
arraySize[i] = Float.parseFloat(JOptionPane.showInputDialog("Enter a number"));
}
return arraySize;
}
public static void calculateArithmeticAverage(float[] numbers){
int total = 0;
int average = 0;
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
}
average = total / numbers.length;
}
public static void main(String[] args) {
calculateArithmeticAverage(fillArray());
}
Your arrayLength method should return an int, not an array.
public static int arrayLength()
{
int arraySize = Integer.parseInt(JOptionPane.showInputDialog("Enter the array size"));
return arraySize ;
}

The mean and the standard deviation of the values in its array parameter

Here's My Code; and I can find an array with this and I would like to calculate the mean of the values (overall) after this I would like to calculate standard deviation of this but I couldn't understand the question exactly so I dont have a method for now. Here's the question for standard deviation (Write a method that takes two parameters --a set of int values in an array and a double value representing their mean-- and computes and returns the standard deviation of the values using the given mean.)
import java.util.*;
public class Test
{
final static int N = 100;
static int limit = 0;
static int[] list;
static int i, j;
static int sum = 0;
static Scanner scan = new Scanner (System.in);
public static int[] generateArray ()
{
System.out.print ("Enter your array limit: ");
limit = scan.nextInt();
list = new int[limit];
for(i = 0; i < limit; i++)
{
list[i] = (int) (Math.random() * 2 * N - N);
}
return list;
}
public static void printArray()
{
for(j = 0; j < limit; j++)
System.out.print (list[j] + "\t");
}
public static void meanArray()
{
sum = sum + list[j]; //PROBLEM HERE
System.out.println (sum);
}
public static void main(String[] args)
{
generateArray();
printArray();
meanArray(); //PROBLEM HERE
}
}
To generate the mean value, add up all values in your list and devide them by the number of values:
public static void meanArray() {
double result = 0;
for(int i : list) {
result += i;
}
result /= list.length;
System.out.println(result);
}

For loop with error in code

UPDATE****
I have my program compiling and executing correctly but now I have faced another problem. I need to create variables that will count each time a certain random number is generated. For example count0 is supposed to record how many times the integer 0 is generated. This is what I have:
import java.util.Random;
public class L10{
public static void main(String[] args){
int total = 100;
Random randObj = new Random();
final int UPPER_BOUND = 10;
for (int i=0; i < total; i++){
int randomInt = randObj.nextInt(UPPER_BOUND);
System.out.print("\n" + randomInt);
int count0 = 0;
if(randomInt==0){
System.out.print(randomInt + count0);
}
int count1 = 1;
if(randomInt==1){
}
int count2 = 2;
int count3 = 3;
int count4 = 4;
int count5 = 5;
int count6 = 6;
int count7 = 7;
int count8 = 8;
int count9 = 9;
}
}
}
The output shows the random number, in this case zero, and prints a zero next to it. I'm not exactly sure how to write code that keeps track of how many times zero is generated. Any suggestions?
Try this:
import java.util.Random;
public class HelloWorld{
public static void main(String []args){
Random randObj = new Random();
final int UPPER_BOUND = 10;
int total = 100;
String star = "*";
for (int i=0; i < UPPER_BOUND; i++){
int randomInt = randObj.nextInt(total);
System.out.print(randomInt);
}
}
}
Modifications:
Random randObj = new Random();
int randomInt = randObj.nextInt(total);
I think your intention is to generate 100 random integers in the range 0-9, and count the frequency of each.
Using separate variables for each count is a poor idea. A better idea is to use a single array of size 10, whose index is the random number.
Modifying your code:
public static void main(String[] args){
final int TOTAL = 100, UPPER_BOUND = 10;
Random randObj = new Random();
int[] count = new int[UPPER_BOUND];
// collect frequencies
for (int i=0; i < TOTAL; i++)
count[randObj.nextInt(UPPER_BOUND)]++;
// report frequencies
for (int i=0; i < UPPER_BOUND; i++)
System.out.print(i + "'s frequency was " + count[i];
}
import java.util.Random;
public class L10{
public static void main(String[] args){
int total = 100;
int[] CountArray = new int[total]; //count numbers
Random randObj = new Random();
final int UPPER_BOUND = 10;
for (int i=0; i < total; i++){
int randomInt = randObj.nextInt(UPPER_BOUND);
System.out.print("\n" + randomInt);
switch(randomInt){
case(0):{
CountArray[0]++;
break;
}
case(1):{
CountArray[1]++;
break;
}
case(2):{
CountArray[2]++;
break;
}
case(3):{
CountArray[3]++;
break;
}
case(4):{
CountArray[4]++;
break;
}
case(5):{
CountArray[5]++;
break;
}
case(6):{
CountArray[6]++;
break;
}
case(7):{
CountArray[7]++;
break;
}
case(8):{
CountArray[8]++;
break;
}
case(9):{
CountArray[9]++;
break;
}
}
}
System.out.println("");
for(int j = 0;j<UPPER_BOUND;j++){
System.out.println("number of "+ j+" generated "+CountArray[j]);
}
}
}
This is the Code that I came up with. I used an array to count each element and used switch case to count them separately. so at the end of the for loop. I printed them. This way you can get the number of elements distinctively.
You are missing () after new Random.

Fibonacci sequence in Java using for statements

I tried making a Java program executing the Fibonacci sequence.
Here's my code:
import java.io.*;
public class Fibonacci{
public static void main(String[]args){
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int ctr1=0;
int ctr2=0;
int num1=0;
int num2=0;
int num3=0;
try{
System.out.println("How many numbers would you want to see?");
ctr2=Integer.parseInt(Data.readLine());
for(int ans=0; ctr1==ctr2; ctr1++){
num1++;
System.out.println(num2 + "\n" + num1);
ans=num1+num2;
System.out.println(ans);
ans=num3;
}
}catch(IOException err){
System.out.println("Error!" + err);
}catch(NumberFormatException err){
System.out.println("Invald Input!");
}
}
}
Obviously, I'm a beginner in Java and I don't know how to properly use the for statement. Would somebody be kind enough to make my code work? Or maybe make a way shorter code that works. I'm a beginner so be cool. Thanks :)
Fibonacci series in java is actually quite simple and can be done with just one single for-loop!!!!
import java.io.*;
class fibonacci{
public static void main() throws NumberFormatException, IOException{
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int a,b,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=Integer.parseInt(Data.readLine());
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
This has been done using buffered reader........ If you are said to use only bufferedreader go for this else you can use Scanner class which is much simple and easy to use because you don't have to catch or throw any exceptions.....
Scanner program:-
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a,b,c;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
Now as I said in one loop you can do it.... Here is another method where you do the swapping inside the body of the loop and not in the arguments of it...
And this is much simplier to understand for beginners as u don't have to pass multiple variables inside the arguments and yeah its a bit longer
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a = 0,b = 1,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
System.out.println(a +"\n" +b);//\n is used to go to next line....
for (c=0;c<d;c++){
c = a + b;//Doing and printing the fibonacci...
System.out.println(c);
a = b;
b = c;//Swapping the values...
}
}
}
So here i have given you three methods that should give the same output(Most probably) choose whichever is convenient for you..
Look at this code snippet which is much easier than yours to understand. Solution tip is simple, you keep 2 pointers for the first 2 fibonacci numbers and update them appropriately in the loop. In the example below, the loop executes 10 times, you can modify it as desired.
static void fibonacci() {
int ptr1 = 1, ptr2 = 1;
int temp = 0;
System.out.print(ptr1 + " " + ptr2 + " ");
for (int i = 0; i < 10; i++) {
System.out.print(ptr1 + ptr2 + " ");
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp + ptr2;
}
}
Output:
1 1 2 3 5 8 13 21 34 55 89 144
Expanding on the answers, if you want to look really cool use recursion.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = 300; // how many numbers you want to generate
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
}
Here is Google search of what it is, hope those resources help: http://bit.ly/1cWxhUS
I'm a beginner in java as well however I've found an easy way to create a Fibonacci number using an array. The basic principle of a Fibonacci number is the addition of the current number and the number that came before.
Here is my code:
//Creation of array
int [ ] fib = new int[size];
//Assigning values to the first and second indexes of array named "fib"
fib [0] = 0;
fib [1] = 1;
//Creating variable "a" to use in for loop
int a = 1
//For loop which creates a Fibonacci number
for( int i = 2; i < size ; i++)
{
fib[i] = a;
a = fib[i] + fib[i-1];
}
This is another algorithm which I found online and I kind of simplified the code from it.
public static BigInteger fib(BigInteger x) {
if (x.intValue() < 0){return x.intValue() % 2 == 0 ?fib(x.multiply(BigInteger.valueOf(-1))).multiply(BigInteger.valueOf(-1)) : fib(x.multiply(BigInteger.valueOf(-1)));}
int n = Integer.valueOf(x.toString());
BigInteger a = BigInteger.ZERO,b = BigInteger.ONE;
for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
BigInteger d = a.multiply(b.shiftLeft(1).subtract(a));
BigInteger e = a.multiply(a).add(b.multiply(b));
a = d;
b = e;
if ((n & bit) != 0) {
BigInteger c = a.add(b);
a = b;
b = c;
}
}
return a;
}
I know there is a chance that you wont understand how to use BigInteger, so I am giving you this link, just trying to be helpful.
Here we get Fibonacci Series up to n.
public static void fibSequence(int n) {
int sum = 0;
for (int x = 0, y = 1; sum < n; x = y, y = sum, sum = x + y) {
System.out.print(sum + " ");
}
}
Example:
Input: n = 20
Output: 0 1 1 2 3 5 8 13
more simple way
public static void main(String[] args) {
int first = 1;
int second = 2;
for (int i = 0; i < 20; i++) {
if (i == 0)
System.out.print(first);
System.out.print("," + second);
int temp = second;
second = first + second;
first = temp;
}
}```
program output :: 1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946
import java.util.*;
public class sequence1
{
public static void main(String[] args)
{
sequence1 fs=new sequence1();
fs.fibonacci();
}
public void fibonacci()
{
int numb1 = 1;
int numb2 = 1;
int temp = 0;
#SuppressWarnings("resource")
Scanner input=new Scanner(System.in);
System.out.println("How Many Terms? (Up To 45)");
int x=input.nextInt();
x=x-2;
System.out.println(numb1);
System.out.println(numb2);
for (int i = 0; i < x; i++)
{
System.out.println(numb1 + numb2 + " ");
temp = numb1;
numb1 = numb2;
numb2 = temp + numb2;
}
}
}
This function return the fibonacci series
/**
* #param startElement
* #param secondElent
* #param length :length of fibonacci series
* #return fibonacciseries : contain the series of fibonacci series
*/
public int[] createFibonacciSeries(int startElement, int secondElent,
int length) {
int fibonacciSeries[] = new int[length];
fibonacciSeries[0] = startElement;
fibonacciSeries[1] = secondElent;
for (int i = 2; i < length; i++) {
fibonacciSeries[i] = fibonacciSeries[i - 1]
+ fibonacciSeries[i - 2];
}
return fibonacciSeries;
}
import java.util.*;
class MyFibonacci {
public static void main(String a[]){
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++){
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++){
System.out.print(feb[i] + " ");
}
}
}
public class FibonacciExercitiu {
public static void main(String[] args) {
int result = fib(6); //here we test the code. Scanner can be implemented.
System.out.println(result);
}
public static int fib(int n) {
int x = 1;
int y = 1;
int z = 1; //this line is only for declaring z as a variable. the real assignment for z is in the for loop.
for (int i = 0; i < n - 2; i++) {
z = x + y;
x = y;
y = z;
}
return z;
}
/*
1. F(0) = 1 (x)
2. F(1) = 1.(y) =>Becomes x for point4
3.(z)F(2) = 2 (z) =>Becomes Y for point4 // becomes X for point 5
4.(z)F(3) = 3 // becomes y for point 5
5.(z)F(4) = 5 ..and so on
*/
}
public static int[] fibonachiSeq(int n)
{
if (n < 0)
return null;
int[] F = new int[n+1];
F[0] = 0;
if (n == 0)
return F;
F[1] = 1;
for (int i = 2; i <= n; i++)
{
F[i] = F[i-1] + F[i-2];
}
return F;
}
Using while loop
class Feb
{
static void Main(string[] args)
{
int fn = 0;
int sn = 1;
int tn = 1;
Console.WriteLine(fn);
Console.WriteLine(sn);
while (true)
{
tn = fn + sn;
if (tn >10)
{
break;
}
Console.WriteLine(tn);
fn = sn;
sn = tn;
}
Console.Read();
}
}
public class Febonacci {
public static void main(String[] args) {
int first =0;
int secend =1;
System.out.print(first+","+secend);
for (int k=1;k<7;k++){
System.out.print(","+(first+secend ));
if(k%2!=0)
first+=secend;
else
secend+=first;
}
}
}
public class FibonacciSeries {
public static void main(String[] args) {
int a=0, c=0, b=1;
for(int i=0; i<10; i++) {
System.out.print(c+" ");
a = c + b;
c = b;
b = a;
}
}
}

Categories

Resources