Reversing an Array: Please check this code out [closed] - java

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 1 year ago.
Improve this question
I am struggling to understand why the following code cannot reverse an array.
I have made a copy of the array.
As you can see below, I have used a for loop and started the counter from 0 until the array's length. I set the first element of the original array to be equal with the last. And, the second from the beginning of the array to be equal with the second from the end. And, so on.
But the result gives me back the original array, not the reversed one.
I have pasted the whole code here so you can copy it into your IDE. Please help me figure this out.
Thank you very much in advance.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int[] myArray = normal(5);
reverse(myArray);
}
public static int[] normal(int count){
int [] array = new int[count];
for(int i = 0; i < count; i++){
array[i] = input.nextInt();
}
return array;
}
public static void reverse(int[] array){
int[] reverse = Arrays.copyOf(array, array.length);
for(int i = 0; i < array.length; i++){
array[i] = reverse[(array.length - i)-1];
}
System.out.println(Arrays.toString(reverse));
}
}

You are printing reverse-
Replace this line
System.out.println(Arrays.toString(reverse));
with this
System.out.println(Arrays.toString(array));

This line is the culprit
System.out.println(Arrays.toString(reverse));
Replace it with
System.out.println(Arrays.toString(array));
A better way to interpret the result would be to use something similar
public static void main(String[] args) {
int[] myArray = normal(5);
System.out.println("Before reverse");
System.out.println(Arrays.toString(myArray));
reverse(myArray);
System.out.println("After reverse");
System.out.println(Arrays.toString(myArray));
}
and remove the print statements from the recursive loop completely.

Related

Is there any method to solve this output problem or to initialize i [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 1 year ago.
Improve this question
These are two of the same code, the first one is in C++, and the other is in Java. The C++ code is compiling successfully, while the Java code gives an error:
last is not initialized
but at the end, the value of i will be the last. But it is throwing an error, please help me to figure it out.
C++ code:
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1,2,3,4,5,6};
int last;
for(int i=0;i<6;i++)
{
cout<<arr[i];
last = i;
}
cout<<last;
return 0;
}
Output:
1234565
Java code:
public class Main
{
public static void main(String[] args) {
int arr[] = {1,2,3,4,5,6};
int last;
for(int i=0;i<6;i++)
{
System.out.print(arr[i]);
last = i;
}
System.out.print(last);
}
}
Output:
Main.java:19: error: variable last might not have been initialized
System.out.print(last);
^
1 error
It seems to me that you didn't initialise the variable first. Initializing them is setting them equal to a value:
int a; // This is a declaration
a = 0; // This is an initialization
int b = 1; // This is a declaration and initialization
Please note, Java primitives have default values but as one user commented below
Their default value is zero when declared as class members. Local variables don't have default values
Try the following:
public static void main(String args[]) {
int arr[] = {1,2,3,4,5,6};
int last = 0;
for(int i=0;i<6;i++)
{
System.out.print(arr[i]);
last = i;
}
System.out.print(last);
}

Returning an Array confusion... who can explain to me the following not working code? [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 6 years ago.
Improve this question
/* the followng main method calls a sortBySelection() method wich shall return an array, but when printing the array directly from the calling statement i am getting wrong stuff!
the array is being returned and printed correctly using a for loop
if i am to use the Arrays class to print the returned array, java is not accepting my code... what is wrong with the code?
*/
import java.util.Arrays;
public class xyz {
public static void main(String [] args){
int [] list = {1,7,4,5,12,205,11,0,1,52,32,3, 27, 72,10, 19, 16};
//The following line is not printing the returned array!!
System.out.print("\nthe sorted array is: " +
(sortBySelection(list)+"\n"));
//The following statement is not even accepted by java!!!
System.out.print("\nthe sorted array is: " +
Arrays.toString((sortBySelection(list))+"\n"));
//The following for loop prints the returned array correctly!!!
for (int i=0; i<list.length; i++)
System.out.print(list[i]+" ");
for (int i=0; i<list.length; i++)
System.out.print(list[i]+" ");
}
public static int[] sortBySelection(int[] array){
int temp = 0;
for (int j=array.length-1; j>=0; j--){
for (int i=0 ; i<j; i++){
if (array[i] > array[j]){
//swap
temp = array[j];
array[j] =array[i];
array[i] = temp;
}
}
}
return array;
}
}
System.out.print("\nthe sorted array is: " +
Arrays.toString((sortBySelection(list))+"\n"));
The problem with this is you are calling Arrays.toString on a String. You can fix by fixing the parentheses
System.out.print("\nthe sorted array is: " +
Arrays.toString(sortBySelection(list))+"\n");

pseudocode to Put Even & Odd Elements of an Array in 2 Separate Arrays [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 7 years ago.
Improve this question
Write pseudocode to Put Even & Odd Elements of an Array in 2 Separate Arrays
import java.util.Scanner;
public class InsertElementInArray
{
public static void main(String[] args)
{
int n, pos, x;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n+1];
System.out.println("Enter all the elements:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Enter the position where you want to insert element:");
pos = s.nextInt();
System.out.print("Enter the element you want to insert:");
x = s.nextInt();
for(int i = (n-1); i >= (pos-1); i--)
{
a[i+1] = a[i];
}
a[pos-1] = x;
System.out.print("After inserting:");
for(int i = 0; i < n; i++)
{
System.out.print(a[i]+",");
}
System.out.print(a[n]);
}
}
Code and pseudocode both are heading in same way, but the main difference is the second one is much easier to write and understand for humans.
Let's take an example: We have a function that takes an string array as an argument and performs some complicated operations like searching for some specified char chains or looking for a pattern with regex.
It can looks very simply in pseudocode:
function doLotsOfStuff(String array):
variable patternApperance
for each string in array:
if (string has "PATTERN"):
increment patternApperance
return patternApperance
The thing about pseudocode is that it doesn't have any specific way or convention of writing. It's something where you don't have to care if it is going to compile, parse etc. but only care about that if others understand your pseudocode. In short words pseudocode isnt made for computers, it's for humans to better understand what a piece of code is going to do.

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

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

Array out of bounds exception:100 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This program is giving me array out of bounds exception :100
How to resolve??? also tell me whether my printing method of array is correct or not?
import java.util.Random;
import java.lang.Math;
class MersennePrime {
public int[] MersennefindPrime() {
int i=0;
int k=0;
int array[] = new int[100];
for(i=2;i<100;i++)
{
int count=0;
for(int j=2;j<=Math.sqrt(i);j++ )
{
if(i%j==0)
{
}
else
{
array[k]=i;
k++ ;
}
}
}
return array;
}
}
public class MersenneRandomNumbers
{
public static void main(String[] args)
{
MersennePrime mrn = new MersennePrime();
int array[] =mrn.MersennefindPrime();
for(int s=0;s<=array.length;s )
System.out.println("array is " array[s]);
}
}
}
This
for(int s=0;s<=array.length;s )
System.out.println("array is " array[s]);
}
should be like this
for(int s=0; s<array.length; s++) {
System.out.println( "array is " + array[s] );
}
Note the change from <= to <!
In your code, within the last loop s equals array.length, which is just the first index outside the boundaries of the array.
EDIT
Beside the upper syntactic error, there is a logical one here as well. In MersennefindPrime() the outer loop runs from 0 to 100, while the inner loop runs ("worst case") from 2 to 10. So there might be about 10 * 100 times, where you increase k and try to set the respective index in the array. This is far more, than the 100 items you allocated the array for!
If you can't be sure about the extent of your array at initialization, use some class, that implements the interface List. This could then look like this:
public List<Integer> MersennefindPrime() {
ArrayList<Integer> array = new ArrayList<Integer>();
for(int i=2;i<100;i++)
{
for(int j=2;j<=Math.sqrt(i);j++ )
{
if(i%j==0)
{
}
else
{
array.add( i );
}
}
}
return array;
}
You would have to adjust the code in main() accordingly!

Categories

Resources