Java 1.4.2 - ArrayIndexOutOfBounds Error [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
(I am using Java 1.4.2) I wanted to have an array that should flip a 'coin' a certain amount of times given by the user (the coin can flip up to 1000 times). Then randomly generate an integer between 1 and ten, store all the numbers in an array. I have the following code but it keeps on giving me the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at CoinFlip.main(CoinFlip.java:42)
Here is the code I wrote.
import java.io.*;
import java.math.*;
public class CoinFlip
{
public static void main(String[] args) throws IOException
{
// setting up variables
String timesString;
int times;
// setting up input
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
do
{
// times will display how many times the coin will flip
// loop if times does not fulfill the requirements
System.out.println("How many times do you want the coin to flip? (MUST be an integer between 1 to 1000)");
timesString = in.readLine();
// convert timesString into an integer
times = Integer.valueOf(timesString).intValue();
if((times > 1000)||(times < 1))
{
System.out.println("ERROR: The number of times you flip the coin must be an integer between 1 and 1000.");
}
System.out.println("The value for times is " +times);
}
while((times > 1000)||(times < 1));
// create a new array
double flip[] = new double[times];
// create a new variable timeStore that sets the boolean conditions for the For Loop
int timeStore;
for(timeStore = 0; timeStore <= times-1; timeStore++)
{
System.out.println("timeStore (how many iterations) is " +timeStore);
System.out.println("FOR LOOP: When " +timeStore+ " is less than or equal to " +(times-1));
flip[times] = Math.round(Math.random()*9)+1;
// the line above stores a random integer between 1 and 10 within the current index
System.out.println("flip["+times+"] = "+flip[times]);
}
}
}

At line 42;
flip[times] = Math.round(Math.random()*9)+1;
Should be;
flip[timeStore] = Math.round(Math.random()*9)+1;
Then also in the System.out on line 44.

These are wrong:
42: flip[times] = Math.round(Math. random()* 9 ) + 1;
44: System.out.println("flip[" + times + "] = " + flip[times]);
It appears you meant
42: flip[timeStore] = Math.round(Math.random()*9)+1;
44: System.out.println("flip["+timeStore+"] = "+flip[timeStore]);
Since you declared flip as an array of size times, only indices 0...(times - 1) are valid. In particular, index times is invalid and so flip[times] will throw.
Note that the compiler was telling you the offending line, and the offending index passed in. It's telling you you passed in 7 as the index. But note, this exception is happening on the first iteration of your loop. You can tell this by the output that your program would have produced since you have helpful print debugging statements in your code. Thus, you should have been able to reason: hey, why is my array seeing the index 7 on the first iteration of the loop when the index should be 0? At that point, the error practically figures itself out.
Also, idiomatic usage of arrays is:
for(timeStore = 0; timeStore < times; timeStore++)
but even better is:
for(timeStore = 0; timeStore < flip.length; timeStore++)

Related

I was solving SPOJ problem 2 of PRIME GENERATOR. I am getting wrong answer as output by SPOJ compiler. Can someone help me? [closed]

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 2 years ago.
Improve this question
PROBLEM DESCRIPTION
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
//----------BLANK SPACE BETWEEN TEST CASES-------------
3
5
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int i=0;i<t;i++)
{
boolean prime = true;
long m = in.nextLong();
long n = in.nextLong();
if(m<2)
{
System.out.println("2");
m=3;
}
for(int j=m;j<=n;j+=2)
{
int z = (int)Math.floor(Math.sqrt(j));
for(int k=2;k<=z;k++)
{
if(j%k==0)
{
prime=false;
break;
}
}
if(prime)
System.out.println(j);
}
System.out.println();
}
}
}
Your loops are using int datatype. It is lossy because you are comparing long with int. It will work for small numbers but constraints are too big so try using long.
Edit
I thought its because overflow without running it.
Your code has lots of problems
It will not work when m is even
you are not setting prime back to true in loop
Check these suggestions and comment is it working?
Solution
use long datatype in loop (that is not necessary)
set prime = true in inner loop
instead of incrementing by 2 i.e. j+=2, increment by 1 j+=1.

What would cause a for loop to decrement when it's supposed to increment?

I wrote a method to calculate how long ago a father was twice as old as his son and in how many years from now this would be true. Unexpectedly, it returns "-2 years ago" for an 8-year-old father and a 3-year-old son. Equally unexpectedly, it returns "-1 years from now" for a 3-year-old father and a 2-year-old son. I am not concerned about how to improve the code because I already know how to do this. Instead, I am puzzled about why the for loop counter appears to be decrementing when it's supposed to increment.
Here is my code.
public class TwiceAsOld {
public static void twiceAsOld (int currentFathersAge, int currentSonsAge) {
int yearsAgo;
int yearsFromNow;
int pastFathersAge = currentFathersAge;
int pastSonsAge = currentSonsAge;
int futureFathersAge = currentFathersAge;
int futureSonsAge = currentSonsAge;
for (yearsAgo = 0; pastFathersAge != 2 * pastSonsAge; yearsAgo++) {
pastFathersAge--;
pastSonsAge--;
}
System.out.println("The father was last twice as old as the son " + yearsAgo + " years ago.");
for (yearsFromNow = 0; futureFathersAge != 2 * futureSonsAge; yearsFromNow++) {
futureFathersAge++;
futureSonsAge++;
}
System.out.println("The father will be twice as old as the son in " + yearsFromNow + " years from now.");
}
public static void main(String[] args) {
twiceAsOld(8, 3);
twiceAsOld(3, 2);
}
}
With twiceAsOld(8, 3), the for loop's increment appears to have reversed itself to count down from 0 instead of up. With twiceAsOld(3, 2), the -1 might stand for an error indicating that the father has never been twice as old as his son and never will be. What I don't understand is what would cause a for loop to start decrementing the i value when it's supposed to increment. I was expecting the counter to increment indefinitely until the program ran out of memory.
I already know how to improve this program, but I am curious about how the counter in a for loop can decrease when it's supposed to increase. Can anybody explain this?
(UPDATE: Thanks everyone for your answers. I can't believe I forgot about integer overflow. I tried making the variables longs instead of integers, but this made the program even slower. Anyway, now I realize that the counter was incrementing all along until it overflew and landed at a negative value.)
It became negative because that is what happens in Java when an int calculation overflows.
Take a look at
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.2
It says that
If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.
Didn't you notice that your program runs quite slowly? :)
For the (8, 3) years ago case, your for loop keeps looping and looping, trying to find a year that the father is twice as old, but as we know, the father will only become twice as old in the future, but not in the past. The for loop doesn't know this and it will try very hard to find such a year. It tries so hard that yearsAgo is incremented past the max value of int. This causes an overflow, and the value of yearsAgo will "wrap back around" to the minimum value of int, which is a negative number. And then this negative number will get incremented many many times, until -2.
The same goes for the other case.
To fix this, you can add if statements to check if the results are negative:
public static void twiceAsOld (int currentFathersAge, int currentSonsAge) {
int yearsAgo;
int yearsFromNow;
int pastFathersAge = currentFathersAge;
int pastSonsAge = currentSonsAge;
int futureFathersAge = currentFathersAge;
int futureSonsAge = currentSonsAge;
for (yearsAgo = 0; pastFathersAge != 2 * pastSonsAge; yearsAgo++) {
pastFathersAge--;
pastSonsAge--;
}
// Here!
if (yearsAgo >= 0) {
System.out.println("The father was last twice as old as the son " + yearsAgo + " years ago.");
}
for (yearsFromNow = 0; futureFathersAge != 2 * futureSonsAge; yearsFromNow++) {
futureFathersAge++;
futureSonsAge++;
}
if (yearsFromNow >= 0) {
System.out.println("The father will be twice as old as the son in " + yearsFromNow + " years from now.");
}
}
You can also stop the loop when it reaches negative values to make your program faster:
for (yearsAgo = 0; pastFathersAge != 2 * pastSonsAge && yearsAgo >= 0; yearsAgo++) {
When I debug your code I can see that yearsAgo is incrementing without bound, causing pastFathersAge and pastSonsAge to go into negatives. This is causing negative integer overflow. This happens because your condition pastFathersAge != 2 * pastSonsAge is never met (rather, never NOT met). Not until your futureFathersAge has gone all the way through the negatives, back into positives, and finally settles on -2.
The moral of the story is to make certain that your terminating condition for your loop can always can be met. Don't use !=, use >= or <= instead.

Counter Loop - Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
Edit: I have found a way to work with CompareTo to help with this problem, but for some reason I cannot get the count down to work.
It's a negative number that needs to get more negative to meet the requirements, but I am missing something here. When I execute the down section it closes the program. So to me this means that I have something messed up and the program isnt seeing the problem and closing.
We are supposed to:
Ask the user for an integer then ask the user if he/she wants to count
up or down. Display a table of numbers where the first column contains
the counter, the second column contains the counter plus 10, and the
third column contains the counter plus 100. Make it so each number
takes up 5 spaces total.
If counting up, the first column should contain numbers 1 through the
user input; If counting down, the first column should contain numbers
-1 through the the negative of the user input;
Do user input validation on the word "up" and "down". Allow for any
case.
import java.util.Scanner;
public class ps1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//Comparision string already declared
String up = "up";
String down = "down";
//initialize the counters sum
int sum = 0;
//ask the user for a number
System.out.println("Enter an ending value");
int num1 = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Count up or down?");
String input = keyboard.nextLine();
while (input.equalsIgnoreCase(up) || input.equalsIgnoreCase(down)) {
System.out.println("Count up or down?");
input = keyboard.nextLine();
}
if (input.compareToIgnoreCase(up) == 0) {
if (num1 >= 0)
for (int c = 1; c <= num1; c++) {
sum = sum + c;
System.out.printf("%5d%5d%5d\n", c, c + 10, c + 100);
else
System.out.println("Up numbers must be positive");
if (input.compareToIgnoreCase(down) == 0) {
for (int c1 = -1; c1 <= num1; c1--) {
sum = sum + c1;
System.out.printf("%5d%5d%5d\n", c1, c1 + 10, c1 + 100);
}
}
}
}
}
I see you have figured out core logic. BTW, your code will not compile, there is a syntax error.
Your code would look like this:
print(a a+10 a+100)
I know that it's not valid syntax but you would be able to figure out the correct way to write the code.
To print data properly, you will need following:
https://dzone.com/articles/java-string-format-examples
I would recommend visualizing the output first. In your case, it would look like following: (_are spaces)
Enter an ending value: 2
Direction: Up
____1___11__101
____2___12__102
Also, think about error cases. What will happen in following:
Enter an ending value: -10
Direction: Up
Error: Improper data
You are allowing user to enter a positive num1 and count down using for (int counter1 = -1; counter1 >= num1; counter1--). This makes no sense as counter1 >= num1 resolves to -1 >= 1 which is never true. When direction is down the number must be negative and when direction is up the number must be positive.
You might need to loop until user provides a valid direction. Currently you go down for any input that is not up. A possible solution would be to:
String input;
do {
input = keyboard.nextLine();
} while (!input.equalsIgnoreCase("up") && !input.equalsIgnoreCase("down"));
Please use shorter variable names. counter1 is scoped just to the for loop block so call it i. It's easier to read.
Whichever editor you are using configure auto formatting :)

Recursions With Integers (Very Basic) [closed]

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 6 years ago.
Improve this question
I am currently taking a HS course on java, so I am a novice at java to say the least. Right now, for my own use, I am writing a program to take a 2 digit number, and then add up it and all the odd numbers before it till 1. I have the Scanner, calculating whether the number is odd or even, and the runner methods done already(the basic bit), but am a bit confused on the logic. I am trying to use a recursion, and do this code, but am a bit stuck. It would be helpful if you could point me in the right direction, without giving the whole code away. Thanks, - A Novice Programmer
public static void main(String[] args)
{
MathRecursion tester = new MathRecursion();
tester.Method1Runner();
}
public void Method1Runner()
{
GetIntM1();
OddOrEven();
System.out.println("\n\n");
}
public void GetIntM1()
{
Scanner kb = new Scanner(System.in);
System.out.print("\n\n\nEnter a 2 digit integer: ");
twoDig = kb.nextInt();
}
public void OddOrEven()
{
if (twoDig % 2 == 0)
{
//This is even method
Method1a(twoDig);
}
else
{
//This is odd method
Method1b(twoDig);
}
}
public int Method1a(int a)
{
//if (a = 1)
int result = 0;
while (a<=b)
{
result+=a;
a++;
}
System.out.println("The sum of all numbers is "+result);
}
You don't need recursion. The sum of the first n odd numbers is n*n.
The number of odd numbers before a number x is floor(x/2) or in Java (int) x/2 or if x is an int, just x/2.
So the expression in Java that gives you "a 2 digit number, and then add up it and all the odd numbers before it till 1" where the number is stored in int x is:
x + (x/2) * (x/2)
or simplified:
x + x*x/4

Java program involving [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to write the following program sequence.
The first three numbers in the sequence are 1, 1, 2. Every other number in the sequence is the sum of the three previous numbers. The program should prompt the user to enter a limit; the program will stop when the current number in the sequence is greater than or equal to this limit.
For example if I write the limit being 123 I should get: 1 1 2 4 7 13 24 44 81
I tried the following:
import jpb.*;
public class XiaolinSequence {
public static void main(String[] args) {
SimpleIO.prompt("Enter a limit on the largest number to be displayed:");
String userInput = SimpleIO.readLine();
int counter = Integer.parseInt(userInput);
int older = 1;
int old = 1;
int current = 2;
while (current < counter) {
int nextNumber = older + old + current;
older = old;
old = current;
current = nextNumber;
System.out.println(nextNumber);
}
}
}
But I am having trouble getting the sequence to print out.
You need to change how you print things.
The missing 1 1 2 are never printed because they are never stored in nextnumber, the only variable you ever print.
You will get an additional 149 because you print nextnumber without checking it its value is greater than the limit.
For me the output of the following code is 1 1 2 4 7 13 24 44 81 all on new lines.
int counter=123; // replaced IO code so I did not have to download the jar.
int older=1;
int old =1;
int current=2;
System.out.println(older); // prints the first 1
System.out.println(old); // prints the second 1
System.out.println(current); // prints the 2
while(current<counter){
int nextnumber=older+old+current;
older=old;
old=current;
current=nextnumber;
if(nextnumber <= counter)
{
System.out.println(nextnumber);
}
}
Ok since people bashed me for your SimpleIO, use whatever you want to read the input. Instead, I'm going to point out a logic flaw in your code.
For the program to function correctly, you need to print out older instead of current, like so:
while (older < counter)
{
System.out.println(older);
final int nextnumber = older + old + current;
older = old;
old = current;
current = nextnumber;
}
It works just fine.
There is no such thing as SimpleIO in java.lang.
You may want to replace String userInput = SimpleIO.readLine() with
System.out.print("Enter limit: ");
Scanner in = new Scanner(System.in);
String userInput = in.next();
then the code will work.
Oh and by the way, don't forget to print out 1 1 2 before you start the loop.

Categories

Resources