This program in java doesn't stop executing [closed] - java

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 8 years ago.
Improve this question
I have written this java program for sorting some numbers. But it doesn't stop executing. Can you help me with it?
package inplacesort;
import java.util.*;
public class InplaceSort
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
Vector <Integer> intList = new Vector <Integer> ();
//getting the numbers from the user
char ans = 'y';
while (ans == 'Y' || ans == 'y')
{
System.out.print("Enter a Number: ");
intList.addElement(console.nextInt());
System.out.print("Do You Want to Continue?(Y/N)");
ans = console.next().charAt(0);
}
System.out.println("Before Sorting the Numbers: " + intList);
for (int i = 1; i < intList.size(); i++)
{
int j = i - 1;
while (j > 0 && intList.elementAt(i) < intList.elementAt(j))
{
j--;
}
for (int k = intList.size() - 1; k >= j; k--)
{
intList.insertElementAt(intList.elementAt(k),k + 1);
}
intList.insertElementAt(intList.elementAt(i+1),j);
intList.removeElementAt(i+1);
}
System.out.print(intList);
}
}

Your problem is with intList.size() in the k & i loops. This is not be as what you would expect it. When I debugged your code the value of k was 425996.
Edit :
When i debugged it more I saw that because of you mutating the vector within it self it keeps increasing in size. If you let your program run for a few minutes you will get out of memory error.
Please don't mutate the object you are looping though it. Either make a copy of it and the loop though one of them and mutate another or start with a fresh one & keep adding the values to it while looping over the older one.
System.out.println("Before Sorting the Numbers: " + intList);
List<Integer> sortList = new ArrayList<Integer>();
int minVal;
int index=0;
int size = intList.size();
for (int i = 0; i < size; i++)
{ minVal=Integer.MAX_VALUE;
for (int j = 0; j < intList.size(); j++)
{
if(intList.get(j) < minVal){
index=j;
minVal=intList.get(j);
}
}
intList.remove(index);
sortList.add(minVal);
}
System.out.print("After Sorting the Numbers: "+ sortList);

The reason is because your value for j is ALWAYS 1 less than the value for i. Therefore, infinite while loop.

Related

"Find Missing & Repeating Number" unable to compile on hackerrank suppose to use array list only not simple array [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 6 months ago.
Improve this question
Encountered this program on hackerrank it was showing runtime error.
The relevant code block is shown below.
On simple array its working, but on lists its not working.
Lists are only accepted.
Question statement on hackerrank:
You are given a read-only array of N integers with values also in the range [1,N] both inclusive. Each integer appears exactly once except A which appears twice and B which is missing. The task is to find the repeating and missing numbers A and B where A repeats twice and B is missing.
Input Format
First line is the length of the array - n
Second line contains n integer that is elements of the array
Constraints
1 <= n <= 105
1 <= arr[i] <= n
Output Format
Print array of integers containing repeating and missing number respectively
Sample Input 0
3
3 1 3
Sample Output 0
3 2
Explanation 0
A = 3 , B = 2 Since 3 is appearing twice and 2 is missing
public static List<Integer> find_missing(List<Integer> arr) {
int i;
// Repeating number
for (i = 0; i < arr.size(); i++) {
int abs_val = Math.abs(arr.get(i));
if (arr.get(abs_val - 1) > 0)
arr.get(abs_val - 1) = -arr.get(abs_val - 1);
else
return abs_val;
}
//Missing number
for (i = 0; i < arr.size(); i++) {
if (arr.get(i) > 0)
return (i + 1);
}
}
first of all arr.get(abs_val - 1) = -arr.get(abs_val - 1); is wrong because it's the same as saying 5 = -3 , as lValue is indeed a value not a variable , use arr.set(index, value); instead .
also in your code , you are using Math.abs() which isn'y necessary because in the question , it's said :
1 <= n <= 105 1 <= arr[i] <= n
so the values of arr[i] will always be positive.
so I edited the whole code of yours as it has many logic problems,
so for finding repeated numbers , what I do is to loop over the list , get every element then see if there is any other similar elements in the same array.
for finding repeated number , I loop over the numbers from 1 to N where N is entered by the user as specified by the problem above and check if every number is there in the list or not.
edited version of the code :
package com.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Integer> example = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i = 0; i < n; i++)
{
example.add(scanner.nextInt());
}
List<Integer> result = find_missing(example, n);
for (Integer i : result)
System.out.print(i + " ");
}
public static List<Integer> find_missing(List<Integer> arr, int n) {
List<Integer> temp = new ArrayList<>();
int i;
// Repeating number
for (i = 0; i < arr.size(); i++) {
for (int j = i + 1; j < arr.size(); j++) {
if (arr.get(j).equals(arr.get(i))){
if (temp.contains(arr.get(j)))
break;
temp.add(arr.get(i));
break;
}
}
}
//Missing number
for (i = 1; i <= n; i++) {
if (!arr.contains(i))
temp.add(i);
}
return temp;
}
}
and here is some examples of the output test cases:

displaying a reversed array? java [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 8 years ago.
Improve this question
It prints
Flip Method (only prints 9 to 5 ) but I want it to print from 9 to 0
http://imgur.com/gggiJwn
public static void flip(int[] flp){
System.out.println("This is the flip method");
for ( int i = 0; i < flp.length; i++){
int e = flp.length-1;
int temp = flp[e-i];
flp[i] = flp[e-i];
flp[i] = temp;
e--;
System.out.println("Index"+(i)+" :"+flp[i]); //is this the problem?
}
}
}
You need to change your logic to following to reverse the full array
public static void flip(int[] flp){
System.out.println("This is the flip method");
for ( int i = 0; i < flp.length/2; i++){
int e = flp.length-(1+i);
int temp = flp[i];
flp[i] = flp[e];
flp[e] = temp;
// remove print from here. else you will get half of the array
// since flp.length/2
}
}
Add that in a separate method.
for(int i = 0; i < flp.length; i++){
System.out.println("Index"+(i)+" :"+flp[i]);
}
The problem is that you are printing half of the elements
i < flp.length/2
That should be
i < flp.length
Actually, your for loop is fine - but you should remove the printing from inside that loop, and have it in a seperate loop after the flip loop
for ( int i = 0; i < flp.length; i++){
System.out.println("Index"+(i)+" :"+flp[i]);
}
public static void flip(int[] flp) {
System.out.println("This is the flip method");
int e = flp.length - 1;
for (int i = 0; i < flp.length / 2; i++) {
int temp = flp[i];
flp[i] = flp[e];
flp[e] = temp;
e--;
}
for (int i = 0; i < flp.length; i++) {
System.out.println("Index" + (i) + " :" + flp[i]);
}
}
Your for loop prints 9 to 5 because this is how you have configured your loop to iterate till i < flp.length/2 .
Change it to:
i < flp.length
from
i < flp.length/2

Find Prime Numbers based on user input [closed]

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 have these two methods that i am using to find prime numbers based on user input, i have a method called isPrime that logically should return true if a number is prime, however it always return true no matter what the number is?
I realise there are plenty of answers similar to my query but none have helped so far.
public static void userPrimes(){
int[] tempPrimes = new int[49];
int primesFound = 0;
//Input Amount of numbers to be analysed
int[] initial = new int[Integer.parseInt(JOptionPane.showInputDialog("Enter Amount of numbers to be checked")) -1];
//Input Values
for(int i = 0; i<initial.length; i++){
initial[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter number at position:" + (i+1)));
if (initial[i] > 49){
initial[i] = Integer.parseInt(JOptionPane.showInputDialog("Numbers cannot be greater than 49, Try again:"));
}
}
for(int i = 0; i<initial.length; i++){
if (isPrime(initial[i]) == true){
tempPrimes[i] = initial[i];
primesFound++;
}
}
int[] finalPrimes = new int[primesFound];
for (int i=0;i<finalPrimes.length;i++){
finalPrimes[i] = tempPrimes[i];
System.out.print(finalPrimes[i] + " ");
}
}
//checks whether an int is prime or not.
static boolean isPrime(int n) {
for(int j = 2; j < n; j++) {
if(n % j == 0) {
return false;
}
}
return true;
}
You have some problems in your code:
1.
int[] initial = new int[Integer.parseInt(JOptionPane.showInputDialog("Enter Amount of numbers to be checked")) -1];
The array should be in length of the amount that the user entered, not minus 1
2.
if (isPrime(initial[i]) == true){
tempPrimes[i] = initial[i];
primesFound++;}
You should put the primes in the temp primes array in tempPrimes[primesFound]
Also, your final loop is not useful.You can do the printing in the previous loop
Your isPrime function is fine but as performance wise is concerned you need to iterate till half of the number rather than iterating till number
boolean x = isPrime(13);
System.out.println(x);
static boolean isPrime(int n) {
for(int j = 2; j <= n/2; j++) {
if(n % j == 0) {
return false;
}
}
return true;
}
returns true and passing 14 returns false..it works perfect here..
might be the problem is with your loop code which is calling this method
modify this line by by removing -1
no need to do minus 1 as it reduces the no of input to user by one .
if user inputs amount as 3 then -1 makes him to enter only 2 numbers. so make it as below
int[] initial = new int[Integer.parseInt(JOptionPane.showInputDialog
("Enter Amount of numbers to be checked"))];
use only one loop as below to print all prime numbers
for(int i = 0; i<initial.length; i++){
if (isPrime(initial[i]) == true){
tempPrimes[i] = initial[i];
System.out.println(tempPrimes[i]);
}
}

rolling dice using arrays [closed]

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 9 years ago.
Improve this question
simple beginner Java question. I just learned how to use arrays and it's still a little confusing to me. My goal is to simply roll a number of dice a number of times and then project it as a sum, frequency, and percentage. I'm sure I'm doing something dumb, but I'm overlooking it!
import javax.swing.JOptionPane;
import java.util.Random;
public class Lab1 {
private static int N = 0;
private static int M = 0;
private static int total = 0;
private static Random rnd = new Random();
public Lab1(){
}
public static void main(String[] args) {
N = Integer.parseInt(JOptionPane.showInputDialog("How many dice would you like to roll?"));
System.out.println("Dice: "+N);
M = Integer.parseInt(JOptionPane.showInputDialog("How many times would you like to roll?"));
System.out.println("Rolls: "+M);
int total[] = new int[(6*Lab1.N)+1];
for (int i=0; i<=total.length; i++)
total[i] = 0;
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
System.out.printf("%3s%12s%12s\n", "Sum","Frequency", "Percentage " );
for(int k=2; k<total.length; k++);{
int percent = total[k]/(360);
System.out.printf("%3s%12s%12s\n", k, total[k], percent);
}
}
}
From what I can see the question is how can you store the previous roles of the dice. And I believe your problem is with this method:
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
I would change this to
for (int roll=1; roll<=M; roll++){
total[roll] = rnd.nextInt(6);
}
This will build up an array storing each dice roll - if that is of course what you are looking for...
Two things.
First, this loop will inevitably throw ArrayIndexOutOfBoundsException ("element" total[total.length] is out of bounds)
for (int i=0; i<=total.length; i++)
total[i] = 0;
You should use < instead of <=.
for (int i=0; i<total.length; i++)
total[i] = 0;
Second, this line here:
for(int k=2; k<total.length; k++);{
You have an empty loop here. You should remove the semicolon before the {:
for(int k=2; k<total.length; k++){
Now your code compiles, doesn't throw exceptions on the start, and prints a pretty table.
That's a start.
for(int k=2; k<total.length; k++);{
You need to remove the ; symbol from your loop as 'k' will not be resolved in the loop as you have terminated it. The format is for(x, x, x) {
The next thing to look at now is:
Dice: 1
Rolls: 1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at Lab1.main(Lab1.java:26)
Hint:
total[i] = 0; // this line is the problem.
Look at your <= in the loop.
for (int i=0; i<total.length; i++)
Simply chaging it to < results in this:
Dice: 1
Rolls: 1
Sum Frequency Percentage
2 1 0
3 0 0
4 0 0
5 0 0
6 0 0

Problems with 3 way sort in Java [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
Hi I think there may be a problem with my 3 way sort algorithm in the following Java program, also any suggestion on optimizing or just a simpler it would be greatly appreciated. The objective of the sort is to have the minus numbers first then zeros and then positive numbers
class ThreeWaySort
{
public static void main(String[] args)
{
int location = 0;
int[] sArray = new int[50];
for (int a = 25; a<= -24; a--)
{
sArray[location] = a;
location++;
}
int i = 0; int j = 0; int k = 50;
while (j!=k)
{
if (sArray[j]==0)
{
j++;
}
else if (sArray[j]<0)
{
int t = sArray[i]; sArray[i] = sArray[j]; sArray[j] = t; // case (ii)
i++; j++;
}
else
{
k--;
int t= sArray[j]; sArray[j] = sArray[k]; sArray[k] = t;
}
}
for (int a = 0; a <= 49; a++)
{
if(sArray[a] >-1)
{
System.out.println();
System.out.println();
System.out.println();
}
if(sArray[a] > 0)
{
System.out.println();
System.out.println();
System.out.println();
}
System.out.print(sArray[a] + " ");
}
}
}
When i run the program as is it costantly print out a zero followed by three line instead of what I'm expecting to be, Numbers below zero in a line, followed by 3 blank lines then any zeros in the array, 3 blank lines, positive numbers in the array.
The loop that populates your array is incorrect:
for (int a = 25; a<= -24; a--)
The variable a starts at 25, which is not less than or equal to -24, so the loop never executes. You should use >=.

Categories