How to print every third element of Array? - java

I need to take 2 inputs from user size of array and then elements of that same array.
I need to print every third element of array.
Example Array: 1,2,3,4,5,6,7,8,9
Desired output: 3,6,9
Getting: 9,6,3
class Demo {
public static void main(String[] args) {
int x;
int[] y;
Scanner tastatura = new Scanner(System.in);
System.out.println("Enter size of array:");
x = tastatura.nextInt();
y = new int[x];
System.out.println("Enter the elements of array:");
for (int i = 0; i < x; i++) {
y[i] = tastatura.nextInt();
}
System.out.println("\n Every third element of array is : ");
for (int i = y.length - 1; i >= 0; i = i - 3) {
System.out.println(y[i]);
}
tastatura.close();
}

You were close! You just have the iteration order reversed!
for (int i = y.length - 1; i >= 0; i = i - 3) {
System.out.println(y[i]);
}
Should be:
for (int i = 2; i < y.length; i += 3) {
System.out.println(y[i]);
}
Take note that this can throw an ArrayIndexOutOfBoundsException if your array does not contain at least 3 elements, so you should handle that somewhere.

use the modulus operator to find each 3rd item.
example
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0

for (int i =0 ; i < y.length - 1; i = i + 3) {
System.out.println(y[i]);
}
The way you are printing is in reverse order .. Correct that

You are on the right track I would strongly recommend using a modulus:
for (int i = 0; i < y.length; i++) {
if(i%3==0){
System.out.println(y[i]);
}//if statement
}//for loop

Related

changing value of the last 3 index in an array

i am currently learning java, bellow are my current code
import java.util.*;
public class numbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How big is the array: ");
int size = input.nextInt();
int[] numb = new int[size];
for (int i=0;i<size;i++)
{
numb[i] = i;
}
//change value of last 3 index of array to 0
for (int i =0; i<size;i++)
{
System.out.println(numb[i]);
}
}
}
Here are how the output if i ran it currently
How big is the array: 7
0
1
2
3
4
5
6
how could i change the value of the last 3 index to 0? bellow are my expected output
How big is the array: 7
0
1
2
3
0
0
0
thanks in advance!
You can loop through the last 3 index and set it to 0.
for (int i = 1; i <= 3; i++) {
num[num.length - i] = 0;
}
You mean?
//change value of last 3 index of array to 0
for (int i = size-1; i >= size-3;i--)
{
numb[i] = 0;
}
//OR
for (int i = size-2; i<size;i++)
{
numb[i] = 0;
}
for (int i = 0; i<size;i++)
{
System.out.println(numb[i]);
}
This should do the trick:
//change value of last 3 index of array to 0
if (size <= 3) {
for (int i =0; i<size;i++)
{
numb[i] = 0;
}
} else {
for (int i=size-3; i<size; i++) {
numb[i] = 0;
}
}
Just subtract 3 from the size, it will work perfectly
for (int i=0;i<size-3;i++)
{
numb[i] = i;
}

Why is there an element that is not being displayed?

I am practicing creating a randomly generating integers in an array, then randomizing the elements in the array. All is well when I print the numbers, but there seems to be one element that does not print when I am displaying the randomized elements. Is there a step I am leaving out?
public class shufflingArrays {
public static void main(String[] args) {
int[] myList = new int[10];
System.out.println("Numbers:");
for(int i = 0; i < myList.length; i++) {
myList[i] = (int)(Math.random() * 100);
System.out.print(myList[i] + " ");
}
System.out.println("\nRandomized:");
for (int i = myList.length - 1; i > 0; i--){
//Generate index j randomly with 0 <= j <= i
int j = (int)(Math.random() * (i + 1));
//Swap myList[i]; with myList[j]
int temp = myList[i];
myList[i] = myList[j];
myList[j] = temp;
System.out.print(myList[i] + " ");
}
}
Your for loop has condition i > 0, which means when i == 0 it will terminate and not print out the first array element.
However, if you're doing the Fisher-Yates shuffle, as it appears, you do indeed need to go from myList.length-1 to 1, so your initial code was correct. You then can't print out all the elements in the array from the same loop, so either use another loop after to print out the elements, or add System.out.print(myList[0]); after.
Ex: for (int i = 4; i > 0; i--)
will run the for loop when i = 4, 3, 2, 1 only and not when i = 0, because the condition there is i > 0. Change the i > 0 condition in for (int i = myList.length - 1; i > 0; i--) to i >= 0 and you will get what you want.

Generating non-duplicate numbers using Arrays, not ArrayList<> in Java

I'm doing the old Lotto exercise and I need to specifically use an Array[] of integers and not an ArrayList. I have what I thought would work, but I seem to be wrong. I looked for posts similar to these and all of them involved an ArrayList<>. Here is a partition of my code.
Integer[] lottoNums;
lottoNums = new Integer[7];
for(int i = 0; i < lottoNums.length; i++){
lottoNums[i] = randomNums.nextInt((59)+1);
if(i <= 5) {
if(lottoNums[i].equals(lottoNums[i+1])){
if(lottoNums[i] < 58 && lottoNums[i] > 1)
lottoNums[i] = lottoNums[i] +1;
}
}
else if(i >= 1) {
if(lottoNums[i].equals(lottoNums[i-1])){
if(lottoNums[i] < 58 && lottoNums[i] > 1)
lottoNums[i] = lottoNums[i] +1;
}
}
}
Arrays.sort(lottoNums);
System.out.print("Winning numbers: "+lottoNums[0]);
for (int i = 1; i < 6; i++) {
System.out.print(", " + lottoNums[i]);
}
System.out.print(System.getProperty("line.separator"));
System.out.println("Bonus Number: "+lottoNums[6]);
I need to get it to generate a number in between 1 and 59 and not duplicate. I was trying to pair it up with the value stored in the element before and after it (if it had one) and if it was equal to it, it would add 1 to it. I run it a few times and every once in a while im still getting duplicate numbers. How can i do this efficiently, using Arrays[] of integers ONLY?
EDIT:
Initialized array to remove NullPointerException.
Updated Code:
for(int i = 0; i < lottoNums.length; i++){
lottoNums[i] = randomNums.nextInt((59)+1);
}
for (int i = 0; i < 6; i++) {
int rnd = randomNums.nextInt((lottoNums).length-i);
int k = lottoNums[lottoNums.length-i-1];
lottoNums[lottoNums.length-i-1] = lottoNums[rnd];
lottoNums[rnd] = k;
}
Arrays.sort(lottoNums);
System.out.print("Winning numbers: "+lottoNums[0]);
//PRINTING LOTTO NUMBERS
for (int i = 1; i < 6; i++) {
System.out.print(", " + lottoNums[i]);
}
System.out.print(System.getProperty("line.separator"));
System.out.println("Bonus Number: "+lottoNums[6]);
You can do this by switching the selected number with the last number in the array each time, and then selecting the next from the prefix you have not yet stored:
for (int i = 0; i < 6; i++) {
int rnd = randomNums.nextInt(numbers.length-i);
int k = numbers[numbers.length-i-1];
numbers[numbers.length-i-1] = numbers[rnd];
numbers[rnd] = k;
}
At the end of this loop your selected numbers will be in numbers[numbers.length-7..numbers.length-1], etc.
I would use two arrays. Each time you draw a number see if it exists in the second array. If not use it and add it to the second array.

Java arrays how to save it in the array

How do I save it actually in the Array?
With this code it doesn't save anything in the array
I hope you can tell me more ways how to do it and explain in detail, thank you very much
import java.util.Scanner;
public class CountArray
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
int countPOZ = 0;
int countP5 = 0;
int countNONE = 0;
System.out.println();
System.out.print("Type elements: ");
int[] x = new int [scan.nextInt()];
for(int i = 0; i < x.length; i++)
{
System.out.print("Type numbers: ");
int numrat = scan.nextInt();
if(numrat > 0)
countPOZ++;
else if (numrat % 5 == 0)
countP5++;
else
countNONE++;
}
System.out.println();
System.out.println(x[1]); //here it will display 0 because nothing is saved.. in the array
System.out.println("Positive: "+countPOZ);
System.out.println("Div.. with 5: "+countP5);
System.out.println("Others: "+countNONE);
}
}
You store a value in the ith position of your x array with:
x[i] = someValue;
In the context of your loop :
for(int i = 0; i < x.length; i++)
{
System.out.print("Type numbers: ");
int numrat = scan.nextInt();
if(numrat > 0)
countPOZ++;
else if (numrat % 5 == 0)
countP5++;
else
countNONE++;
x[i] = numrat;
}
This stores the user's input in order.
x[i] = scan.nextInt();
Remove the local numrat and use x[i]. And please use braces, something like
x[i] = scan.nextInt();
if(x[i] > 0) {
countPOZ++;
} else if (x[i] % 5 == 0) {
countP5++;
} else {
countNONE++;
}
This is covered in and an example to JLS-10.4 - Array Access.
A component of an array is accessed by an array access expression (ยง15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++) ia[i] = i;
int sum = 0;
for (int e : ia) sum += e;
System.out.println(sum);
}
}
Try, add values in array then use array for business logic.
int[] x = new int [scan.nextInt()];
for(int i = 0; i < x.length; i++){
System.out.print("Type numbers: ");
x[i] = scan.nextInt();
if(x[i] > 0)
countPOZ++;
else if (x[i] % 5 == 0)
countP5++;
else
countNONE++;
}
But you missing something int[] x = new int [scan.nextInt()] as per your code you are not passing only one element and add that element to your array.
I assist pass multiple elements as comma separated list 1,2,3,4,5,6,7 then in your code you can create array list int x[] = scan.nextInt().split(",") then use it.
in your code
int[] x = new int [scan.nextInt()];
you are defining the size of an array. you are not storing any elements in here.
So define any elements in an array you have to access it's index and store your value in that specific index
x[1] = scan.nextInt()
can store the values in specific index

How do I sort numbers from an array into two different arrays in java?

I have to create a program that takes an array of both even and odd numbers and puts all the even numbers into one array and all the odd numbers into another. I used a for loop to cycle through all the numbers and determine if they are even or odd, but the problem I'm having is that since the numbers in the original array are random, I don't know the size of either the even or the odd array and therefore can't figure out how to assign numbers in the original array to the even/odd arrays without having a bunch of spots left over, or not having enough spots for all the numbers. Any ideas?
Try using an ArrayList. You can use
num % 2 == 0
to see if num is even or odd. If it does == 0 then it is even, else it is odd.
List<Integer> odds = new ArrayList();
List<Integer> evens = new ArrayList();
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evens.add(array[i]);
}
else {
odds.add(array[i]);
}
}
to convert the ArrayLists back to arrays you can do
int[] evn = evens.toArray(new Integer[evens.size()]);
(Note: untested code so there could be a few typos)
EDIT:
If you are not allowed to use ArrayLists then consider the following that just uses Arrays. It's not as efficient as it has to do two passes of the original array
int oddSize = 0;
int evenSize = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenSize++;
}
else {
oddSize++;
}
}
Integer[] oddArray = new Integer[oddSize];
Integer[] evenArray = new Integer[evenSize];
int evenIdx = 0;
int oddIdx = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenArray[evenIdx++] = array[i];
}
else {
oddArray[oddIdx++] = array[i];
}
}
You can do it without using arrays or any '%' Just a simple idea
input = new Scanner(System.in);
int x;
int y = 0; // Setting Y for 0 so when you add 2 to it always gives even
// numbers
int i = 1; // Setting X for 1 so when you add 2 to it always gives odd
// numbers
// So for example 0+2=2 / 2+2=4 / 4+2=6 etc..
System.out.print("Please input a number: ");
x = input.nextInt();
for (;;) { // infinite loop so it keeps on adding 2 until the number you
// input is = to one of y or i
if (x == y) {
System.out.print("The number is even ");
System.exit(0);
}
if (x == i) {
System.out.print("The number is odd ");
System.exit(0);
}
if (x < 0) {
System.out.print("Invald value");
System.exit(0);
}
y = y + 2;
i = i + 2;
}
}
Use a List instead. Then you don't need to declare the sizes in advance, they can grow dynamically.
You can always use the toArray() method on the List afterwards if you really need an array.
The above answers are correct and describe how people would normally implement this. But the description of your problem makes me think this is a class assignment of sorts where dynamic lists are probably unwelcome.
So here's an alternative.
Sort the array to be divided into two parts - of odd and of even numbers. Then count how many odd/even numbers there are and copy the values into two arrays.
Something like this:
static void insertionSort(final int[] arr) {
int i, j, newValue;
int oddity;
for (i = 1; i < arr.length; i++) {
newValue = arr[i];
j = i;
oddity = newValue % 2;
while (j > 0 && arr[j - 1] % 2 > oddity) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = newValue;
}
}
public static void main(final String[] args) {
final int[] numbers = { 1, 3, 5, 2, 2 };
insertionSort(numbers);
int i = 0;
for (; i < numbers.length; i++) {
if (numbers[i] % 2 != 0) {
i--;
break;
}
}
final int[] evens = new int[i + 1];
final int[] odds = new int[numbers.length - i - 1];
if (evens.length != 0) {
System.arraycopy(numbers, 0, evens, 0, evens.length);
}
if (odds.length != 0) {
System.arraycopy(numbers, i + 1, odds, 0, odds.length);
}
for (int j = 0; j < evens.length; j++) {
System.out.print(evens[j]);
System.out.print(" ");
}
System.out.println();
for (int j = 0; j < odds.length; j++) {
System.out.print(odds[j]);
System.out.print(" ");
}
}
Iterate through your source array twice. The first time through, count the number of odd and even values. From that, you'll know the size of the two destination arrays. Create them, and take a second pass through your source array, this time copying each value to its appropriate destination array.
I imagine two possibilities, if you can't use Lists, you can iterate twice to count the number of even and odd numbers and then build two arrays with that sizes and iterate again to distribute numbers in each array, but thissolution is slow and ugly.
I imagine another solution, using only one array, the same array that contains all the numbers. You can sort the array, for example set even numbers in the left side and odd numbers in the right side. Then you have one index with the position in the array with the separation ofthese two parts. In the same array, you have two subarrays with the numbers. Use a efficient sort algorithm of course.
Use following Code :
public class ArrayComparing {
Scanner console= new Scanner(System.in);
String[] names;
String[] temp;
int[] grade;
public static void main(String[] args) {
new ArrayComparing().getUserData();
}
private void getUserData() {
names = new String[3];
for(int i = 0; i < names.length; i++) {
System.out.print("Please Enter Student name: ");
names[i] =console.nextLine();
temp[i] = names[i];
}
grade = new int[3];
for(int i =0;i<grade.length;i++) {
System.out.print("Please Enter Student marks: ");
grade[i] =console.nextInt();
}
sortArray(names);
}
private void sortArray(String[] arrayToSort) {
Arrays.sort(arrayToSort);
getIndex(arrayToSort);
}
private void getIndex(String[] sortedArray) {
for(int x = 0; x < sortedArray.length; x++) {
for(int y = 0; y < names.length; y++) {
if(sortedArray[x].equals(temp[y])) {
System.out.println(sortedArray[x] + " " + grade[y]);
}
}
}
}
}

Categories

Resources