Problem With Reversing Each Number In An Array In Java - java

I'm trying to reverse each number in an Integer array using do-while, but I get NullPointerException error.I'm trying to reverse each element in this array: for instance if this is my array:{12,34,56} then the result must be:{21,43,65}.Can someone please help me with this?
public class Reverse {
public int[] revCalculator(int[] number) {
int[] reverse = null;
for (int j = 0; j < number.length; j++) {
do {
reverse[j] = reverse[j] * 10 + number[j] % 10;
number[j] /= 10;
} while (number[j] > 0);
}
return reverse;
}
}
public class ShowReverse {
public static void main(String[] args) {
// instantiation
// -----------------------------------------
Reverse rev = new Reverse();
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Enter The Number Of Elements: ");
int len = in.nextInt();
int[] numbers = new int[len];
for (int i = 0; i < len; i++) {
System.out.println("Enter Number: ");
numbers[i] = in.nextInt();
}
int[] result = rev.revCalculator(numbers);
// shows the result
// -----------------------------------------
System.out.println("THE REVERSE WOULD BE: ");
System.out.print(result);
}
}
pic

You didn't initialize your variable reverseArray, initialize it like so:
UPDATE, I see what you are trying to do, you want to reverse the values of your array, not the array itself
public int[] revCalculator(int[] number) {
int[] reverse = new int[number.length]; //Initialize it to the same size as the passed in arary
//int[] reverse = null; //Problem
StringBuilder sb = new StringBuilder();
for (int j = 0; j < number.length; j++)
{
//You could convert the number to string then reverse it and use parseInt() int
reverse[j] = parseInt(sb.append(number[j].toString()).reverse().toString());
//Clear the StringBuilder object
sb.setLength(0);
}
return reverse;
}

I would recommend initializing the reverse array to an array of the same length as the number array.
int[] reverse = new int[number.length];

There are a couple of changes that you have to make:
initialize reverse array int[] reverse = new int[number.length];
System.out.print(result); would give you the address of result array. You have to show the elements of the array.
int[] result = new int[numbers.length];
result = rev.revCalculator(numbers);
// shows the result
// -----------------------------------------
System.out.println("THE REVERSE WOULD BE: ");
//System.out.print(result);
for(int i = 0 ; i<result.length; i++)
System.out.println(result[i]);
Hope this helps.

Related

Printing an integer array in java using for loop, but the first element is always zero

I have been trying for hours to change a user inputted string of numbers into an integer, then create and print an integer array with those integers. I finally got it, but the first element of the printed array is always zero. I don't know how to fix it. I feel like it is really simple, but I am exhausted and am getting stuck on the easiest things. Does anyone know what is wrong? I'll put my code below.
String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];
for (int a : myArray) {
System.out.print(a);
System.out.print(" ");
for (int i = 0; i < size; i++) {
char n = stringNum.charAt(i);
int intNum = Character.getNumericalValue(n);
myArray[i] = intNum;
}
}
// input: 12345
// output: 0 2 3 4 5
You have mixed up printing the array and populating the array.
First, parse the input string and populate the array
String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];
for (int i = 0; i < size; i++) {
char n = stringNum.charAt(i);
int intNum = Character.getNumericalValue(n);
myArray[i] = intNum;
}
Then print the elements,
for (int a : myArray) {
System.out.print(a);
System.out.print(" ");
}

java arrays random scanner class

I am stuck in my beginner java course and am trying to get my array to print out with the user's input on randomly selected index's. With the code I have so far it will only print out an index with all 0's such as this "{0, 0, 0, 0, 0, 0}"
Here is the prompt:
Create an empty int array of size 6.
Create a method called populateArray that will pass an array, use random class to choose a random index and prompt the user to enter a value, store the value in the array. Note: Generate 6 random index numbers in an attempt to fill the array.
Create a method called printArray that prints the contents of the array using the for each enhanced loop.
Here is my code:
public class ChangeUp {
public static void main(String[] args) {
int[] array = new int[6];
System.out.println("Please enter 6 numbers to add to a list.");
populateArray(array);
printArray(array);
}
public static void populateArray(int[] array) {
Random r = new Random();
Scanner input = new Scanner(System.in);
int rArray = r.nextInt(array.length);
int i = 0;
for (i = rArray; i <= array.length; i++) {
i = input.nextInt();
}
}
public static void printArray(int[] array) {
System.out.print("{" + array[0]);
for (int i = 1; i < array.length; i++) {
System.out.print(", " + array[i]);
}
System.out.println("}");
}
}
for (int i = rArray; i <= array.length; i++) {
i = input.nextInt();
}
Here is your problem. You assign the value(s) to i, not to elements of the array.
Turn:
i = input.nextInt();
into:
array[i] = input.nextInt();
You do not change any values of array. You can do it with array[i] = value where i is index which value you want to change.
Here is example of what populateArray would looks like:
public static void populateArray(int[] array) {
Random r = new Random();
Scanner input = new Scanner(System.in);
int i = r.nextInt(array.length);
array[i] = input.nextInt();
}
You did not assigne input values to the array: array[i] = ....
I would recommend you to not randomly insert an elements, but just fill an array and then shuffle it.
public class ChangeUp {
public static void main(String... args) {
int[] arr = new int[6];
System.out.format("Please enter %d numbers to add to a list:\n", arr.length);
populateArray(arr);
printArray(arr);
}
public static void populateArray(int... arr) {
Scanner scan = new Scanner(System.in);
List<Integer> tmp = new ArrayList<>(arr.length);
for (int i = 0; i < arr.length; i++)
tmp.add(scan.nextInt());
Collections.shuffle(tmp);
int i = 0;
for (int val : tmp)
arr[i++] = val;
}
public static void printArray(int... arr) {
System.out.println(Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", ", "{", "}")));
}
}
Demo:
Please enter 6 numbers to add to a list:
1
2
3
4
5
6
{4, 3, 1, 5, 2, 6}

I want to create a method that returns a reversed array [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 2 years ago.
static int[] fun1(int[] ar){
int[] auxarray = new int[ar.length];
int j = ar.length;
for (int i = 0; i < ar.length; i++) {
auxarray[j - 1] = ar[i];
j = j - 1;
}
return ar;
}
I have tried to implement a swap method to modify the same array, but it didn't work (tested with a void method and printed the result inside it: same as the initial array)
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Please enter the size of the array: ");
size = input.nextInt();
array = new int[size]; //array and size are declared private static globally
for(int i = 0; i<size; i++){
array[i] = input.nextInt();
}
System.out.println("Your reversed string is:");
int[] reversedarray = fun1(array);
for(int i = 0; i < size; i++){
System.out.print(reversedarray[i] + ' ');
}
}
This returns 3334353637.. in all cases. Any solution or any idea on what I have done wrong?
error is in your fun1
You are returning a wrong array
What you can consider as an enhancement
You can simply swap the elements in the same array only iterate half the length of the array
static int[] fun1(int[] ar){
int size = ar.length, temp;
for (int i = 0; i < size/2; i++) {
temp = ar[i];
ar[i] = ar[size-1-i];
ar[size-1-i] = temp;
}
return ar;
}
You are returning the wrong array,ar instead of auxarray
Return auxarray instead of ar.

Bubblesort random Array Java

I'm very new to java and have been playing around with sorting algorithms. I have the following code working for a set array. I was just wondering what I'd need to change to get it to sort arrays of randoms lengths and integers. I guess the answer is pretty obvious any help is appreciated!
public static void main(String[] args) {
int number[]={8,5,3,2,9};
int temp;
boolean fixed=false;
while(fixed==false){
fixed=true;
for(int i=0; i<number.length-1 ; i++){
if(number[i] > number[i+1]){
temp = number[i+1];
number[i+1]=number[i];
number[i]=temp;
fixed=false;
}
}
}
for(int i=0; i<number.length; i++)
System.out.println(number[i]);
}
}
I mean, your algorithm would work regardless of the array's length. About how to generate such arrays, you could do this:
int n = Math.random()*10000 + 1; //so its never 0.
int number[] = new int[n];
for(int i=0;i<n;i++) number[i]=Math.random()*10000;
Everything else stays the same :).
EDIT: You commented on the question that you'd rather generate the array by taking an input from the keyboard. You can do that by using a scanner.
Scanner scanIn = new Scanner(System.in);
do{
int n = scanIn.nextInt();
} while (n<1);
int number[] = new int[n];
for(int i=0;i<n;i++) number[i] = scanIn.nextInt();
scanIn.close();
What you are looking for is probably a method to extract your bubblesort to. Please note that this method changes the input array and does not return a new array.
private static void bubblesort(int[] array) {
int temp;
boolean fixed = false;
while (!fixed) {
fixed = true;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
fixed = false;
}
}
}
}
You can then call it using different approaches.
Fixed size array:
// fixed size array
int number[] = {8, 5, 3, 2, 9};
bubblesort(number);
System.out.println(Arrays.toString(number));
Read numbers from System.in.
// read from sys.in like "2 6 4"
Scanner s = new Scanner(System.in);
String line = s.nextLine();
int[] parsedInts = Arrays.stream(line.split("\\s+")).mapToInt(Integer::parseInt).toArray();
bubblesort(parsedInts);
System.out.println(Arrays.toString(parsedInts));
You can the use Scanner Class in java and need to import java.util.Scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Enter the array length :");
int n = sc.nextInt();
int number[] = new int[n];
System.out.println("Enter the numbers :");
for(int i = 0; i < number.length; i++) {
number[i] = sc.nextInt();
}

Need help to sort array list

I am very new to java and I need to create an array that stores numbers and then outputs the numbers in sorted list the mean mode and median.
can anyone tell me if I am on the right track so far with the code below
int number=0;
ArrayList<Integer> listOfNumbers = new ArrayList<>();
Scanner scannerStream = new Scanner (System.in);
System.out.println("Enter list of numbers to Sort: (OR * TO END LIST)");
while(!(listOfNumbers = br.readLine()).equals("*"))
{
listOfNumbers = scannerStream.nextInt();
NumberList = listOfNumbers();
public Vector listOfNumbersSort (int number) {
for (int i=0; i<NumberList; i++) {
int Sort = listOfNumbers();;
return Sort;
// returns the mean
public Vector<Integer> listOfNumbersMean (int number){
return mean;
} // end
// returns the mode
public Vector<Integer> listOfNumbersMode (int number){
return mode;
} // end
// returns the median
public Vector<Integer> listOfNumberMedian (int number){
return median;
} // end
Thanks in advance for any help for advice provided
Use Collections.sort() to sort an ArrayList.
Use Arrays.sort() to sort an array.
can anyone tell me if I am on the right track so far with the code below
Your method definitions does not look good. You are passing a number and expecting the sortedlistofnumbers. Offcourse, if you already have a list, and you sorted it, and then if you get a new number and need to re-sort, then you can have the method signature as you have written, but not at the primary level.
The way you are accepting the list of number is not right. You need a loop. And when you use Arrays, since Arrays are fixed length, you should specify the size too.
see the below code for reference.
If you want to implement sorting in your way, there are various alogorithms like bubble sort.
Sorting Arrays
public class Sorter {
public static void main(String[] args) {
Scanner scanner = new Scanner(new InputStreamReader(System.in));
System.out.println("How many numbers to sort ?");
int count = scanner.nextInt();
int numbers[] = new int[count];
System.out.println("Enter list of numbers to Sort: ");
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
numbers[i] = scanner.nextInt();
}
System.out.println("List before sorting..");
for (int i = 0; i < count; i++) {
System.out.println(numbers[i]);
}
Arrays.sort(numbers);
System.out.println("Sorted list");
for (int i = 0; i < count; i++) {
System.out.println(numbers[i]);
}
}
}
Sorting ArrayList
public class SorterList {
public static void main(String[] args) {
Scanner scanner = new Scanner(new InputStreamReader(System.in));
System.out.println("How many numbers to sort ?");
int count = scanner.nextInt();
List<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter list of numbers to Sort: ");
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
numbers.add(scanner.nextInt());
}
System.out.println("List before sorting..");
System.out.println(numbers);
Collections.sort(numbers);
System.out.println("Sorted list");
System.out.println(numbers);
}
}
Edit:
If you want to do custom sorting - say bubble sort algorithm,
int temp;
for (int i = 0; i < (count - 1); i++) {
for (int j = 0; j < count - i - 1; j++) {
if (numbers[j] > numbers[j + 1]) // '> for ascending order'
{
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}

Categories