Java beginner- Can somebody debug my code? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
import java.util.*;
import javax.swing.*;
public class Practice {
public static void main(String[] args){
int[] numbers = {1, 2, 3, 14, 15, 16, 17};
getSmall(numbers);
}
public static void getSmall(int[] ar){
int small=0;
for(int i=0; i<ar.length; i++){
if(ar[i]<small)
small = ar[i];
}
System.out.println(small);
}
}
The program is to find the smallest number in the array, there is no compiler error but it doesn't show the correct result.
Thank you in advance!

public static void getSmall(int[] ar){
int small=ar[0];
for(int i=1; i<ar.length; i++){
if(ar[i]<small)
small = ar[i];
}
System.out.println(small);
}

Setting small initially to 0 is a bad idea as you are hoping that your array contains an element less than that for the answer to be correct.
A common idiom is to initialise small to ar[0] (having, of course, first checked that ar contains at least 1 element). Then run your loop from 1.
for(int i = 1;
(I dislike initialising small to a very large number since that puts the answer to your function in an undefined state if ar does not have any elements.)

Change
int small = 0
to
int small = ar[0];

Don't init small=0,
change to int small = ar[0]

You can also use
int small=Integer.MAX_VALUE;
in place of
int small=0;

this code will print small value, give the max of integer

Change this
public static void getSmall(int[] ar) {
int small = 0;
for (int i = 0; i < ar.length; i++) {
if (ar[i] < small)
small = ar[i];
}
System.out.println(small);
}
to
public static void getSmall(int[] ar) {
int small = ar[0];
for (int i = 1; i < ar.length; i++) {
if (ar[i] < small)
small = ar[i];
}
System.out.println(small);
}
because variable small is not assigned to any value from your array

Related

Program to find the maximum product of two numbers in a given integer array [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
Kindly help me with the underlying program as I am stuck. I'm a newbie programmer.
import java.util.*;
public class Source
{
static int maxProduct(int arr[]) {
int n = arr.length ;
if (n < 2)
{
System.out.println("NA");
return Integer.MIN_VALUE;
}
int a = arr[0];
int b = arr[1];
for(int i = 0; i<n; i++) {
for (int j = i+1; j<n; j++) {
if (arr[i]*arr[j] > arr[0]*arr[1]) {
a = arr[i];
b = arr[j];
}
}
}
return maxProduct;
}
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int[] arr = new int[size];
for(int i = 0; i < size; i++) {
arr[i] = s.nextInt();
}
int answer = maxProduct(arr);
System.out.print(answer);
}
}
You should change
if (arr[i]*arr[j] > arr[0]*arr[1])
to
if (arr[i]*arr[j] > a * b)
Since arr[0]*arr[1] is just the original max product, so you shouldn't be comparing against it.
Also note that your solution is not as efficient as it can be, since you are using a nested loop, which requires O(n^2) running time.
You can achieve linear (O(n)) running time if you use the fact that the max product is either the product of the two highest positive values or the product of the two lowest negative values. This means that if you find these 4 numbers, which can be done with a single loop, you'll find the max product.

To use method from the main method 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 5 years ago.
Improve this question
This question is pretty specific for my problem, that is why I am creating a new question. The second method in this program is supposed to make a row of the number 1 2 3 4 5 6 7 8 9 10. The only problem I am having is that I don't know how to print this out in the main method.
public class Uppgift1_6a
{
public static void main(String[] args)
{
for(int k = 0; k < 10; k++)
{
int tal = Numberline(k);
System.out.print(tal);
}
}
public static int Numberline(int tal1)
{
int tal = 1;
for(int i = 1; i < 11; i++)
{
tal = tal1 + i;
}
return tal;
}
}
Right now it prints out all the number from 11 to 19. And if I change it, it only prints out either 10 or 11.
Look closely at the code:
public static int Numberline(int tal1)
{
int tal = 1;
for (int i = 1; i < 11; i++)
{
tal = tal1 + i;
}
return tal;
}
The for loop literally does absolutely nothing - you're only returning the final result. The final result is always exactly equal to tal1 + 10; again, what the for loop did up this point makes no difference. (I'd encourage you to step through the code with a debugger to convince yourself of that fact).
If you want it to print out the values as you're going through the for loop, you need to do something like:
for (int i = 1; i < 11; i++)
{
// You may need to modify this line too, depending on what values you want printed
tal = tal1 + i;
// Print the value here
System.out.print(tal);
}
because the way you've written it it'll only print out the final value of tal (the one you returned).

finding odd numbers in java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 7 years ago.
Improve this question
I try to print the odd numbers in Java that are inside the array but this algorithm doesn't work ... May someone help me ?
The printing result is that :
"Exception in thread "main" .java.lang.ArrayIndexOutOfBoundsException: 7
at JavaArray.main(JavaArray.java:12)"
Code :
public class JavaArray {
public static void main(String[] args) {
int[] myArray = {1,3,4,5,8,9,10};
int i = 0;
for(i = 0; i < myArray.length; i++); {
if(myArray[i] % 2 == 1) {
System.out.println(myArray[i]);
}
}
}
}
Remove the semi-colon that is terminating your for loop
for (i = 0; i < myArray.length; i++);
^
Because you have placed semicolon after for loop, variable i increments till length of array(here 7). After that loop ends and you are trying to access myarray element through i which is 7 so it is giving out of bound exception.
Besides the extra ; you need to remove, you can consolidate by declaring the int in the loop declaration:
for (int i = 0; i < myArray.length; i++) {
.
.
.
}
Beside #Reimus point , you can also do it like below , sort the array if it's not sorted yet, in your case it is sorted . FYI, Instead of Collections.sort which is above O(N) complexity use a Hash Set.
public static void main(String[] args) {
int[] myArray={1,3,4,5,8,9,10};
Arrays.sort(str);
for (int i = 1; i < myArray.length; i++) {
if (str[i] == str[i - 1]) {
System.out.println("Dupe-num: " + str[i];
}
}
}

how to print number of occurences of element of an 1d array [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
I have worked on this but I keep getting an exception. Can anyone tell me where the problem is?
package assingment;
public class frequencyCount {
static void count(int x[]){
System.out.println("ENTERED ARRAY IS ");
for( int i=0; i < x.length; i++)
{
System.out.print(x[i]);
}
int c[] = new int [x.length];
for(int i=0; i<c.length ;i++)
{ c[i] = 0;
}
for(int i=0; i< x.length ;i++){
int m= x[i];
c[m]++;
}
System.out.println("frequency table");
for(int i=0; i< c.length ;i++){
System.out.print(i + " "+ c[i]);
}
}
public static void main(String[] args) {
count(new int []{1,1,5,2,10});
}
}
This is because you are incorrectly allocating the space to store your counts properly. What you need is to create an array where the total number of elements is the maximum of your array, plus 1 to account for 0. I'm going to assume that all of your numbers are positive to make things simple. As such, you actually need to determine what the maximum value is in your array first, then allocate the space accordingly.
By not doing this, when you specify the value of 5 in your array, you only allocated an array of size 5, and so if you try using 5 to index into your array, you get an OutOfBounds exception as you are trying to access the sixth position of the array, where it doesn't exist.
FWIW, there are much more smarter ways to do this, such as using a HashMap, but I'm assuming you haven't covered more advanced data structures in your Java course yet, and you probably need a solution with arrays. However, I completely recommend using HashMap.
As such, modify your code to find the maximum first, then allocate accordingly:
package assingment;
public class frequencyCount {
static void count(int x[]){
System.out.println("ENTERED ARRAY IS ");
// NEW - To store maximum
int maxi = -1;
for( int i=0; i < x.length; i++)
{
System.out.println(x[i]);
// Keep checking for the maximum
if (x[i] > maxi)
maxi = x[i];
}
// NEW - modify length to account for maximum
int c[] = new int [maxi+1];
for(int i=0; i<c.length ;i++)
{
c[i] = 0;
}
for(int i=0; i< x.length ;i++){
int m= x[i];
c[m]++;
}
System.out.println("frequency table");
for(int i=0; i< c.length ;i++){
System.out.println(i + " "+ c[i]);
}
}
public static void main(String[] args) {
count(new int []{1,1,5,2,10});
}
}
You are trying to access c[m] where m=x[i] in 3rd cycle. But x[2]=5 and c[5] causes an exception since there are only 5 elements in c[] (from c[0] to c[4])

Code not Working For Large Permutations [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
I've just completed a codility test and only achieved a score of 81%. My code failed when a 'large permutation' was tested against it.
I've got no idea why this failed, as the spec says all values are integers, and my for loop uses only int values. I would really appreciate it if somebody could look at my code and tell me why it provides a value of -1 for massive permutations:-
https://codility.com/demo/results/demo4G8CJS-9YN/
class Solution {
public int solution(int X, int[] A) {
// write your code in Java SE 8
int target = X;
int[] path = new int[X];
for(int i = 0; i < A.length-1; i++) {
if(A[i] != path[A[i]-1]) {
path[(A[i]-1)] = A[i];
target--;
}
if(target==0) {
return i;
}
}
return -1;
}
}
It should be for (int i = 0; i < A.length; i++)(not i < A.length - 1). As of now, the last element of the array is just ignored. It actually fails a very simple test: an array of one element and X = 1.

Categories

Resources