Fibonacci sequence with arrays - java

I have the task of writing a program using the fibonacci sequence and putting them into arrays. It works by getting user input ( how many numbers in the sequence the user wants to print out) and then it implements that into an array and prints out the sequence with the number of 'numbers' the user inputed.
As I missed out on 2 weeks of class I looked online on how to write this program and found a video which the following code was written. So I do not take credit for the following code, I'm merely using it as an example.
Anyway here's the code:
public class Fibonacci
{
public static void main(String[] args)
{
int numToPrint;
//how many numbers to print out
Scanner scan = new Scanner(System.in);
System.out.println("Hvað viltu prenta út margar tölur úr Fibonacci röðinni?");
numToPrint = scan.nextInt();
scan.close();
//prints out the first 2 numbers
int nuverandiT = 1;
int lokaT = 0;
System.out.println(lokaT);
System.out.println(nuverandiT);
//prints out the rest of the sequence
int lokaLokaT;
for(int i = 2; i < numToPrint; i++)
{
lokaLokaT = lokaT;
lokaT = nuverandiT;
nuverandiT = lokaLokaT + lokaT;
System.out.println(nuverandiT);
}
}
}
Now this prints out the fibonacci sequence with input from the user, but I'm not quite sure how to make it print out into an array. Do any of you guys know how to do this?

You have to create an array, for example:
int[] simpleArray;
simpleArray = new int[numToPrint];
At the place of
System.out.println(lokaT);
System.out.println(nuverandiT);
Put:
simpleArray[0] = lokaT;
simpleArray[1] = nuverandiT;
And inside your loop, you put instead this:
System.out.println(nuverandiT);
This:
simpleArray[i] = nuverandiT;

I'm guessing when you say 'print out into an array' you really mean you just want to store the values in an array. In that case,
Before your for loop:
int[] array = new int[numToPrint];
And inside your for loop:
array[i-2] = nuverandiT;
If you wanted to print the numbers once they've been stored in an array, you would probably want to loop through it and print in the same fashion, accessing the elements by index. For more information, the java documentation is very good. I recommend reading up on arrays and counted loops.

Related

how to print Scanner element using parallel arrays in java?

I am new to learning about parallel arrays and want to know how to effectively print content/elements using parallel array only, I tried but couldn't get it to work and function the way I want.
The task is: The program inputs an integer from the user representing how many peoples’ information will be entered. Then, the program inputs the information one person at a time (name first, then age), storing this information in two related arrays.
Next, the program inputs an integer representing the person on the list whose information should be displayed (to get information for the first person, the user would enter ‘1’). The program makes a statement about the person’s name and age.
Although I got the name and age to work until the integer the user inputs, but after that I am not sure how to do
Sample input:
4
Vince
5
Alexina
8
Ahmed
4
Jorge
2
2 // I am confused about this part, how would I make it so that it prints the desired name,
//for example with this input, it should print:
Sample output:
Alexina is 8 years old
My code:
import java.util.Scanner;
class Example {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < num.length; x++){
String[] name = {keyboard.next()};
int[] age = {keyboard.nextInt()};
}
int num2 = keyboard.nextInt();
System.out.println(); // what would I say here?
}
}
You need to rewrite your code so your arrays aren't being assigned within the loop. You want to add values to the arrays, not reset them each time, and you want to be able to access them afterwards. Below is a modified version of your code:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
keyboard.nextLine(); //you also need to consume the newline character(s)
String[] name = new String[num]; //declare the arrays outside the loop
int[] age = new int[num];
for (int x = 0; x < num; x++){
name[x] = keyboard.nextLine(); //add a value instead of resetting the array
age[x] = keyboard.nextInt();
keyboard.nextLine(); //again, consume the newline character(s) every time you call nextInt()
}
int num2 = keyboard.nextInt() - 1; //subtract one (array indices start at 0)
System.out.println(name[num2] + " is " + age[num2] + " years old"); //construct your string with your now-visible arrays
}
As I think you have to think about the local and global variable usage in java.In brief,
Local variables can only use within the method or block, Local variable is available only to method or block in which it is declared.
For example:
{
int y[]=new Int[4];
}
this y array can be accessed within the block only.
Global Variable has to be declared anywhere in the class body but not inside any method or block. If a variable is declared as global, it can be used anywhere in the class.
In your code you try to create arrays and use them out of the For loop. But your arrays are valid only inside the For loop. After every loop runs all info is lost.there will be new array creation for every iteration of For loop.
therefore, In order to access and save the information you have to declare your arrays before the For loop and access and store data using iteration number as the index. finally, to print the data you gathered, you have to scan new input as integer variable.then you can access your arrays as you wanted.
//For example
int [] age=new int[4]; //global -Can access inside or outside the For loop
int[] numbers = new int[keyboard.nextInt()];
for (int x = 0; x < 4; x++){
age[x] = keyboard.nextInt(); //Local
}
int num2 = keyboard.nextInt();
System.out.println(age[num2]); // Here you have to access global arrays using num2 num2
}
}

Save Integers with the Scanner class

I have a quick question about the Scanner class.
I had an idea to make a simple program that starts to count all the numbers I write in, but if it goes over a limit it should stop.
This is not the problem....
The problem is that the FIRST number you write in should be the number that tells the program how many numbers it will be counting.
For an example.
When the program starts, I will write in for example :
3
100
234
546
Sum: 880.
and the output should be the sum of 100+234+546.
The number 3 in the beginning just told the program that it is 3 numbers that it should read. I don't understand how to make the first number the number that tells the program how many numbers it should be in the input before it starts to count.
If you are using Java 8, you can do something like this:
Scanner scan = new Scanner(System.in);
int N = scan.nextInt(); //First number is the count of numbers
//line below loops for you and sums at the end
int sum = IntStream.range(0, N).map(i -> scan.nextInt()).sum();
use this code
void yourMethod()
{
int sum=0;
Scanner scan = new Scanner(System.in);
int conut=scan.next();
for(int i=0;i<count;i++)
{
sum=sum+scan.next();
}
}
Store the first number in a variable called counter or similar, and then execute a loop (for, while) for counter times, in each iteration you will read the next number and sum them. The algorithm seems very straightforward to create code from it.
How about:
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
while(count>0){
//your logic
count--;
}

Increase Array Size Based on Total Numbers Entered

I have an issue for creating an array based on the total amount of numbers entered into the array.
Essentially the program is expected to work as the following: the user is prompted for n numbers to enter into an array. So until the user types '000' as their input, the user will be prompted for a new number.
Note: for this array, I do not want the user to input the amount of numbers they want to enter for the array size. Instead, I want the user to continue inputting random numbers until '000' has been inputted, then, the total amount of numbers that has been entered into the array, is the size of such array.
For example: this would work if we have int array[] = {1, 2, 4, 6}, this will automatically set array size to 4, without actually explicitly declaring the array size as 4 elements. Similarly, with my code, I want it where the numbers that the user enters is added to the array, and then the array size is automatically given from the amount of numbers the user has entered like above.
It is important to note that we do not know the length of the array until the user has entered all n numbers.
I have attempted a skeleton, but it returns a cannot find symbol error:
Code:
//Array Code
import java.util.*;
class setArray {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int stopInput = 000;
int number;
System.out.print("Enter a number: ");
number = input.nextInt();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
int array[] = {number};
}
System.out.print("Array size: " + array.length);
} // Main brace
} // Class brace
setArray.java:19: error: cannot find symbol
System.out.print("Array Size: " + array.length);
symbol: variable array
location: class setArray
1 error
You have a few errors here. The first is understanding why you get your immediate error. The variable array is declared within the scope of the while loop. It can not be seen outside of this loop. That is why the compiler is complaining.
The second is that the size of the array (if declared outside of the loop) will always be 1. From my understanding of what you have written as an attempt to solve the problem you have describe shows that you are not tackling the problem correctly.
While you don't known the the final length of the array to be entered; you do need to store the values entered (my inference) to populate the final array. To store the value entered by the user you need a list that will grow with the input.
List<Integer> values = new ArrayList<>();
while (number != stopInput) {
System.out.print("Enter a number: ");
values.add(Integer.valueOf(input.nextInt()));
}
Integer[] array = values.toArray(new Integer[values.size()]);
Firstly, the compilation error is because the array variable is not visible from the System.out.println line. This is because it's declared inside the while loop, so is only visible inside the while loop.
To make it visible to the whole method, declare it before the while loop.
Secondly, arrays cannot be resized. You declare an array to be a certain size, and you cannot add or remove elements.
My suggestion would be to use an ArrayList. Declare one before your loop, and add the new number inside the loop. After the loop, the size should be how many numbers were entered.
Finally, there's no difference between 000 and 0. Is 0 a valid input number?
You can use
List<Integer> array=new ArrayList<Integer>();
while(number != stopInput) {
System.out.print("Enter a number: ");
number = input.nextInt();
array.add(number);
}
This sounds like a job for java.util.ArrayList - this is the array that doesn't have a fixed size and is growing as you add values to it automatically under the covers.
The error is caused because you are creating the array only within the scope of the while loop. You need to create it outside the loop. Secondly, standard arrays are not dynamic, so you would need to either set the size and increase it as needed, or just simply use an ArrayList.
Psuedo:
ArrayList<Integer> list = new ArrayList<Integer>()
...
while(not stop number)
list.add(number)
...
print(list.size())
If you really want to use an Array, here is how you can do it
public static void main(String[] args){
STOP_ENTRY = "000";
scan = new Scanner(System.in);
entry = "";
while(true){
System.out.print("Enter #: ");
String tempS = scan.nextLine();
if(tempS.equals(STOP_ENTRY)) break;
else entry += tempS + ":";
}
String[] split = entry.split(":");
int[] intArray = new int[split.length];
System.out.println("Length of created intArray = " + intArray.length); //length of created array
for(int i = 0; i < intArray.length; i++){
intArray[i] = Integer.parseInt(split[i]);
System.out.println("intArray[" + i + "] => " + String.valueOf(intArray[i]));
}
}
I would recommend an ArrayList, as it dynamically changes is size when you add an element, but do whatever you'd like.
An important note, this does not handle any malicious entry that you might not want (characters, symbols), and will error if they are entered, something you can easily add if you need

Program Output Problems (Java)

I was given an assignment to write a program which will accept any number of input data until 999 has been read. Then the program should type out total number of zero's and various other requests, but the problem is I don't know the output command to tell it to read the number of zeros. All I have so far is
import java.util.Scanner;
public class MidtermI {
public static void main(String args[]) {
Scanner console = new Scanner(System.in);
int numbers = console.nextInt();
and then from there I'm lost.
Break it down into small steps, and check that each step works before going further:
The first thing you need to sort out is to be able to read multiple inputs, by looping. Your current code only reads a single number from the Scanner.
Next, you need to check for the special value 999, and stop looping when that is received.
When you have got that working, figure out how to count the zeros - either by counting them as they arrive, or collecting all the values and counting them afterwards.
You can then print out the required results using System.out.println() - but you'll probably want to use that for testing and debugging your code as you go along, anyway.
Create ArrayList to hold the zero values the print its size.
ArrayList<Integer> zeroValues = new ArrayList<Integer>();
Then loop n time to input n numbers:
for(int i=0; i<999; i++) {
int numbers = console.nextInt();
if(number == 0) {
zeroValues.add(number);
}
}
Then you could print the total of zero's values like:
System.out.println(zeroValues.size());

How to make it so only ints from the array can be chosen? Also how to find biggest integer from integers chosen?

I am making a program that prompts the user for 3 integers and prints out the biggest one chosen. I am stuck with 2 problems at the moment. I would like to know how I can make the program so that the user can only choose integers from the array. I would also like to know how to find and print out the biggest integer from the ones that the user chose. I'm quite new to programming so all feedback is appreciated.
Thanks!
import java.util.Scanner;
public class Lab14C // name of class file
{
public static void main(String [] args)
{
int[] array = {0,1,2,3,4,5,6,7,8,9};
for(int i=0; i<array.length; i++)
{
System.out.print(array[i] + " ");
}
System.out.println("\n");
Scanner array1 = new Scanner(System.in);
System.out.println("What is your first integer? ");
double array11 = array1.nextInt();
Scanner array2 = new Scanner(System.in);
System.out.println("What is your second integer? ");
double array22 = array2.nextInt();
Scanner array3 = new Scanner(System.in);
System.out.println("What is your third integer? ");
double array33 = array3.nextInt();
System.out.println("\n");
}
}
I don't think there is a way to force a user to input an element. Few things you could do is :
Tell the user he has to select a number in a particular range.
Keep the input statement in a loop. If the entered element exists in array , go ahead. Else tell the user to enter again.
Printing the biggest integer can be done using Math.max(double,double) function. For three elements you can try System.out.println("Max of three is "+Math.max(array11,Math.max(array22,array33)))
You can do it yourself if you want instead of built in function like:
if(array1>array2&&array1>array3)
//print max as array1
else if(array2>array1&&array2>array3)
//print max as array2
else //print array3 as max
Also change your element types to int as you are reading integer.
1) There is no need to create a new Scanner all the time.
Just create one Scanner (which I would just call input or scanner or something that makes sense).
2) If you're reading int's why are you storing them in doubles?
3) To check for a certain condition you use if(*condition*) { /*do something */ }. So if you want to check if x is smaller than y you do if(x < y) { /* do something */ }. (In your case you'll want to check if current input is greater than biggest input and if so set the biggest input to current input.)
4) For a sorted array you can use Arrays.binarySearch(array, elementToSearch) which will return the index of the element when found, or a negative number if not found (the negative number is (-(insertionPoint)-1)). (So you can check if the number entered by the user is in the array and keep asking for a new number if is not.)
1) How I can make the program so that the user can only choose integers from the array.?
You are declaring array variable as int[] so it stores only integer values. Whenever you retrives the value from this array, it returns int value only so you don't have to worry about it.
2)how to find and print out the biggest integer from the ones that the user chose.?
To find the maximum or minimum from a set of values, Java provide a function name Math#max(). You can use it like this :
int maxValue = Math.max(Math.max(array11,array22),array33);
Here is the doc for Math library.

Categories