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 3 years ago.
Improve this question
I was trying to obtain the minimun value and its index between an array of int.
I can't understand why if I use the for-loop inside the main method it doesn't work, but if I use the same code in an aux method it works. The code should be right.
The part of the code that is commented is the for-loop that doesn't work.
package minimoArray;
import java.util.Scanner;
public class minimoArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Inserisci 10 numeri interi: ");
int [] Arr = new int [10];
//int a = Arr[0];
int b = 0;
for (int i = 0; i < Arr.length; i++) { //NON si può riempire l'array con for-each
Arr[i] = scanner.nextInt();
}
/*
for (int i = 0; i < Arr.length; i++) {
if (Arr[i] < a) {
a = Arr[i];
b = i;
}
}*/
int minimo = minimo(Arr);
for (int i = 0; i < Arr.length; i++) {
if (Arr[i] == minimo) {
b = i;
}
}
System.out.println(" il minimo è: " + minimo);
System.out.println(" l'indice del minimo è: " + b);
}
private static int minimo (int [] a) {
var min = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < min ) {
min = a[i];
}
}
return min;
}
}
Edit: Just saw that the a is commented out too, my mistake. However, here Nicktar's answer applies with the reason why, you set a to the first element of the array, whose numbers weren't even set yet. The solution stays the same though.
First of all, stick to the naming convention of Java. Classes start with an uppercase letter, variables start with a lowercase letter.
Your mistake in the for loop within your main method is that a isn't even definied there, therefore the whole loop shouldn't even compile.
Simply add the var a = Arr[0]; before the loop and start the loop at the index 1.
The initialization of a in your main method is to early. You set a to Arr[0] before the array is written which sets it to 0 because primitive int is initalized to 0. So your code in the main methods compares all your array to 0.... This would find a minimum that is negative only.
Related
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.
I'm pretty new here and new to Java in general. I'm trying to solve a projecteuler question and I thought I had a solution but got stick with this error that I cannot fix. Just to give you an idea of what I was going for(in case it wasn't clear) this is the question:
"What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"
I don't want a solution but rather any help with getting rid of the "Java Variable expected inside a for loop." error would be appreciated.
public class Main {
public static void main(String[] args) {
int remainder = 0;
int remainders[] = new int[20];
int j = 1;
int remaindersMax = 0;
while (true) {
for (int i = 1; i <= 20; i++) {
j % i = remainders[i];
for (int k = 0; k < remainders.length; k++) {
if (remaindersMax < remainders[i]) {
remaindersMax = remainders[i];
}
}
}
if (remaindersMax == 0) {
break;
}
System.out.println(j);
}
}
}
j % i = remainders[i];
is invalid syntax. The left hand side (LHS) of a variable assignment can only contain a variable, not an expression. The right hand side (RHS) can contain arbitrarily complex expressions. You want to assign the array remainders at index i the value of the modulo operation. Swap LHS and RHS to make your program compile:
remainders[i] = j % i;
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).
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
class arr{
//array sorting to find maximum value
public static void main(String[]args){
int[] array={1,6,4,5,2};
int n;
int i,j;
for( i=0;i<(array.length*2);i++){
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
}
System.out.println(array[array.length]);
}
}
>
Can anyone tell me why i am getting runtime error and this sorting method will work or not?
Dont reinvent the wheel.., you are able to use arrays, so then use the array help class too...
:-)
public static void main(String[] args) {
final int[] array = { 1, 6, 4, 5, 2 };
System.out.println("Array before sort " + Arrays.toString(array));
Arrays.sort(array);
System.out.println("Array before sort " + Arrays.toString(array));
}
you will likely have an indexOutOfbounds exception because your second loop:
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
J loops through teh array then you attempt to index the array at J + 1 which on the last element in the array would push it out of bounds thus throwing an outOfBoundsException
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
Since array.length = 5 and j < array.length, the value array[j+1] in the last round of the inner loop cause array out of bound exception.
The swap needs another variable to hold array[j] before changing it.
e.g:
int x;
for( j=0;j<array.length - 1;j++){
if(array[j]>array[j+1]){
x = array[j];
array[j]=array[j+1];
array[j+1]=x;
}
}
The bubble sort algorithm can be implemented as follows
public static void sort(int[] arr){
int len = arr.length;
int k = 0;
for(int j = 0 ; j < len-1; j++){
for(int i= 0+k; i < len-1; i += 2){
if(arr[i] <= arr[i+1])
continue;
int tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
}
k++;
if ( k % 2 == 0)
k = 0;
} }
The inner loop must alternately start at indexes 0 and 1 so as not to always swap the same pairs (k variable).
The others have already pointed out why you're getting an exception.
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])