This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I need replace the while loop with a for loop. Make sure it produces the same output, if 6 is given as a parameter: java PowersOfTwo 6.
But my answer cannot run well. Always outputs:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Below is the previous example:
public class PowersOfTwo {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // last power of two to print
int i = 0; // loop control counter
int v = 1; // current power of two
while (i <= N) {
System.out.println(i + " " + v);
i = i + 1;
v = 2 * v;
}
}
}
Below is my answer:
public class PowersOfTwo {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // last power of two to print
int v = 1; // current power of two
for (int i = 0; i <= N; i ++) {
System.out.println(i + " " + v);
i = i + 1;
v = 2 * v;
}
}
}
I strongly suggest you to use a tool like this - it helps in the majority of cases similar to yours.
java.lang.ArrayIndexOutOfBoundsException: 0 occurs when trying to iterate an empty array - so check if you pass the params into app properly and didn't forget 6 here:
java PowersOfTwo 6
Also I suppose you should remove the i = i + 1; line.
You added i = i + 1 inside the loop which is not necessary here since its already done by the for loop
You can fix it this way:
public class PowersOfTwo {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // last power of two to print
int v = 1; // current power of two
for (int i = 0; i <= N; i ++) {
System.out.println(i + " " + v);
//i = i + 1; // you dont need this line
v = 2 * v;
}
}
}
Or this way:
public class PowersOfTwo {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // last power of two to print
int v = 1; // current power of two
for (int i = 0; i <= N;) { //no need to i++
System.out.println(i + " " + v);
i = i + 1;
v = 2 * v;
}
}
}
You can use , to separate multiple variables (and increment commands). So you could do something like,
for (int i = 0, v = 1; i <= N; i++, v *= 2) {
System.out.println(i + " " + v);
}
Finally, when you run the program, pass the value N.
java -cp . PowersOfTwo 4
Which outputs
0 1
1 2
2 4
3 8
4 16
For the same result you could eliminate v, and bitshift 1 left by i like
for (int i = 0; i <= N; i++) {
System.out.println(i + " " + (1 << i));
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need help getting my code output to look like the image below and I am not sure what I am doing wrong and I need to have my code output indented and cant remember how to indent it.
Here is my code currently:
// Fig. 18.3: FactorialCalculator.java
// Recursive factorial method.
public class Assignment_6_1
{
// recursive method factorial (assumes its parameter is >= 0
static StringBuilder s = new StringBuilder();
public static long factorial(long number)
{
if (number == 0) // test for base case
{
return 1;
} else {// recursion step
if (s.length() == 0) {
s.append(number).append("*").append(number - 1);
} else {
for (int i = 0; i < s.length(); i++) {
}
System.out.println(number + " * " + (number - 1) + "!");
s.append("*").append(number).append("*").append(number - 1);
}
return number * factorial(number - 1);
}
}
// output factorials for values 0-21
public static void main(String[] args) {
System.out.println("Hannah Coffey - Lab 6");
// calculate the factorials of 0 through 20
for (int counter = 0; counter < 25; counter++) {
s = new StringBuilder();
System.out.println(counter + "!");
System.out.printf("%d! = %d%n", counter, factorial(counter));
}
}
} // end class FactorialCalculator
Here is what I need it to look like and not sure what I am doing wrong:
Any Help would be greatly appreciated.
My program currently looks like this:
enter image description here
You can pad a String using String.format like this :
String.format("%10s", "foo");
It will create a left padding of 7 spaces 7 + foo.length = 10;
Now, we can render that dynamic like :
public static String padding( int i ) {
return i == 0 ? "" : String.format( "%" + i + "s", "" );
}
Just pass the number of spaces and let the formatter do the job.
for(int i = 5; i >= 0; --i){
System.out.println(padding(i) + "i");
}
Output :
5
4
3
2
1
0
public static long factorial(long number){
if (number == 0) // test for base case
{
return 1;
} else {// recursion step
if (s.length() == 0) {
s.append(number).append("*").append(number - 1);
} else {
String spaces = "";
for (int i = 0; i < number; i++) {
spaces = spaces+" ";
}
if(number==1)
System.out.println(" Base Case: 1");
else {
System.out.println(spaces + "Recursive call:" + number + " * fact(" + (number - 1) + ")");
s.append("*").append(number).append("*").append(number - 1);
}
}
return number * factorial(number - 1);
}
}
public static void main(String[] args) {
System.out.println("Hannah Coffey - Lab 6");
// calculate the factorials of 0 through 20
for (int counter = 0; counter < 25; counter++) {
s = new StringBuilder();
for (int i = 0; i < counter; i++) {
spaces = spaces+" ";
}
System.out.println(spaces+"Recursive call:"+counter + "!");
System.out.printf("%d! = %d%n", counter, factorial(counter));
}
}
I don't understand why the output is 25, from my wrong understanding obviously, i thought it is 20, because: first loop will be: i = 2; x = 5 and there will be 4 more loops since i <= m , therefor 5 x 4 = 20. I know i'm wrong but can't figure out where.
public class num {
public static void main(String[] args) {
int m, x, i;
x = 0;
i = 1;
m = 5;
while (i<= m){
x = x + m;
i = i + 1;
}
System.out.println(x);
}
}
Let's try a dry-run for this:
x=0;i=1;m=5
while (1<=5) ? yes, so x=0+5; i=2,
while (2<=5) ? yes, so x=5+5; i=3,
while (3<=5) ? yes, so x=10+5; i=4,
while (4<=5) ? yes, so x=15+5; i=5,
while (5<=5) ? yes, so x=20+5; i=6,
while (6<=5) ? no, so exit from loop
And therefore the result is: x=25
Whenver face this type situation, try debugging and printing. Most of the time you'll find your answqer:
public class num {
public static void main(String[] args) {
int m, x, i;
x = 0;
i = 1;
m = 5;
System.out.println("Initial : x = " + x + " and i = " + i);
while (i <= m) {
x = x + m;
i = i + 1;
System.out.println("x = " + x + " and i = " + i);
}
System.out.println(x);
}
}
Output:
Initial : x = 0 and i = 1
x = 5 and i = 2
x = 10 and i = 3
x = 15 and i = 4
x = 20 and i = 5
x = 25 and i = 6
25
I have a problem in which I need to ask for user input for how many times they wish to roll a die and to create and print that an array that has the rolls requested. So far I can create the array, however another part of the problem is that whenever there are consecutive duplicate rolls I must put parentheses around them. For example inputting 11, creates the array
{1 , 2 , 1 , 4 , 4, 6 , 2 , 3 , 5 , 5 , 5} would print 1 2 1 ( 4 4 ) 6 2 3 ( 5 5 5 )
So far I have written
import java.util.Scanner;
import java.util.Random;
public class HW0603 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many times would you like to roll: ");
System.out.println();
int x = input.nextInt();
run(rolls(x), x);
}
public static int[] rolls(int x) {
Random random = new Random();
int y[] = new int[x];
for (int i = 0; i < x; i++) {
int z = random.nextInt(6) + 1;
y[i] = z;
}
return y;
}
public static void run(int a[], int b) {
for (int i = 1; i < b; i++) {
System.out.print(a[i] + " ");
}
}
}
As for the parentheses I honestly don't know how to start. Using if statements didn't work for me, my if statement variations seem to give me out of bound errors since I compare a[i] to a[i+1] and a[i-1]. Could anyone give me a place to start or some tips to being extracting consecutive duplicates?
you need to compare current item with next item
if equal, print "(" then print the item
make flag paranOpened that you have opened (, so you don't reopen ( again, to avoid this: 1 (2(2(2..., then when curr!=next, based on that flag either print the item or print the item then close the ")"
at end of loop
print lat item (b-1) that was excluded from the loop ..;i < b - 1;.., and check if you have opened "("
your run() method will be like this
static boolean paranOpened = false;
public static void run(int a[], int b) {
for (int i = 0; i < b - 1; i++) {
if (a[i] == a[i + 1]) {
if (!paranOpened) {
paranOpened = true;
System.out.print(" (");
}
System.out.print(a[i] + " ");
} else {
System.out.print(a[i] + " ");
if (paranOpened) {
System.out.print(") ");
paranOpened = false;
}
}
}// for loop
// print last item in array #(b-1)
System.out.print(a[b - 1] + " ");
// check if opened ( , then close it
if (paranOpened) {
System.out.print(") ");
}
}// run()
this is a quick solution, there could be better algorithms
The first problem with you program is that the counter in your run method starts
from 1 which should be zero. Your current program does not print the first element of the array.
then you need to check each element with the next one to see if they are duplicate and if they are open the parenthesis and vice versa.
The last element does not need to be checked so print it outside the loop and close the parenthesis if needed.
By the way you do not need to pass the array size element with it. Just use the array.length method.
public static void run(int a[], int b)
{
boolean pOpen = false;//keep track if parenthesis is open
for (int i = 0; i<a.length; i++)
{
if (i < a.length-1)//prevent out of bound exception
{
if (a[i] == a[i+1] && !pOpen )// check if it is needed to `open or close the parenthesis`
{
System.out.print("(");
pOpen = true;
}
System.out.print(a[i] + " ");
if (a[i] != a[i+1] && pOpen)
{
System.out.print(")");
pOpen = false;
}
}
}
System.out.print(a[a.length-1]);//print the last element
if (pOpen)//close the parenthesis if open
{
System.out.print(")");
}
}
Iterate through your array and keep a boolean that marks if parenthesis have opened.
import java.util.*;
class Ideone
{
public static int[] rolls(int x) {
Random random = new Random();
int y[] = new int[x];
for (int i = 0; i < x; i++) {
int z = random.nextInt(6) + 1;
y[i] = z;
}
return y;
}
public static void run(int a[], int b) {
StringBuilder sb = new StringBuilder();
String out = "";
boolean parens = false;
for (int j = 0; j < a.length; j++)
{
out = "" + a[j]; //by default just add an element
//check for duplicate and build parenthesis
if (j + 1 < a.length && a[j] == a[j+1]) //duplicate found
{
if (!parens) // if no parenthesis
{
parens = true; //start parenthesis
out = "( " + a[j];
}
}
else
{
if (parens) //if parenthesis already started
{
out = a[j] + " )";
parens = false; //stop parenthesis
}
}
sb.append(" " + out);
}
// if the last element occured multiple times
if (parens) //should end parens
{
sb.append(a[a.length-1] + " )");
}
//print out the result
System.out.println(sb.toString());
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.print("How many times would you like to roll: ");
System.out.println();
int x = input.nextInt();
run(rolls(x), x);
}
}
You need to use boolean to check whether your parenthesis is open or no.
Here I've tried to create a clean and readable example:
Sample code:
public class HelloWorld {
public static void main(String[] args) {
int arr[] = { 1, 2, 1, 4, 4, 6, 2, 3, 5, 5, 5 };
printConsecutiveInBrace(arr);
}
public static void printConsecutiveInBrace(int arr[]) {
int printFrom = 0;
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1 || arr[i] != arr[i + 1]) {
print(arr, printFrom, i);
printFrom = i + 1;
}
}
}
public static void print(int arr[], int printFrom, int printTo) {
if (printFrom < printTo) //Here check: Consecutive Duplicate
System.out.print("( ");
for (int i = printFrom; i <= printTo; i++)
System.out.print(arr[i] + " ");
if (printFrom < printTo)
System.out.print(") ");
}
}
Output:
1 2 1 ( 4 4 ) 6 2 3 ( 5 5 5 )
I need nested while loops to print so that the outter loop k makes one decrement iteration every time that inner loop "I" finishes an iteration. K has to start at 5 and count back to 1 and I has to starts at 0 and count to 10 by 2's. So it would the out put would look like this:
K = 5 I = 0
K = 5 I = 2
K = 5 I = 4
K = 5 I = 6
K = 5 I = 8
K = 5 I = 10
K = 4 I = 0
I have been stumped for hours and tried everyway to I can think of to make it work. Can someone please help?
public class Task1 {
public static int i = 0;
public static int k = 5;
public static void Display(){
while(k > 1){
while(i >=10){
i = i+2;
System.out.println("K = " + k + " I = " + i);
}
if (i >= 10){
k=k-1;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Display();
}
}
There are a few errors. Follow the comments
while(k >= 1){ // Make it >= instead of >
i = 0; // reset i
while(i <=10){ // Make it i<= (less than)
System.out.println("K = " + k + " I = " + i); //print before incrementing
i = i+2;
}
Rest of the code is correct. And the output is as expected
K = 5 I = 0
K = 5 I = 2
K = 5 I = 4
K = 5 I = 6
K = 5 I = 8
K = 5 I = 10
K = 4 I = 0
K = 4 I = 2
K = 4 I = 4
K = 4 I = 6
.
.
.
You need to initialize i before the start of the inner loop, inside the outer loop, so it gets reset each time
while(k > 1) {
i = 0;
while( i <= 10) {
Print
i += 2;
}
k--;
}
Your inner while loop condition was incorrect. And you were adding to i too soon so you would never print for 0.
Something like this
public class Task1 {
public static int i = 0;
public static int k = 5;
public static void Display(){
while(k > 0){
i = 0;
while(i <= 10){
System.out.println("K = " + k + " I = " + i);
i+=2;
}
k--;
}
}
public static void main(String[] args) {
Display();
}
}
Replace your display method with this..
public static void Display(){
while(k > 1){
i=0; //initialise i back to 0
while(i <=10){ //Change >= to <=
i = i+2;
System.out.println("K = " + k + " I = " + i);
}
k--;
//comment or delete below if block
/*if (i >= 10){
k=k-1;
}*/
}
}
use the following code.
public class Task1 {
public static int i = 0;
public static int k = 5;
public static void Display() {
while (k >= 1) { // use >=1 if you wanna print till 1
i = 0; // set i=0
while (i <= 10) {
System.out.println("K = " + k + " I = " + i); // add print
// statement
i = i + 2;
}
k--; // no need to use if (i >= 10){ }
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Display();
}
}
You can do it like this:
for(int k = 5;k>0;k--;){
for(int i = 0;i<10;i+=2;)
System.out.println(k+ "" +i)
}
The method printPowersOf2 accepts a max number as the argument and prints each power of 2 from 2^0 up to that max number.
printPowersOf2(3); outputs 1 2 4 8
printPowersOf2(5); outputs 1 2 4 8 16 32
I can't seem to figure out the right code to print. I have to use a loop and the *= operator. Math class not allowed. I know its something so simple too
Here is my code
public class Chap3LabP2 {
public static void main(String[] args) {
printPowersof2(3);
printPowersof2(5);
printPowersof2(10);
printPowersof2(12);
}
public static void printPowersof2(int maxNum){
System.out.print("1" + " ");
for(int i = 1; i <= maxNum; i++){
System.out.print(i*2 + " ");
}
System.out.println("");
}
}
Before the loop set i = 2. The loop body should be (pseudocode):
i *= 2
Print i
You can store the value of current power and in each iteration of the cycle multiply it by 2.
int pow = 1;
for(int i = 1; i <= maxNum; i++){
pow = pow * 2;
System.out.print(pow + " ");
}
public static void printPowersof2(int maxNum) {
int power = 0;
int answer = 1;
while (true) {
if (power <= maxNum) {
System.out.println(answer);
} else {
return;
}
answer *= 2;
}
}