Matthew Reading
Matthew Reading

Reputation: 81

Java Freezes when input is one million

My program freezes when I enter one million as a number for input. How do I fix this?

I tried separating second for loop as a second function, it didn't work.

import java.io.*;
public class Array {
public static void main(String[] args) {
  String line = System.console().readLine("How many digits of Pi do you want? ");
  int n = Integer.parseInt(line);

  int columns = (int)(10.0*n/3.0);

  int[][] makedigitsofpi = new int[columns][2];
  makedigitsofpi[0][0] = 30;
  makedigitsofpi[0][1] = 10;
  for(int i = 1; i < columns; i++) {
           makedigitsofpi[i][0] = i;
           makedigitsofpi[i][1] = i*2+1;
  }
  int[] make2s = new int[columns];
  for(int i = 0; i < columns; i++) {
            make2s[i] = 2;
  }
  int[] timesby10 = new int[columns];
  int[] thirdrow = new int[columns];
  int[] fourrow = new int[columns];
  int[] fifthrow = new int[columns];
  for(int four_rows = 0; four_rows < n; four_rows++) {
         for(int i = 0; i < columns; i++) {
               timesby10[i] = make2s[i]*10;
         }
         for(int column = (columns - 1); column >= 0; column--) {
                if(columns == (column + 1)) { //last column
            thirdrow[column] = 0; // add last
            }
            else { // Third Row
                    int[] cell0 = makedigitsofpi[(column+1)];
                    int cellfour = fourrow[(column+1)];
                    int cellfive = fifthrow[(column+1)];
            int d = cellfour - cellfive;
                thirdrow[column] = (d*cell0[0])/cell0[1];
            }
         }
     }
  }
}

I need my program to be able to handle large numbers. This program is only the start of my project. The project is to create a program that generates Pi to a unlimited amount of digits.

Upvotes: 1

Views: 89

Answers (1)

matheszabi
matheszabi

Reputation: 624

How do I fix this?

Do the work in background thread.

Your code is working, the processor is used, doing math.

The "freeze" it is because it is not handling your inputs and is not finished his job.

To finish earlier the job, give smaller number of course.

To handle your imputs you need to do those for loops in a separated Thread The code will not ececute faster, but you will not have the "freeze" feeling. If you would have a button to start in this case the button would be pressed and stay pressed, no other input.

In multi threaded context the button would release and you could switch from "start" state to "stop" state and if you press the button again, you set a Boolean variable value toggle: ex shouldCalculate = false; In your for loop if check that value, if is false, than exit from the thread, that's all.

Please take a look here to work with threads.

Upvotes: 1

Related Questions