My code requires me to create an array (from user input), display it backwards, and find the sum of each number. So far I have been able to accomplish all requirements. However, if the array is more than 8 numbers, then when it is displayed the program must create a new line every 8th number. I'm having difficulty accomplishing this goal. Here is my code so far:
import java.util.Scanner;
public class arrayCreator {
public static void main(String[] args) {
int length;
double sumArray = 0;
Scanner input = new Scanner(System.in);
System.out.print("How many elements in the array? ");
length = input.nextInt();
}
for(int j = currentArray.length-1; j >= 0; j-- )
{
System.out.printf("%.3f \t", currentArray[j]);
if(currentArray.length - 8 == j) // here is where I'm having the problem
{
System.out.print("\n");
}
input.close();
}
}
What should go inside of the if statement in order to create a new line each time 8 inputs are displayed?
This is what output should look like :
How many elements in the array? 20
Please enter the next value 1
Please enter the next value 2
Please enter the next value 3
Please enter the next value 4
Please enter the next value 5
Please enter the next value 6
Please enter the next value 7
Please enter the next value 8
Please enter the next value 9
Please enter the next value 10
Please enter the next value 11
Please enter the next value 12
Please enter the next value 13
Please enter the next value 14
Please enter the next value 15
Please enter the next value 16
Please enter the next value 17
Please enter the next value 18
Please enter the next value 19
Please enter the next value 20
20.000 19.000 18.000 17.000 16.000 15.000 14.000 13.000
12.000 11.000 10.000 9.000 8.000 7.000 6.000 5.000
4.000 3.000 2.000 1.000
The Sum of the array's elements is : 210.000
The other answer isn't working correctly because you're backing up through the list from the end back to the beginning, but the mod operator causes line breaks as if you were moving from the beginning to the end. However, the idea of using the modulo operator is definitely correct. Do this in your if statement:
if((length - j) % 8 == 0) {
System.out.print("\n");
}
Usually when you want to do something every n times, you want to use modulo division: %.
Change this
if(currentArray.length - 8 == j) // here is where I'm having the problem
{
System.out.print("\n");
}
To this
if (j % 8 == 0) // here is where I'm having the problem
{
System.out.print("\n");
}
Related
I have what I thought was a very basic code example, but I can't figure out why the code never completes. It seems to stay stuck in a loop. This very simple code is supposed to declare and initialize a jagged array with the first row having 4 columns and the second row having 3 columns. The code asks the user for 7 integers and prints out the result to the screen. All of that works, but it doesn't break out of the loop unless I manually break out of it. If the manual break is used, the correct output is not achieved.
public class TestCode {
public static void main(String[] args) {
//Create new scanner object
Scanner userInput = new Scanner(System.in);
//Declare two dimentional array
int[][] num2d = new int[4][3];
//Declare variables
int i;
int j;
//Print to screen asking for user input
System.out.print("Enter seven numbers: ");
//Loop through array and print the result
for (i = 0; i < num2d.length; i++) {
for (j = 0; j < num2d[i].length; j++) {
num2d[i][j] = userInput.nextInt();
System.out.println(num2d[i][j]);
//break;
}
}
}
}
When I run this code with the break commented out, I get this result, but I have to manually stop it from running.
run:
Enter seven numbers: 1 2 3 4 1 2 3
1
2
3
4
1
2
3
When I put the break in, this is what I get.
run:
Enter seven numbers: 1 2 3 4 1 2 3
1
2
3
4
BUILD SUCCESSFUL (total time: 4 seconds)
What's going on? Why can I get the correct result with the "build successful" message without using the break?
Your code doesn't loop forever: it loops 12 times, because you have declared a 4x3 array - i.e. an array sized 4 where each of the elements is an array of 3 ints.
Instead, I think you want something like this:
int[][] num2d = {new int[4], new int[3]};
your loop runs on the "columns" of the 2d array which is 4 times and for each "column" it runs on its length which is 3. 4 times 3 is 12, and you only enter 7 numbers. the console is always waiting your input.
Problem
Turtles live long (and prosper). Turtles on the island Zanzibar are
even immortal. Furthermore, they are asexual, and every year they give
birth to at most one child. Apart from that, they do nothing. They
never leave their tropical paradise.
Zanzi Bar, the first turtle on Zanzibar, has one further activity: it
keeps track of the number of turtles on the island. Every New Year’s
Day it counts the turtles, and writes the total number in a small
booklet. After many years this booklet contains a non-decreasing
sequence of integers, starting with one or more ones. (After emerging
from its egg on Zanzibar’s beautiful beach, it took Zanzi some time to
start a family on its own.)
One day Zanzi realizes that it could also be the case that turtles
from abroad come to Zanzibar, by boat or plane. Now it wonders how
many of the inhabitants were not born on Zanzibar. Unfortunately, it
can only derive a lower bound from the sequence in the booklet.
Indeed, if the number of turtles in a year is more than twice as big
as the year before, the difference must be fully explained by import.
As soon as Zanzibar has 1000000 turtles, the island is totally covered
with turtles, and both reproduction and import come to a halt. Please
help Zanzi! Write a program that computes the lower bound of import
turtles, given a sequence, as described above.
Input
The input starts with a line containing an integer T(1≤T≤13), the
number of test cases. Then for each test case:
One line containing a sequence of space-separated, positive integers
(≤1000000), non-decreasing, starting with one or more ones. For
convenience, a single space and a 0 are appended to the end of the
sequence.
Output
For each test case, output a line containing a single integer: the
lower bound for the number of turtles not born on Zanzibar.
See question and sample input and output here
My approach
public Zanzibar() {
Scanner scan = new Scanner(System.in);
int iterations = scan.nextInt();
for (int i = 0; i < iterations; i++) {
int previous = -1;
int current = -1;
int lower = 0;
while (true) {
if (current != -1)
previous = current;
current = scan.nextInt();
if (current == 0)
break;
if (current > 2 * previous && previous != -1)
lower += current - previous;
}
System.out.println(lower);
}
}
I think I am understanding the problem wrong. Am I supposed to keep adding to the lower bound or should I find the biggest difference between two years? Also I don't understand how input 1 100 0 produces output 98 (from the link). Shouldn't it be 99?
This is what the problem setter wants us to understand:
The initial 1 for every test case means that the initial population on the island is always 1
So for an input like 1 1 1 0, it means that:
The initial population is 1. Then at the start of the 2nd year, the population is still 1. At the start of the 3rd year, the population is still 1.
As for your doubt about the input: 1 28 0, it means that:
At the start of the 2nd year, the population is 28, whereas the maximum that could have been is 2, as the only turtle could have given birth to one more turtle at max. So, it means that clearly, at least (28-2) = 26 turtles migrated!!!
Hope it helps...
Edit: This is the algorithm:
For every line of test case do the following:
Set initial to 1, migrated to 0
Start reading from the second number in the line, until we encounter a 0:
If the current number is greater than 2*initial: migrated = migrated + (current - 2*initial)
Else: do nothing
Set initial to current
Print migrated
Edit-2:
Here is the JAVA implementation:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int iterations = scan.nextInt();
int i = 0;
int len,x;
int j,initial;
long migrated;
int arr[] = new int[1000005];
while(i<iterations)
{
len = 0;
while(true)
{
x = scan.nextInt();
if(x==0)
break;
arr[len++] = x;
}
initial = arr[0];
migrated = 0;
j = 1;
while(j<len)
{
if(arr[j]-(2*initial)>0)
{
migrated += arr[j]-(2*initial);
}
initial = arr[j];
j++;
}
System.out.println(migrated);
i++;
}
}
}
Input:
3
1 100 0
1 1 1 2 2 4 8 8 9 0
1 28 72 0
Output:
98
0
42
In this lab, you will be creating a program that merges two arrays of positive (greater than 0) integers. Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter zero or a negative number. You should disregard any non-positive numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
After the two arrays have been input, your program must check to make sure the elements of each array have been entered in order. If an out of order element is found, print the message “ERROR: Array not in correct order”.
Your task is to merge the two input arrays into a new array, with all elements in order, lowest to highest. Print out each of the original arrays entered, followed by the merged array.
Please note that your program must output the arrays with exactly one space between each of the numbers.
Sample Run 1:
Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit
3
3
5
6
8
9
-1
Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit
3
4
5
6
-5
First Array:
3 3 5 6 8 9
Second Array:
3 4 5 6
Merged Array:
3 3 3 4 5 5 6 6 8 9
My code was:
import java.util.Scanner;
class Main{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int one1=0;
int two1=0;
int a = 0;
int b = 0;
int flag = 0;
int[]one=new int[10000];
int[]two=new int[10000];
System.out.println("Enter the values for the first array, up to 10000 values, enter a negative number to quit");
while (a==0){
int first = scan.nextInt();
if (first<=0) a++;
else{
one[one1]=first;
one1++;
}
}
System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");
while (b==0){
int second = scan.nextInt();
if (second<=0) b++;
else{
two[two1]=second;
two1++;
}
}
System.out.println("First Array:");
for (int i = 0 ; i < one1 ; i++){
System.out.print(one[i]+" ");
}
for (int i = 0 ; i < one.length-1 ; i++){
if (one[i]>one[i+1]) flag++;
}
System.out.println("Second Array:");
for (int i = 0 ; i < two1 ; i++){
System.out.print(two[i]+" ");
}
for (int i = 0 ; i < two.length-1 ; i++){
if (two[i]>two[i+1]) flag++;
}
int[]combo = new int[one.length+two.length];
for (int i = 0 ; i < combo.length-1 ; i+=2){
combo[i]=one[i];
combo[i+1]=two[i];
}
if (flag>0) System.out.println("ERROR: Array not in correct order");
else{
for (int i = 0 ; i < combo.length; i++){
System.out.print(combo[i]+" ");
}
}
}
}
This code keeps giving me runtime error- what am I doing wrong?
I am sorry, your merge algortithm is all wrong. You create an array combo of length one.length + two.length, that is, 20000 (I think one1 + two1 should suffice). Then you try to fill the new array by looping through it two elements at a time:
for (int i = 0; i < combo.length - 1; i += 2) {
So i is 0, 2, 4 etc. through 19998 (the last even number before 20000). Except when it gets 10000, you try to pick out one[i], that is one[10000], which is outside the one array. This gives the ArrayIndexOutOfBoundsException.
How I found out? The stack trace gives a line number. The line it mentions is
combo[i] = one[i];
It also mentioned the number 10000, so I knew this was the value of i at this point.
I think that what you were trying to do, was fill elements 0 from one and two into elements 0 and 1 of combo, I think it works so far. Then you wanted to fill element 1 from each array into elements 2 and 3; but since you have added 2 to i, you fill in element 2 from each source array and never use element 1 from them. Or any element from odd indices.
Before you mend that problem, allow me to mention one more thing. I think with your logic, input arrays 2 5 and 11 30 will come out as 2 11 5 30. This doesn’t fulfil “with all elements in order, lowest to highest”. So I think you should think your algorithm over.
the code exist many logic error,
as for Runtime Error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10000 at..
the problem is here:
for (int i = 0 ; i < combo.length-1 ; i+=2){
combo[i]=one[i];
combo[i+1]=two[i];
}
the i from 0 to 19999 and the index of a,b is from 0 to 9999, and the code exist other simple logic problem. Please check it again.
Homework questions are very frowned upon, but still, Java is a relatively easy language. If your program is throwing a RuntimeException, you just have to read what the problem is.
In this case, it seems a loop iterates more times than it should, and you are accessing other memory space. Give it a few reads with the info provided by the error trace in mind.
I am writing a Java program that let user input a number, then the program combine 5,8,and 9 to get user's input number.
I want to achieve following samples:
1.
what is your number that you what to find the combination?
8
your number has 1 eights
2.
what is your number that you what to find the combination?
13
your number has 1 fives and 1 eights
3.
what is your number that you what to find the combination?
11
invalid number
Here are codes that I wrote:
import java.util.Scanner;
class combine {
public static void main (String[] args){
System.out.println("what is your number that you what to find the combination? ");
Scanner scan = new Scanner(System.in);
if (num < 5){
System.out.println("invalid number");
System.exit(0);
}
//Begin Looping
for (int g=0; g<=1000000;g++){
//Find the the number left after minus g*5
int left = num - g*5;
//Check the combination of 5 and 8
if (left%8 == 0){
System.out.format("your number has %d fives and %d eights\n",g,left/8);
System.exit(0);
}
//Check the combination of 5 and 9
if (left%9 == 0){
System.out.format("your number has %d fives and %d nines\n",g,left/9);
System.exit(0);
}
//Check the combination of 8 and 9
while (false){ //This while loop doesn't work. It fails compile.
int left2 = nuggets_num - g*8;
try{
if (left%8 == 0){
System.out.format("your number has %d eights and %d nines\n",g,left/8);
System.exit(0);
}
if (left%8 != 0){
System.out.println("invalid number");
}
}
}
}
System.out.println("invalid number");
}
}
//I am a beginner and I know that reading my codes might be painful, sorry about that:(
As I mentioned, my while loop doesn't work. So my program could't find the combination of "17", which should be 1 eight and 1 nine. How to fix it?
Also, my program's outputs are not clean enough. For example, if user input "8", my program would output"your number has 0 fives and 1 eights". How to add checkers to avoid these conditions? Like output "your number has 1 eights" instead of the former output.
You are using while(false) which means that this loop will never be executed. Java compiler is intelligent enough to stop you to compile something that it knows will not run.
As for your logic, when you deduct maximum multiple of 5's from some number (which means that you are doing modulus by 5), the remainder will never be more than 4! So, you should do something like below:
Divide the input by 9. This will give you the count of 9's in that input.
Modulus the input by 9. This will give you the remainder, which will be less than or equal to 8.
Perform step 1 and 2 with 8 and 5, respectively.
Use the output of above algorithm to format your output string.
You have a basic misunderstanding of the division and modulus operators.
You're trying to divide a number by a specific digit to "get rid" of it, but that only works when you're diving by multiplications of 10 (assuming you're working in the decimal system).
For example, (1985 / 10) = 198, but 888 / 8 does not equal 88!
The same goes for the % operator - (350 % 3) will not return 50! It's actually equal to 2
I am trying to find a way to count down from the int that is input by a user and then add each second value as i count down to 0
for example.
{user inputs 10
program counts down 8,6,4,2,0
then add 10 + 8 + 6 + 4 +2 +0= 30
}
how can I do this using a nested for loop
so far I have only been able to take user input, and count down by 2 each time. I get to 0 but have no way of adding every second value.
My code:
so far, it just counts to 0
public class Week5b {
static Scanner userVal = new Scanner (System.in);
public static void main(String[] args) {
//printTable();
reverseAddSkip();
public static void reverseAddSkip(){
System.out.println("Please enter an integer");
for (int i = userVal.nextInt(); i >=0; i-=2){
System.out.println(i) ;
}/* this creates a loop where the variable i is equal to user input;
the condition for the loop to continue is whether the input is larger or equal to 0; the update part of the loop takes 2 away each time, as if it were -- (which takes away one each time) */
}
}
How would I write that out mathematically?
Adding the sum of i-=2 to the original value of i.
You type 11 , it counts 9 7 5 3 1 , then adds 11 9 7 5 3 1. and give you the sum.
don't know how to sum every 2 numbers decrementing by 2, from a user value.
You input put 50, it counts down by 2 to 0
you put 51 it counts down by 2 to 0
but I haven't found away to sum all then numbers that were generated before getting to 0
:/
NoGlitching,
You need to look at the control flow of your program - which is to say, the path it takes upon execution.
You should also look at using more variables.
I'll give you the pseudocode I would use, because I think it's important for you to be able to write the code yourself:
Make a new integer called OriginalInput.
Make a new integer called RunningTotal.
Set RunningTotal to 0.
Store the user's input in OriginalInput.
Loop through OriginalInput.
Print the current OriginalInput.
Add the current OriginalInput to RunningTotal.
When the loop is finished:
Print RunningTotal.
I hope this helps.
EDIT:
// First you equalize j with i
input = userVal.nextInt();
j = i; // Put the user input in j first. for instance 11.
for (int i = input; i >=0; i-=2)
{
if (i >= 0) // If i is not below 0
{
j += i; // Add to j what i has now (everytime -2)
// put a system out print here to show what was added
// J starts as 11 and adds 9,7,5,3,1 then nothing. So it ends as 36.
}
}
// outside the For loop after it ends but INSIDE your method, you get the sum from the variable j!