I want to get the fibonacci sequence entered by the user in array. The task given to me was "Ask the user for 2 integer input which will be taken for first and second array elements of size 10 array."
Here is my code.
int limit = 10;
int[] fib = new int[limit];
fib[0] = 0;
fib[1] = 1;
for (int j = 1; j < 2; j++)
{
System.out.print("Enter number " + "[" + j + "]: ");
num[j] = reader.nextInt();
num[j] = fib[j+1] + fib[j+2];
System.out.println("");
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++ )
{
System.out.print(fib[j] + " ");
System.out.print("");
}
I badly need help for this one, been searching for solution for hours and still don't get it.
I'll just make some corrections to your code and explain them:
int limit = 10;
int[] fib = new int[limit];
// fib[0] = 0;
// fib[1] = 1;
// The two lines above are wrong. Even though the real fibonacci sequence starts
// with 0 and 1, the question asks for the first two terms to come from user
// inputs. Instead, you can initialize them below:
// In your old code, you had "j = 1; j < 2; j++". However, that only loops once.
// So, have your condition to be j <= 2 instead: (I'm assuming that you want 1
// and 2 and not zero-based because it should print out "Enter number [1]:" and
// "Enter number [2]:"
for (int j = 0; j < 2; j++) // Not "j < 2"
{
System.out.print("Enter number " + "[" + j + "]: ");
fib[j] = reader.nextInt(); // not num[j] = ..., it's fib[j] = ...
// num[j] = fib[j+1] + fib[j+2];
// You don't need this ^^^
System.out.println("");
}
// Now you need to fill in the array:
for (int j = 2; j < limit; j++)
{
fib[j] = fib[j - 1] + fib[j - 2];
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++)
{
System.out.print(fib[j] + " ");
System.out.print("");
}
You have a number of mistakes here. Try to answer the following things:
What is the purpose of num variable here? You are using it to take input (num[j] = reader.nextInt();), then you are using it to store the Fibonacci sequence as well (num[j] = fib[j+1] + fib[j+2];)!!!
The first loop is only running one time. Assuming that your calculations are correct (which is not in this case!), it will have values for the first fibonacci number only.
Finally when you are printing the Fibonacci numbers, you are not using the num variable! Why?
Anyway, here is a solution to your problem. But, it will not help you unless you understand the logic behind it and you know which line is doing what!!!
int limit = 10;
int[] fib = new int[limit];
for (int j = 0; j < 2; j++)
{
System.out.print("Enter number " + "[" + j + 1 + "]: ");
fib[j] = reader.nextInt(); // These are the first two fibonacci numbers provided by the user
System.out.println("");
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++ )
{
if( j > 1 ) // You only calculate from the third Fibonacci, as the first two were given by user
{
fib[j] = fib[j-1] + fib[j-2];
}
System.out.print(fib[j] + " ");
System.out.print("");
}
Related
I created a nested while loop as shown in the image, however, after the first full loop is finished, the second while loop does not execute even though the condition inside the second while loop is still true. This could be an issue with System.in, but I tried commenting it out and it still did not loop again. What could be the issue here?
int i = 0;
int j = 0;
int p = 0;
while(i < nStudents) {
p = i+1;
System.out.println("\nStudent " + p + "'s rankings: ");
while(j < nSchools) {
System.out.print("\nSchool " + toArrayList.get(j).getName() + ": ");
String ranking = DisplayMenu.br.readLine();
Array1.add(ranking);
j++;
}
i++;
}
I have also included an image, which shows what exactly happens here. For the second time looping through, it should print out the schools but it does not.
You need to set variable j to 0 after exiting the loop.
int i = 0;
int j = 0;
int p = 0;
int nStudents = 10;
int nSchools = 4;
while (i < nStudents) {
p = i + 1;
System.out.println("\n Student " + p + "'s rankings: ");
while(j<nSchools){
System.out.print("\n School " + j+ " :");
j++;
}
j=0; //// LIKE THIS
i++;
}
For loop can be used as well
int i = 0;
int nSchools = 4;
for(int nStudents = 10; nStudents > i; i++){
System.out.println("\n Student " + i + "'s rankings: ");
for(int j = 0; j < nSchools; j++){
System.out.print("\n School " + j+ " :");
}
i++;
}
The reason why this does not work is that, once the first full loop is finished (like you mentioned), j becomes greater than nStudents because of the increment you wrote (j++;). It never gets set back to 0 or lower than nStudents for the second time it goes back into the while loop.
int i = 0;
int j = 0;
int p = 0;
while(i < nStudents) {
p = i+1;
System.out.println("\nStudent " + p + "'s rankings: ");
while(j < nSchools) {
System.out.print("\nSchool " + toArrayList.get(j).getName() + ": ");
String ranking = DisplayMenu.br.readLine();
Array1.add(ranking);
j++;
}
//Set j less that nSchools here. One example is j = 0;
i++;
}
I'm working on a small game that essentially has piles of coins, and you must take some coins from a pile then the program prints out the resulting piles in the format:
Pile 1: ****
Pile 2: *****
Pile 3: **
I have an array list that store all these values like so:
List<Integer> coins = new ArrayList<>();
[4,5,2]
But I can't figure out how to get it to properly print the *'s.
How can I write this code to print out a * for each value in an element. IE 4 *'s if the element value is 4?
Here is my current method:
static void printGameState(){
for(int i = 0; i <= coins.size()-1; i++){
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j <= coins.indexOf(i); j++){
System.out.print("*");
}
}
}
Instead of using this condition:
j <= coins.indexOf(i);
Use this condition:
j < coins.get(i);
Try it:
for(int i = 0; i <= coins.size()-1; i++) {
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j < coins.get(i); j++) {
System.out.print("*");
}
System.out.println();
}
You'll get:
Pile 1: ****
Pile 2: *****
Pile 3: **
You should be using < instead of <=. Also, you should be able to use get(i) to take the value at index i.
static void printGameState(){
for(int i = 0; i < coins.size(); i++){
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j < coins.get(i); j++){
System.out.print("*");
}
}
}
You could also make it a bit cleaner by forming another method to print * such as:
public void ast(int n){
for(int i=0; i<n; i++){
System.out.print("*");
}
}
Then the contents of printGameState loop would be
int k = i+1;
System.out.print("Pile " + k + ": ");
ast(coins.get(i));
You have to look at the values of the different stacks by accessing the array coins[i] instead of using the number of stacks as stack height:
static void printGameState(){
for(int i = 0; i < coins.size(); i++) {
// Build the coin stack
String coinStack = "";
for(int j = 0; j < coins.get(i); j++) {
coinStack += "*";
}
// And output it
System.out.println("Pile " + (i + 1) + ": " + coinStack);
}
}
import java.util.Scanner;
public class Assign58{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int numintegers, j;
System.out.print("Enter a positive integer: ");
numintegers = keyboard.nextInt();
System.out.print("Now enter " + numintegers + " integers: ");
int[] integers = new int[numintegers];
for (int i=0; i < integers.length; i++){
integers[i] = keyboard.nextInt();
int[] reverse = new int[integers.length];
for (i = 0, j = reverse.length - 1; i < reverse.length; i++, j--){
reverse[j] = integers[i];
}
}
System.out.print("In reverse: ");
for (int i=0; i < integers.length; i++)
System.out.print(integers[i] + " ");
}
}
So if the integers were 3 4 6 2 9, how would I change the following from the code above:
for (int i=0; i < integers.length; i++)
System.out.print(integers[i] + " ");
to make the output come out as:
9 - 2 - 6 - 4 - 3
REMEMBER I need it to come out in reverse order and I want those dashes in between those numbers and there should be no dash after the last number.
I hope someone can help me! Thanks!
Use this code for printing the array in reverse order.
int j = integers.length; //integers is the array in which the values are stored.
for(int k=j-1; k>=0; k--)
System.out.print(integers[k]+"-");
reverse the forloop to get the reverse order
for (int i=integers.length-1; i>=0 i--)
System.out.print(integers[i] + "-");
for (int i = integers.length; i > 0; i--) {
System.out.print(integers[i] + " - ");
}
System.out.print(integers[0]);
This should work
for (int i=0; i < integers.length; i++){
integers[i] = keyboard.nextInt();
int[] reverse = new int[integers.length];
for (i = 0, j = reverse.length - 1; i < reverse.length; i++, j--){
reverse[i] = integers[j]+" ";
}
}
System.out.print(reverse[0]);
for (int i=1; i < integers.length; i++)
System.out.print(" - " + reverse[i]);
the other proposed solutions would print one - too much.
Either you could traverse the Array from the end
for(int i = integers.length-1; i >= 0; i--) {
System.out.print(integers[i] + " ");
}
or you could use a Stack<Integer> to push all entered numbers and pop them in the reverse order.
Stack<Integer> integers = new Stack<Integer>();
for (int i=0; i < numIntegers; i++){
integers.push(keyboard.nextInt());
}
System.out.print("In reverse: ");
while(!integers.isEmpty()) {
System.out.print(integers.pop() + " ");
}
I'm at a loss here.
I have this homework assignment where I have to enable the user to input 10 numbers, place them in an array, and figure out which inputted numbers are unique.
This is my workflow right now: Input number> If number has not been inputted before, store in array; if number has been inputted before, ignore> Display the numbers inputted> Display the unique numbers
ex: Inputting 1 2 3 5 1 2 4 6 would find the unique numbers and show "1 2 3 4 5 6"
So far my code looks like this:
public class HwChapter6 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[] count = new int[10];
int number = 0;
int x = 0;
boolean unique = false;
int length = count.length;
System.out.println("Insert 10 single digit numbers in any order your heart desires:");
for (int i = 0; i < count.length; i++) {
count[i] = input.nextInt();
number = count[i];
for (int j = 0; j < count.length; j++) {
Thanks for the help guys.
Instead of an array of input values, put them in a Set of Integers. Sets, by definition, store only unique values. If you add 3 'foos', there will be only one 'foo' in the set.
// Add this to your top-level loop
Set<Integer> uniqueValues = new TreeSet<Integer>;
uniqueValues.add(number);
// Add this after the loop to write all unique values on one line
for (Integer value : uniqueValues) {
System.out.print(value.toString() + " ");
}
// Now end the line.
System.out.println();
Check the numbers at they are entered, then keep track of which ones are unique by marking the same positions in a second (boolean) array with true if they are unique and false otherwise.
Then, when you print out the unique values, only print the value from each position in numbers[] if that position in uniques[] contains true.
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
boolean[] uniques = new boolean[10];
for(int i = 0; i < 10; i++) {
System.out.println("Please enter a value: \n" + "[" + (i + 1) + "]: ");
numbers[i] = input.nextInt();
uniques[i] = true;
for(int j = 0; j < 10; j++) {
if(numbers[i] == numbers[j] && i != j) {
uniques[i] = false;
}
}
}
System.out.println("\nThe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
System.out.println(numbers[i] + ", ");
}
System.out.println("done.\n\n");
System.out.println("\nThe uniqe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
if(uniques[i]) {
System.out.println(numbers[i] + ", ");
}
}
System.out.println("done.\n\n");
Store all numbers in an array.
For each stored number: check if number was inserted before and save that in a boolean array.
Print all numbers that are not marked in the boolean array.
java.util.Scanner input = new java.util.Scanner(System.in);
int[] numbers = new int[10];
boolean[] usedBefore = new boolean[10];
// Insert all numbers
for (int i = 0; i < numbers.length; i++) {
// Read number from console
numbers[i] = input.nextInt();
// Check if number was inserted before
usedBefore[i] = false;
for(int k = 0; k < i; k++) {
if(numbers[k] == numbers[i]) {
usedBefore[i] = true;
break;
}
}
}
// Print all numbers that were not inserted before
for(int j = 0; j < numbers.length; j++) {
if(!usedBefore[i]) {
System.out.print(String.valueOf(numbers[j])+" ");
}
}
The fastest and most concise and efficient way is to destructively parse the array for uniques using its first number as a magic value, after all other operations on it are complete:
Scanner input = new Scanner(System.in);
int magic = 0;
int[] numbers = new int[10];
for(int i = 0; i < 10; i++) {
System.out.println("Please enter a value: \n" + "[" + (i + 1) + "]: ");
numbers[i] = input.nextInt();
}
System.out.println("\nThe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
System.out.println(numbers[i] + ", ");
}
System.out.println("done.\n\n");
System.out.println("The unique numbers are: ");
magic = numbers[0];
System.out.println(magic + ", ");
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(numbers[i] == numbers[j] && j != i) {
numbers[j] = magic;
}
}
if(numbers[i] != magic) {
System.out.println(numbers[i] + ", ");
}
}
System.out.println("done.\n\n");
Yes, I have two answers - this one is significantly different from the other one, and is better, though it is much more difficult for beginners to understand. Both solutions are valid, however.
How do I add each element into an arrayqueue? Basically, if I have an array of queues where each index is an arrayqueue that holds the 1s, 10s, 100s, etc. place of a corresponding 6 digit number in another index of array a. For example, if a[1] is 123456 then how can I make the code below hold arr[1] 654321? I've posted a question similar to this before but I'm just trying to get this right.
public static void radixSort(int[] a) {
//Create an array of 10 empty array queues
Queue[] arr = new Queue[a.length];
for (int i = 0; i < arr.length; i++)
arr[i] = new ArrayQueue();
for (int place = 1; place <= 100000; place *= 10) {
for (int i = 0; i < a.length; i++) {
arr[i].add(selectDigit(a[i],place));
// System.out.println("i: " + i + " a[i]: " + a[i] + " place: " + place + " digit: " + selectDigit(a[i],place));
}
}
// for (int i = 0; i < arr.length; i++)
// System.out.print(arr[i].remove()+ " ");
//for (int j = 0; j < arr.length; j++)
// a[j] = (Integer) arr[j].remove();
}
This tutorial might help:
http://www.sourcecodesworld.com/articles/java/java-data-structures/Radix_sort.asp
It seems a good walk through.