This question already has answers here:
What is a StackOverflowError?
(16 answers)
Closed 2 years ago.
During execution the problem is giving stack overflow problem, but what is this!
Runtime Error (NZEC)
Exception in thread main java.lang.StackOverflowError at
sun.nio.cs.US_ASCII$Encoder.encodeArrayLoop(US_ASCII.java:198) at
sun.nio.cs.US_ASCII$Encoder.encodeLoop(US_ASCII.java:231) at
java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:579) at
sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:271) at
sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125) at
java.io.OutputStreamWriter.write(OutputStreamWriter.java:207) at
java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129) at
java.io.PrintStream.write(PrintStream.java:526) at
java.io.PrintStream.print(PrintStream.java:669) at
Solution.solve(Solution.java:22) at Solution.solve(Solution.java:23)
at Solution.solve(Solution.java:23) at
Solution.solve(Solution.java:23) at Solution.solve(Solution.java:23)
at Solution.solve(Solution.java:23) at
Solution.solve(Solution.java:27) at Solution.solve(Solution.java:23)
at Solution.solve(Solution.java:27) at
Solution.solve(Solution.java:23)
import java.util.*;
public class Solution {
public static void printIncreasingNumber(int n) {
/* Your class should be named Solution.
* Don't write main() function.
* Don't read input, it is passed as function argument.
* Print output as specified in the question
*/
int k = 10;
int N = (int)Math.pow(10,n);//limit
solve((int)Math.pow(10,n-1),N);
}
static void solve(int j,int n){
if(j==n){
return;
}
if(check(j)){
System.out.print(j+" ");
solve(j+1,n);
}
else{
j = increase(j,n);
solve(j,n);
}
}
static boolean check(int k){
ArrayList<Integer> arr = new ArrayList<>();
int temp = k;
while(temp>0){
arr.add(temp%10);
temp = temp/10;
}
boolean ans = true;
for(int i=0;i<arr.size()-1;i++){
if(arr.get(i)<=arr.get(i+1)){
ans = false;
return ans;
}
}
return ans;
}
static int increase(int j,int n){
int ans = 0;
for(int i = j;i<n;i++){
ArrayList<Integer> arr1 = new ArrayList<>();
int temp = i;
while(temp>0){
arr1.add(temp%10);
temp = temp/10;
}
int count = 0;
for(int i1=0;i1<arr1.size()-1;i1++){
if(arr1.get(i1)<=arr1.get(i1+1)){
count++;
}
}
if(count==0){
ans = i;
break;
}
}
return ans;
}
}
My main function is,
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a;
Scanner s = new Scanner(System.in);
a = s.nextInt();
Solution.printIncreasingNumber(a);
}
}
You have several problems in your code:
Instead of if(j==n){ you should use if(j>=n){
It look like function increase has bug, due to this function returns same number or 0 (it is a quite strange for increase function, isn't?). For example, if you call printIncreasingNumber(2), when j = 90 this function returns 0 and you have infinitive loop (you call solve function again and again from 0 till 90),
P.S. I recommend you use any Java debbuger for checking, then you can see all numbers step by step.
Related
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 2 years ago.
I am writing a program that generates 10k random integers in the main class and then bubble-sorts it and returns the count of how many times the array was sorted. The problem is that even though I got the method to be public and return the count, it always shows up to means 0 after running it.
METHOD
public int bubbleSort(int bub[], int count){
int n = bub.length;
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(bub[j]>bub[j+1]){
int temp = bub[j];
bub[j] = bub[j+1];
bub[j+1] = temp;
count++;
}
return count;
}
void printArray(int bub[]){
int n = bub.length;
for(int i=0;i<n;i++){
System.out.print(bub[i] + " " );
}
}
}
MAIN CLASS
import java.util.Random;
class Main{
public static void main(String args[]){
Random rd = new Random();
Bubble ob = new Bubble();
int count=0;
int[] bub = new int[10000];
for(int i=0;i<bub.length;i++){
bub[i] = rd.nextInt(100);
}
ob.bubbleSort(bub, count);
System.out.println(count);
System.out.println("sorted array");
ob.printArray(bub);
System.out.println("number of times array was sorted " + count);
}
}
Because int is a primitive type the count variable won't get modified in your function.
change
ob.bubbleSort(bub, count);
to
count = ob.bubbleSort(bub, count);
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'm trying to make a bubble sorting algorithm in Java however my code just keeps going when It's supposed to sort without returning anything. When the program is run it gets as far as printing the array before the sorting however after that nothing happens but the program doesnt stop it keeps running
package src;
import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
public class bubbleSort {
public static void main(String[] args) {
int length = getLength();
List<Integer> randomList = createList(length);
System.out.println("The list before sorting:\n" + randomList);
List<Integer> newList = sortList(randomList, length);
System.out.println("The list after sorting:\n" + newList);
}
public static int getLength() {
System.out.println("Please enter how long you want the array to be");
Scanner reader = new Scanner(System.in);
int length = Integer.parseInt(reader.nextLine());
return length;
}
public static List<Integer> createList(int length) {
Random rand = new Random();
List<Integer> randomList = new ArrayList<Integer>();
for(int x = 0 ; x < length ; x++){
int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
randomList.add(randomnumber);
}
return randomList;
}
public static List<Integer> sortList(List<Integer> randomList, int length){
boolean sorted = false;
while(sorted == false){
sorted = true;
for(int x = 0 ; x < (length - 1) ; x++) {
if(randomList.get(x) > randomList.get(x + 1)) {
sorted = false;
int temp = randomList.get(x + 1);
randomList.set((x + 1), (x));
randomList.set((x + 1), temp);
}
}
}
return randomList;
}
}
Create a swap method to make it clearer (both for us and yourself):
private void swap(List<Integer> values, x, y) {
int temp = values.get(x);
values.set(x, values.get(y));
values.set(y, temp);
}
Other suggestions:
name your class BubbleSort rather than bubbleSort. Convention for class names is to start with uppercase.
don't pass the length as a second argument to your sort method. It's redundant and might become incorrect if someone sneakily adds an item to the list.
rename randomList to values or numbers or randomNumbers. No need to repeat the type in the variable name.
replace sorted == false with !sorted. This is the common and more readable notation
getLength and createList can be private
Consider using the main method to create an instance of your sorting class, with the list as a field. In that way the methods won't have to pass the list along to each other. Your code will be more readable and more object-oriented.
EDIT: you could take the separation even further and move all the static methods into a separate class called 'Application' or 'Main'. See edited code below:
Here's roughly how the code would look following my suggestions:
public class BubbleSort {
// a field
private List<Integer> numbers;
public BubbleSort(List<Integer> numbers) {
this.numbers = numbers;
}
public static List<Integer> sort() {
boolean sorted = false;
while(!sorted) {
sorted = true;
for(int x = 0; x < length - 1; x++) {
if(numbers.get(x) > numbers.get(x + 1)) {
sorted = false;
swap(x, x + 1);
}
}
}
return numbers;
}
private void swap(x, y) {
int temp = numbers.get(x);
numbers.set(x, numbers.get(y));
numbers.set(y, temp);
}
}
The Application class. It's purpose is to get the length from the user, create test data and set up and call a BubbleSort instance:
public class Application {
public static void main(String[] args) {
int length = getLength();
List<Integer> unsorted = createList(length);
System.out.println("The list before sorting:\n" + unsorted);
// creating an instance of the BubbleSort class
BubbleSort bubbleSort = new BubbleSort(unsorted );
List<Integer> sorted = bubbleSort.sort();
System.out.println("The list after sorting:\n" + sorted);
}
private static int getLength() {
System.out.println("Please enter how long you want the array to be");
Scanner reader = new Scanner(System.in);
return Integer.parseInt(reader.nextLine());
}
private static List<Integer> createList(int length) {
Random rand = new Random();
List<Integer> numbers = new ArrayList<Integer>();
for(int x = 0 ; x < length ; x++){
int randomnumber = rand.nextInt((100 - 1) + 1) + 1;
numbers.add(randomnumber);
}
return numbers;
}
BTW Good job splitting off those methods getLength and createList. That's the right idea.
you made a couple of mistakes
this:
randomList.set((x + 1), (x));
randomList.set((x + 1), temp);
should be:
randomList.set((x + 1), randomList.get(x));
randomList.set((x), temp);
full method:
public static List<Integer> sortList(List<Integer> randomList, int length){
boolean sorted = false;
while(sorted == false){
sorted = true;
for(int x = 0 ; x < (length - 1) ; x++) {
if(randomList.get(x) > randomList.get(x + 1)) {
sorted = false;
int temp = randomList.get(x + 1);
randomList.set((x + 1), randomList.get(x));
randomList.set((x), temp);
}
}
}
return randomList;
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I wrote a code for keeping record of indices even after sorting but it is showing me null pointer exception.I read other threads on same topic but still couldn't find.
import java.io.*;
import java.util.*;
public class Solution {
class Order{
public int index;
public int sum;
public void setIndex(int index){
this.index = index;
}
public void setSum(int sum){
this.sum = sum;
}
public int getSum(){
return this.sum;
}
public int getIndex(){
return this.index;
}
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
Order array[] = new Order[N];
int index = 0;
int sum = 0;
while(index<N){
int input1 = sc.nextInt();
int input2 = sc.nextInt();
//line 32
array[index].setIndex(index);
array[index].setSum(input1+input2);
index++;
}
ArrayList<Order> list = new ArrayList<Order>(Arrays.asList(array));
Collections.sort(list, new Comparator<Order>(){
#Override
public int compare(Order o1, Order o2){
return(Integer.compare(o1.getSum(), o2.getSum()));
}
});
System.out.println(list);
}
}
error is like this :
Exception in thread "main" java.lang.NullPointerException
at Solution.main(Solution.java:32)
I am passing i, still null pointer why?
You initialized array with Order array[] = new Order[N];, but the array is full of null objects. You need to initialize every element with new Order and then use setters
This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 7 years ago.
This question is based on my former question. How to add a "cheat" function to a Java mastermind game
I added the cheat function to my program, but it cannot compile because of "Cannot Make Static Reference to Non-Static Method"(the old codes works, you can check it through the link I post). Here are my new codes:
import java.util.*;
public class mm {
static int[] random;
public static void main(String[] args) {
System.out.println("I'm thinking of a 4 digit code.");
//update
mm m1 = new mm();
random = m1.numberGenerator();
int exact=0, close=0;
while(exact!=4){
int[] guess= m1.userinput(); //update
exact=0;
close=0;
for(int i=0;i<guess.length;i++){
if(guess[i]==random[i]){
exact++;
}
else if (random[i]==guess[0] || random[i]==guess[1] || random[i]==guess[2] || random[i]==guess[3]) {
close++;
}
}
if(exact==4){
System.out.println("YOU GOT IT!");
}
else{
System.out.println("Exact: "+exact+" Close: "+close);
}
}
}
public int[] userinput() {
System.out.print("Your guess: ");
Scanner user = new Scanner(System.in);
String input = user.nextLine();
//cheater
if (input.equals("*")) {
System.out.format("Cheater!Secret code is:");
for(int i=0;i<random.length;i++){
System.out.print(random[i]);
}
}
int[] guess = new int[4];
for (int i = 0; i < 4; i++) {
guess[i] = Integer.parseInt(String.valueOf(input.charAt(i)));
}
return guess;
}
public int[] numberGenerator() {
Random rnd = new Random();
int[] randArray = {10,10,10,10};
for(int i=0;i<randArray.length;i++){
int temp = rnd.nextInt(9);
while(temp == randArray[0] || temp == randArray[1] || temp == randArray[2] || temp == randArray[3]){
temp=rnd.nextInt(9);
}
randArray[i]=temp;
}
return randArray;
}
}
How to solve this?
You can't call a non-static method directly from a static method. in public static main(String [] args)
To do so, you should first create an object of the class.
try this at main method:
mm m1 = new mm();
random = m1.numberGenerator();
int [] guess = m1.userInput();
this should work
The other option would be to make userinput method static as well
Here I am working on the following problem where we are given n types of coin denominations of values v(1) > v(2) > ... > v(n) (all integers) The following code tries to find the minimum number of coins that are required to make a sum-C. Here the C is 100(see main function).When I run the code, error--"java.lang.StackOverflowError" comes. Please help.
import java.util.ArrayList;
public class Problem2 {
public static int count=4;
public static int []v={25,10,5,1}; //Array storing denominations
private static int findminimum(ArrayList<Integer> v2) {
int count=v2.get(0);
for(int i=0;i<v2.size();i++)
{
if(count>v2.get(i))
{
count=v2.get(i);
}
}
return count;
}
public static int countmincoins(int n)
{
int t;
if(n<0)
{
t=Integer.MAX_VALUE-100 ;
}
if(n==0)
{
t= 0;
}
else
{
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0;i<v.length;i++)
{
int temp=0;
temp=countmincoins(n-v[i])+1; //Stackoverflow error
a.add(temp);
}
t=findminimum(a);
}
return t;
}
public static void main(String args[])
{
System.out.println(countmincoins(100));
}
}
If you use recursion then you need to reach a condition to terminate the recursion. But in your code I do not seen any termination logic. Thats why, it get to infinite loop and StackOverflowException. In your code you use following code to terminate.
if(n==0)
{
t= 0;
}
But here n may not be zero. Becuase countmincoins(n-v[i]) do not ensure you to n will be 0.
Your code is infinite cause t will never be <0 or ==0 given that the values in the array and the condition (n - v[i] )+1, v[i] will always return the same value in every call to the method, therefore infinite recursion.
If your not restricted to using recursion the following would be much simpler:
public static int[] denominations = {25,10,5,1};
public static int minimumCoins(int amount){
int total = 0;
for(int denomination: denominations){
while(amount - denomination >= 0){
amount -= denomination;
total++;
}
}
return total;
}
public static void main(String args[])
{
System.out.println(minimumCoins(98));
}