How to reverse an array of numbers in java? - java

import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
int[] xxx={1,3,5,7,9};
System.out.println(Arrays.toString(krakin(xxx)));
}
public static int[] krakin(int[]x) {
for(int i=x.length-1;i>=0;i--) {
int[]dev=new int[x.length-1];
dev[i]=x[i];
}
return dev[i];
}
I'm writing a method in java that reverses the order of the passed array.
I'm getting an error saying void is not allowed in my main method.
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
int[] xxx={1,3,5,7,9};
System.out.println(krakin(xxx));
}
public static void krakin(int[]x){
for(int i=x.length-1;i>=0;i--){
}
}

Your krakin method has a void return type, which means it returns nothing. Therefore you can't pass it as an argument to System.out.println.
You can change it, for example, to return an int array:
public static int[] krakin(int[]x){
int[] rev = new int[x.length];
...
return rev;
}
Then you could print it in your main:
System.out.println(Arrays.toString(krakin(xxx)));

With additional libraries it can be done within one line.
If we consider pure Java then I would write like this:
public static void main(String[] args) {
int[] xxx = {1,3,5,7,9} ;
int[] reversed = reverseWithStream(xxx);
int[] reversed2 = reverseWithTempArray(xxx);
Arrays.stream(reversed).forEach(System.out::println);
Arrays.stream(reversed2).forEach(System.out::println);
}
private static int[] reverseWithStream(int[] array) {
return Arrays.stream(array)
.boxed()
.sorted(Collections.reverseOrder())
.mapToInt(value -> value)
.toArray();
}
private static int[] reverseWithTempArray(int[] sourceArray) {
int[] tempArray = new int[sourceArray.length];
for (int i = 0; i < tempArray.length; i++) {
tempArray[i] = sourceArray[sourceArray.length - 1 - i];
}
return tempArray;
}
One of the biggest benefits of this one is the fact that the previously created array is not affected.
In case of:
java.util.Arrays#sort(int[])
Or apache commons methods, the previously created array is affected.

public static void main(String[] args) {
int[] numbers = new int [100];
int j = numbers.length ;
for (int i = 0; i <= 99; i++) {
numbers [i] = numbers [i] + j ;
j = j - 1 ;
System.out.println(numbers [i]);
}

Related

Modify the java program so that it works for the numbers in range between -25 and 25

I've started learning java some time ago. I'm reading through the Java Foundations book and doing exercises from the book to practice.
Just come across this one "Modify the java program so that it works for the numbers in the range between -25 and 25." and I wonder if you have any different solutions to it or is it really that simple? :)
Here's the original code:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 15;
final int MULTIPLE = 10;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
And here's my solution to it:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 51;
final int MULTIPLE = 1;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = (index - 25) * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
Yes, basically it's really simple exercise.
Regarding to your solution we actually don't need MULTIPLE in code.
public class BasicArray {
public static void main(String[] args) {
final int LIMIT = 51;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++) {
list[index] = (index - 25);
}
list[5] = 999; // change one array value
// Print the array values
for(int value : list) {
System.out.println(value + "");
}
}
}
If you are ready for a bit of advanced java, you can try following:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(System.out::println);
}
}
Or this if you need to replace one value:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(i -> {
if (i == -20) { // change one array value
System.out.println(999);
} else {
System.out.println(i);
}
});
}
}

Using Different Methods for Input and Display of an Array

public class InputRealNums1
{
static double [] numArr = new double [(int) (Math.random()*100)];
static String res = "";
public static void main(String[] args)
{
inputArray();
displayArray();
}
static void inputArray()
{
for (int i = 0 ; i < numArr.length ; i++)
{
numArr[i] = Math.random()*100;
}
}
static void displayArray()
{
System.out.println(res.inputArray());
}
}
The aim of this code is to seperate the input and the output. The program would generate certain numbers and then it will display them. I just want to know how to seperate the the input and output with the above methods.
You can display that array by using this method.
public static void displayArray()
{
for (int i = 0 ; i < numArr.length ; i++)
{
System.out.println(numArr[i]);
}
}
But this is not a good way. You can do this by passing parameters to the method.
public static void displayArray(Double[] myArray)
{
for (int i = 0 ; i < myArray.length ; i++)
{
System.out.println(myArray[i]);
}
}
public static void main(String[] args){
// some code in here
displayArray(numArr);
}

Manually sorting an ArrayList of strings alphabetically in Java

I am trying to reorder an ArrayList alphabetically for an assignment. I am not allowed to use any methods for automatically sorting, it has to be done manually. This is the code I tried, but it does not even run. I appreciate any input on this.
import java.util.ArrayList;
public class SortArrayList {
public static void main(String[] args) {
ArrayList<String> values = new ArrayList<String>();
public static void main(String[] args) {
ArrayList<String> values = new ArrayList<String>();
values.add("car");
values.add("bear");
values.add("apple");
values.add("xray");
sort(values);
for (int i = 0; i < values.size(); i++)
System.out.println(values.get(i));
}
public static void sort(ArrayList<String> x) {
String temp;
for (int i = 0; i < x.size() - 1; i++) {
for (int j = i + 1; j < x.size(); j++) {
if (x.get(i).compareToIgnoreCase(x.get(j)) > 0) {
temp = x.get(i);
x.add(i,x.get(j));
x.add(j,temp);
}
}
}
}
}
The lines
x.add(i,x.get(j));
x.add(j,temp);
are adding more elements to the ArrayList. You should change them to
x.set(i, x.get(j));
x.set(j, temp);
so that it replaces the elements at those positions.
Unless the multiple calls to public static void main(String[] args) was a typo when you copied it across for your question this would cause issues when running the program as it won't know where to start

How do split this code so that I can call it in the main method and return the statement from a method in a different file?

I need to split this code in a way where I would be calling it from the main and doing the sorting in another method in a different file.
This is what I have in the main:
public class Test {
public static void main(String[] args) {
//array of 10 numbers
double numbers[] = new double[]{1.9, 2.5, 3.7, 2, 1.5, 6, 3 , 4 , 5, 2};
//assign first element of an array to largest and smallest
double smallest = numbers[0];
double largetst = numbers[0];
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] < smallest)
smallest = numbers[i];
}
System.out.println("The minimum number is: " + smallest);
}
}
This is the other method:
import java.util.Arrays;
public class Chapter8 {
public static void chap8method(){}
public static double[][] sortRows(double[][] m) {
Chapter8.chap8method();
double[][] result = Chapter8.sortRows(m);
}
}
Create a class with the main method.
Main.java
public class Main {
public static void main(String[] args) {
//if your sort method is static in another class
Sort.sortRows(
//if your method is non static than create an object of that class
Sort obj = new Sort();
obj.sortRows
}
}
Your another class:
Sort.java
public class Sort{
public static double sortRows(double[][] m) {
//your sorting logic here
}
}

Having issues with arrays

I'm working on a homework problem that is asking me to write a program that generates 20 random numbers (0-99) in an array and then sorts and prints them.
I am getting crazy errors in my methods and I can't figure out whats wrong. I keep getting errors "Illegal start of expression, ; expected and .class expected. Any advice would be great.
import java.util.Arrays;
public class P6_14
{
public static void main(String[] args)
{
System.out.println("This program will sort randomly generated numbers");
public static int[] createNumbers(int n)
{
int[] numbers = new int[n];
for (int i = 0; i < n; i++)
{
numbers[i] = (int) (Math.random() * 99 + 1);
}
return numbers;
}
public static void orderArray(int[] array)
{
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
}
}
The way your trying to fit everything into one main method isnt very OOP. Try to create methods in the future within your class! Hope this help
import java.util.Arrays;
public class Hello{
private int[] numbers = new int[20];
public Hello(){
for (int i = 0; i < this.numbers.length; i++)
{
this.numbers[i] = (int) Math.floor(Math.random()*99);
}
}
public void orderArray()
{
Arrays.sort(this.numbers);
}
public void printArray()
{
for (int i = 0; i < 20; i++)
{
System.out.println(this.numbers[i]);
}
}
public static void main(String[] args)
{
System.out.println("This program will sort randomly generated numbers1");
Hello test = new Hello();
System.out.println("Printing randomized");
test.printArray();
test.orderArray();
System.out.println("Printing sorted");
test.printArray();
}
}

Categories

Resources