Java: Output Array in Reverse Order - java

I am new to Java and working with arrays. Also new to this site. Trying to output my array in reverse order:
import java.util.Scanner;
public class ListingTest
{
public static void main (String[] args)
{
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many names will you enter?");
length = input.nextInt();
String[] names = new String[length];
int[] ages = new int[length];
for(int counter = 0; counter < length; counter++)
{
System.out.println("Enter name " +(counter+1));
names[counter] = input.next();
System.out.println("Enter age " +(counter+1));
ages[counter] = input.nextInt();
}
input.close();
for(int counter = 0; counter < length; counter++)
{
System.out.println("Name: " +names[counter]+ " Age: "+ages[counter]);
}
}
}
Having trouble with the last "for loop." Any help is appreciated.
Thank you.

for (int i = names.length - 1; i >= 0 ; i--) {
System.out.println("Name: " + names[i] + " Age: " + ages[i]);
}
This starts at the top of the array and decrements i by 1 every iteration.

Just for printing Array at reversed order you have to use following:
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for (int i = arr.length - 1; i >= 0; i--) {
System.out.println(arr[i]);
}
}
Or can use Commons Lang library:
ArrayUtils.reverse(arr)

Related

How can I sum these two arrays into a new one?

How can I sum these two arrays into a new one? Where the first value of the arrayA sums the first value of the arrayB?
public class Exercises {
static BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
static PrintStream out = System.out;
public static void main(String[] args) throws IOException {
int numbersA[] = new int[5];
int numbersB[] = new int[5];
int numbersC[] = new int[5];
for (int i = 0; i < 5; i++) {
out.print("Please insert a number for the first array: ");
numbersA[i] = Integer.parseInt(in.readLine());
}
for (int i = 0; i < 5; i++) {
out.print("Please insert a number for the second array: ");
numbersB[i] = Integer.parseInt(in.readLine());
}
int j = 0;
for (int i = 0; i < 5; i++) {
numbersC[j] = (numbersA.length[i] + numbersB.length[i]);
}
{
out.print("The sum of the two arrays are: " + numbersC[j] + " ");
}
out.println();
}
}
You were pretty close. numbersA[i] and numbersB[i] (not the length of each array). Also, you don't need j and should print the prelude before the loop. Like,
out.print("The sum of the two arrays are: ");
for (int i = 0; i < 5; i++) {
numbersC[i] = numbersA[i] + numbersB[i];
out.print(numbersC[i] + " ");
}
out.println();
Finally, your code relies on magic numbers (hard coded array lengths). That is bad practice, instead you should use the array.length so your code doesn't require changing when your array sizes change. Like,
int[] numbersA = new int[5];
int[] numbersB = new int[5];
for (int i = 0; i < numbersA.length; i++) {
out.print("Please insert a number for the first array: ");
numbersA[i] = Integer.parseInt(in.readLine());
}
for (int i = 0; i < numbersB.length; i++) {
out.print("Please insert a number for the second array: ");
numbersB[i] = Integer.parseInt(in.readLine());
}
int[] numbersC = new int[Math.min(numbersA.length, numbersB.length)];
out.print("The sum of the two arrays are: ");
for (int i = 0; i < numbersC.length; i++) {
numbersC[i] = numbersA[i] + numbersB[i];
out.print(numbersC[i] + " ");
}
out.println();
try to delete the numbersC[j] = (numbersA.length[i] + numbersB.length[i]);
length from both
use this shape
numbersC[i] = numbersA[i] + numbersB[i];
i think it will be work now

How to output multiple values being stored into an array using a for loop on the same line?

I created my arrays and when I am entering the values for the arrays, they are being shown on separate lines for example...
Enter the values for the first array: 75
48
23
I would like the numbers to be shown on the same line and not sure how to do it. Thank you for your help.
public class CompareArrays
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int arraySize;
System.out.print("Enter the array size: ");
arraySize = input.nextInt();
int[] array1 = new int[arraySize];
int[] array2 = new int[arraySize];
System.out.print("Enter the values for the first array: ");
for(int i = 0; i < arraySize; i++) {
array1[i] = input.nextInt();
}
System.out.print("Enter the values for the second array: ");
for(int i = 0; i < arraySize; i++) {
array2[i] = input.nextInt();
}
if(Compare(array1, array2)) {
System.out.println("Judgement: \t The arrays are identical");
}else {
System.out.println("Judgement: \t The arrays are not identical");
}
input.close();
}
public static boolean Compare(int[] array1, int[] array2)
{
for (int i = 0; i < array1.length; i++) {
if(array1[i] != array2[i]) {
return false;
}
}
return true;
}
}
When in the console inputting those values you are hitting enter which is why it looks like it is on different lines. If you want to input the values on 1 line you could possibly input them as a string and split it.
If you're looking to just print the array on one line you can do that with a basic for loop and using System.out.print().
int[] a = {1, 2, 3, 4};
for(int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}

Creating an array that counts up to a given number

I need help creating an array that counts up to a given number. The output should look something like this:
Enter a positive integer: 8
Counting up: 1 2 3 4 5 6 7 8
Counting down: 8 7 6 5 4 3 2 1
The first 8 multiples of 5: 5 10 15 20 25 30 35 40
The first 8 multiples of 10: 10 20 30 40 50 60 70 80
Here is what I have so far:
Scanner input = new Scanner(System.in);
int[] myList = new int[1];
System.out.print("Enter a positive integer: ");
promptUser(myList);
int[] testArray = { 1, 1, 2, 3, 5, 8, 13 };
System.out.print("Test array: ");
printArray(testArray);
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
}
public static void promptUser(int[] a){
Scanner input = new Scanner(System.in);
for(int i=0; i<a.length; i++){
a[i] = input.nextInt();
}
}
public static void printArray(int[] array){
for(int i=0; i<array.length; i++)
System.out.print(array[i]);
}
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
}
Everything seems to work alright except for the last method called countingUp.
Thank you so much!
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
change this to
public static int[] countUp(int n){
int [] temp=new int[n];
for(int i=0; i<n; i++){
temp[i]=i+1;
}
return temp;
}
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
In this line change to
int[] countingUp = countUp(n);
for(int i=0;i<countingUp.length;i++){
system.out.println(countingUp[i]+" ");
}
We can start by extracting the common logic of counting by providing an initial message, the number of times to run, an initial value and an increment. Something like,
private static void count(String msg, int times, int init, int inc) {
System.out.print(msg);
for (int i = 0; i < times; i++) {
System.out.print(' ');
System.out.print(init);
init += inc;
}
System.out.println();
}
We can then implement the entirety of the requirements with something like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
System.out.flush();
do {
int num = scanner.nextInt();
count("Counting up:", num, 1, 1);
count("Counting down:", num, num, -1);
count(String.format("The first %d multiples of 5:", num), num, 5, 5);
count(String.format("The first %d multiples of 10:", num), num, 10, 10);
System.out.print("Enter a positive integer: ");
System.out.flush();
} while (scanner.hasNextInt());
}
This will produce the requested output given an input of 8, and will then prompt for more input.
First of all, If you are trying to change the Array Size Dynamically then It is NOT POSSIBLE in java Take a look # this accepted answer. I recommend you to use ARRAYLIST instead.
Although I have found below mistakes in your code. In your code I do not understand two things.
First One:
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
What is the value of n? I think it is not being initialized.
Second One:
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
What will return this function? You have not returned anything from it.
Apparently you don't need an array just follow below steps.
First create a class which handle all your calculating and counting
class SupportCounting {
public void countUp(int num) {
System.out.print("Counting up : ");
for (int i = 1; i <= num; i++) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("");
}
public void countDown(int num) {
System.out.print("Counting Down : ");
for (int i = num; i > 0; i--) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("");
}
public void printMultiple(int num, int scalefactor) {
System.out.print("First " + num + " multiples of " + scalefactor + " : ");
for (int i = 1; i <= num; i++) {
System.out.print(i * scalefactor);
System.out.print(" ");
}
System.out.println("");
}}
Then make use of that class in you main method
public class Counting {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a positive integer : ");
int n = reader.nextInt();
SupportCounting sc = new SupportCounting();
sc.countUp(n);
sc.countDown(n);
sc.printMultiple(n, 5);
sc.printMultiple(n, 10);
}}
Hope that helps

Pulling distinct values from a array in java

Have a program where the user inputs 10 int values into the array. Lastly I need to pull out the distinct values and display them. Added my second for loop which would determine if the the value is distinct (i.e. meaning if the number appears multiple times it is only displayed once).
For instance, let say I pass in the numbers: 1, 2, 3, 2, 1, 6, 3, 4, 5, 2 the distinct array should only contain numbers {1, 2, 3, 6, 4, 5}
import java.util.Scanner;
import java.io.*;
public class ArrayDistinct {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
// Create arrays & variables
int arrayLength = 10;
int[] numbers = new int[arrayLength];
int[] distinctArray = new int[arrayLength];
int count = 0;
System.out.println("Program starting...");
System.out.print("Please enter in " + numbers.length + " numbers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
for (int i = 0; i < numbers.length; i++) {
int temp = numbers[i];
int tempTwo = numbers[i + 1];
if (tempTwo == temp) {
count++;
distinctArray[i] = temp;
}
}
// Print out results
} // end main
} // end class
Try this :
Set<Integer> uniqueNumbers = new HashSet<Integer>(Arrays.asList(numbers));
uniqueNumbers will contain only unique values
In Java 8
Stream< T > distinct()
Returns a stream consisting of the distinct elements (according to
Object.equals(Object)) of this stream. For ordered streams, the
selection of distinct elements is stable (for duplicated elements, the
element appearing first in the encounter order is preserved.) For
unordered streams, no stability guarantees are made.
Code:
Integer[] array = new Integer[]{5, 10, 20, 58, 10};
Stream.of(array)
.distinct()
.forEach(i -> System.out.print(" " + i));
Output:
5,10,20,58
Read More About distinct function
Try this code.. it will work
package Exercises;
import java.util.Scanner;
public class E5Second
{
public static void main(String[] args)
{
Scanner In = new Scanner(System.in);
int [] number = new int [10];
fillArr(number);
boolean [] distinct = new boolean [10];
int count = 0;
for (int i = 0; i < number.length; i++)
{
if (isThere(number,i) == false)
{
distinct[i] = true;
count++;
}
}
System.out.println("\nThe number of distinct numbers is " + count);
System.out.print("The distinct numbers are: ");
displayDistinct(number, distinct);
}
public static void fillArr(int [] number)
{
Scanner In = new Scanner(System.in);
System.out.print("Enter ten integers ");
for (int i = 0; i < number.length; i++)
number[i] = In.nextInt();
}
public static boolean isThere(int [] number, int i)
{
for (int j = 0; j < i; j++)
if(number[i] == number[j])
return true;
return false;
}
public static void displayDistinct(int [] number, boolean [] distinct)
{
for (int i = 0; i < distinct.length; i++)
if (distinct[i])
System.out.print(number[i] + " ");
}
}
One possible logic: If you're supposed to only sort out "unique" numbers, then you'll want to test each number as it's entered and added to the first array, and loop through the array and see if it's equal to any of the numbers already there; if not, add it to the "unique" array.
Sets in java doesn't allow duplicates:
Integer[] array = new Integer[]{5, 10, 20, 58, 10};
HashSet<Integer> uniques = new HashSet<>(Arrays.asList(array));
That's it.
Something like this should work for you:
Scanner input = new Scanner(System.in);
// Create arrays & variables
int arrayLength = 10;
int[] numbers = new int[arrayLength];
int[] distinctArray = new int[arrayLength];
int count = 0;
Set<Integer> set = new HashSet<Integer>();
System.out.println("Program starting...");
System.out.print("Please enter in " + numbers.length + " numbers: ");
for (int i = 0; i < numbers.length; i++) {
set.add(input.nextInt());
}
for(Integer i : set)
{
System.out.println("" + i);
}
This will only add unique values to the set.
int a[] = { 2, 4, 5, 3, 3, 3, 4, 6 };
int flag = 0;
for (int i = 0; i < a.length; i++)
{
flag = 0;
for (int j = i + 1; j < a.length; j++)
{
if (a[i] == a[j])
{
flag = 1;
}
}
if (flag == 0)
{
System.out.println(a[i]);
}
}

10 element Array will only accept 5 integers during Selection sort project

Ok, so this is for a Java class, but I'm not looking for someone to write the code, just help me debug this one. I want to enter 10 integers and have the inputs sorted in ascending order as they are entered then displayed, without any zeros (0) that may exist in the array.
Example of what the assignment should look like:
Enter 10 integers - one at a time...
Enter integer #1: 21
Sorted numbers: 21
Enter integer #2: 48
Sorted numbers: 21 48
Enter integer #3: 37
Sorted numbers: 21 37 48
etc....
I have tried a Selection Sort, Insertion and Bubble Sort, but the array will not hold or display more than 5 numbers.
Help.
Here is my Main:
import java.util.*;
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int j = 1;
int[] list = new int[10];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length; i++){
System.out.print("Enter integer #" + j + ": ");
list[i] = input.nextInt();
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for(int p= 0; p<list.length; p++){
if (list[p] !=0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}
Here is my Selection Sort:
public class SelectionSort {
public static void sort (int[] list){
for(int i=0; i<list.length; i++)
{
for(int j=i+1; j<list.length; j++)
{
if(list[i] > list[j] )
{
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}
}
}
Thanks in advance!
Why don't you use List insteed of array and ready-to-go sorting implementations from jdk -> Collections.sort() ?
Anyway the problem is that you are inserting new integers into already sorted array and that causes disfunction of your code. So as you inserting new elements on indexes 0,1,2,3,4 - sorting algorithm moves them to positions 5,6,7,8,9. From this point your inputs starts overriding sorted values with new ones from input - (Main loop i>=5).All in all, it accepted 10 integers, but 5 of them where kindly overriten.
Here is little modified version of your work whitch works like you want. Analyze it!
import java.util.*;
public class test {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int j = 1;
int[] list = new int[11];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length - 1; i++) {
System.out.print("Enter integer #" + j + ": ");
list[0] = input.nextInt();
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for (int p = 1; p < list.length; p++) {
if (list[p] != 0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}
class SelectionSort {
public static void sort(int[] list) {
for (int i = 0; i < list.length; i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[i] > list[j]) {
int temp = list[j];
list[j] = list[i];
list[i] = temp;
i--;
break;
}
}
}
}
}
You are replacing sorted value with list[i] = input.nextInt(); with every input. So, 5 values always 0 in list. Use List<Integer> instead of int[] and add new value to List<Integer>. Try following code:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int j = 1;
List<Integer> list = new ArrayList<>();
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < 10; i++){
System.out.print("Enter integer #" + j + ": ");
list.add(input.nextInt());
j++;
//SortMethod.sort(list, list.length);
// SelectionSort.sort(list);
Collections.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for(int p= 0; p<list.size(); p++){
if (list.get(p) !=0)
System.out.print(list.get(p) + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
I just modified the lines below the comments I put (temp declaration and for loop).
This changes makes program support negative numbers too, read the comments below:
import java.util.*;
public class test {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int j = 1;
int[] list = new int[11];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length - 1; i++) {
System.out.print("Enter integer #" + j + ": ");
// Add temporal variable to store input
int temp = input.nextInt();
// Check for empty place in list (as far as it seems you don't care about zeros)
for (int p = 0; p < list.length; p++) {
if (list[p] == 0) {
list[p] = temp;
break;
}
}
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for (int p = 1; p < list.length; p++) {
if (list[p] != 0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}

Categories