Comparing Every Odd Number with Every Even Number - java

I am separating the Odd Numbers and Even Numbers from an Arrays.
My Code is:
public class EvenAndOdd {
public static void main (String[] args)
{
int countEven = 0;
int countOdd = 0;
int[] myArray = {1, 2, 3, 4, 5, 6, 7};
for(int i : myArray) {
if(i%2 == 0) {
countEven++;
System.out.println("EVEN numbers: " + i);
}
else {
countOdd++;
System.out.println("ODD numbers: " + i);
}
}
System.out.println("Total Even Number: " + countEven);
System.out.println("Total Odd Number " + countOdd);
}
}
Getting correct result from above Code. But i want to now compare every Odd Number with Every Even Number, if any of Even number is greater than odd Number then return o and no odd Number is greater than Even number return 1.

code is as below
for(int i=0;i<myArray.length;i+=2)
{
j=i+1; //odd number
//if even number is greater
if(myArray[i]>=myArray[j])
System.out.println(1);
else //if odd is greater
System.out.println(0);
}

I don't understand "if any even number is greater than an odd number return 0" and "if no odd number greater than even return 1" because there is a 7 which is greater than, say 2, but there is a 4 which is greater than 3, or 1. So this means both cases match so there is a flaw in your logic, or poor phrasing of the question. In any case, you might find this useful
import java.util.*;
import java.lang.*;
import java.io.*;
class EvenAndOdd{
public static void main(String[] args){
int countEven = 0;
int countOdd = 0;
int result = 0;
int[] myArray = {1, 2, 3, 4, 5, 6, 7};
List<Integer> evens = new ArrayList<Integer>();
List<Integer> odds = new ArrayList<Integer>();
for(int i : myArray){
if(i%2 == 0) {
countEven++;
System.out.println("EVEN numbers: " + i);
evens.add(i);
}
else {
countOdd++;
System.out.println("ODD numbers: " + i);
odds.add(i);
}
}
for(int i : evens){
for(int j : odds){
if(i > j)
result = 1;
else
result = 0;
}
}
System.out.println("Result: " + result );
}
}

Related

linear search for multiple integers

Im trying to implement a linear search for an array of integers that if the number is a multiply of 3 its going to print the index of the number in the array and if there is no any number that is a multiple of 3 its going to return -1
im trying to implement this without using a method for it and my problem is how im going to do the printing/returning of -1?
knowing that my code is
int[] a = {3, 5, 22, 7, 9, 8, 21};
System.out.println("the index of 3 multiplies is" );
for (int i = 0; i < a.length; i++) {
if (a[i] % 3 == 0) {
System.out.print(i + " ");
continue;
}
}
You could use a boolean found = false and set it to true if the algorithm found a multiply of 3. After the for loop you could ask for result.
int[] a = {3, 5, 22, 7, 9, 8, 21};
int multipleOfThree = 0;
System.out.println("the index of 3 multiplies is" );
for (int i = 0; i < a.length; i++) {
if (a[i] % 3 == 0) {
System.out.print(i + " ");
multipleOfThree++;
}
}
if( multipleOfThree == 0 ){
System.out.println(-1);
}
I think this is what you are looking for. If you want to use a method, instead of printing the multipleOfThree, you should return it.
int[] a = {1,5,22,7,52,8,20};
System.out.println("the index of 3 multiplies is" );
boolean found = false;
for(int i = 0; i<a.length;i++){
if(a[i]%3==0){
found = true;
System.out.println(i+" ");
}
}
if(!found){
System.out.println("-1");
}
}``

A Java program that gets an integer, separates the individual digits and gives the sum of the digits

Below is my code, I have been able to get the sum of the digits, but I don't know how to cleanly separate and print the individual digits of my integer. Can it be done within my 'do' loop?
import java.util.*;
public class Ch5PgEx1 {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int num;
int sum;
int remainder;
int count;
System.out.print("Please enter an integer: ");
num = console.nextInt();
System.out.println();
sum = 0;
count = 0;
do {
remainder = num % 10;
sum = sum + remainder;
num = num / 10;
count++;
}
while (num > 0);
System.out.print("There are " + count + " digits in your number. \nThe sum of the individual digits is:" + sum);
System.out.println();
}
}
To print them just add the print line
do {
remainder = num % 10;
sum = sum + remainder;
num = num / 10;
count++;
System.out.println(remainder);
} while (num > 0);
/*
Please enter an integer: 123456789
9
8
7
6
5
...
To store them in an array
int[] res = new int[Integer.toString(num).length()];
do {
remainder = num % 10;
sum = sum + remainder;
num = num / 10;
res[count++] = remainder; // LINE 1
} while (num > 0);
/*
Please enter an integer: 123456789
[9, 8, 7, 6, 5, 4, 3, 2, 1]
...
To have the array in [1, 2, 3, 4, 5, 6, 7, 8, 9] way :
way change LINE 1 to res[res.length - ++count] = remainder;
Not entirely sure if this would be something you'd be looking for. It does simplifies your code and it builds the array based on the remainders:
Integer Array
int arraySize = String.valueOf(num).length();
List<Integer> collectList = IntStream.range(0, arraySize).map(i -> (int) (num / Math.pow(10, i) % 10)).boxed()
.collect(Collectors.toList());
Integer[] collect = collectList.toArray(new Integer[0]);
System.out.print("There are " + collectList.size()
+ " digits in your number. \nThe sum of the individual digits is:" + collectList.stream()
.reduce(Integer::sum).orElse(0));
System.out.println();
Character Array
And if you want with characters, maybe this would also help you:
int arraySize = String.valueOf(num).length();
List<Integer> collectList = IntStream.range(0, arraySize).map(i -> (int) (num / Math.pow(10, i) % 10)).boxed()
.collect(Collectors.toList());
Character[] collect = collectList.stream().map(number -> String.valueOf(number).charAt(0))
.toArray(Character[]::new);
System.out.print("There are " + collectList.size()
+ " digits in your number. \nThe sum of the individual digits is:" + collectList.stream()
.reduce(Integer::sum).orElse(0));
System.out.println();
Well, I have made a quick example for you. Take a look at it.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Pleaseee, input your numbers.");
String text = scanner.nextLine();
int[] arrayOfNumbers = new int[text.length()];
for (int i = 0; i < text.length(); i++) {
arrayOfNumbers[i] = text.charAt(i) - '0';
}
/*
// prints every number
for( int number : arrayOfNumbers){
System.out.printf(" %s ",number);
}
*/
// sums every number
int sumOfNumbers = IntStream.of(arrayOfNumbers).sum();
String listOfNumbers = IntStream.of(arrayOfNumbers).mapToObj(Integer::toString).collect(Collectors.joining(", "));
System.out.printf("Ho-ho-ho! List of numbers is: %s \n", listOfNumbers);
System.out.printf("Ho-ho-ho! The sum of your numbers is: %d \n", sumOfNumbers);
}

Java - Searching an element in a random array

I executed the following code:
import java.util.Scanner;
public class Linear_Search {
public static void main(String[] args) {
int arr[] = new int[20];
for(int i = 0; i < arr.length; i++) {
arr[i] = (int)(Math.random() * 10) + 1;
}
System.out.print("Array is: ");
for(int i : arr)
System.out.print(arr[i] + " ");
//int arr[]= {1,2,4,5,6,7,8,43,6,4,2,6,8,3};
System.out.println();
System.out.println("Enter the number you want to search");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
boolean found = false;
String indices = "";
for(int i = 0; i < arr.length; i++) {
if(num == arr[i]) {
found = true;
indices = indices + i + ", ";
}
}
if(found == false) {
System.out.println(num + " does not exist");
}
else {
System.out.println(num + " found at index: " + indices.substring(0, indices.length() - 2));
}
sc.close();
}
}
Output:
Array is: 3 3 1 2 8 1 2 2 3 1 3 3 7 1 7 3 1 3 8 3
Enter the number you want to search
2
2 found at index: 0, 1, 8 ,15
Why is this displaying random indices as answers. The code works fine when i use a custom array like the one that is commented in the code. Is it related to explicit cast on Math.random() or something else?
You are mislead by the loop printing the array, which doesn't really print the array elements.
Change:
for(int i : arr)
System.out.print(arr[i] + " ");
to:
for(int i : arr)
System.out.print(i + " ");
and you'll see the actual array values.
When you iterate over an array with the enhanced for loop, you are iterating over the array values not over the array indices.

Check for perfect number using boolean

I have problem with my Java coding to find the perfect number using boolean method. I want to print out like this:
Example :
‘6 is a perfect number. 6 is the sum of 1, 2, 3’
Otherwise :
‘9 is not a perfect number’
But I don't know how to make the coding for "6 is the sum of 1, 2, 3". Can anyone help me?
Here is my coding :
import java.util.Scanner;
public class trial
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner perfect = new Scanner(System.in);
System.out.print("Enter any integer number : ");
int n = perfect.nextInt();
if(isPerfectNumber(n))
{
System.out.println(n+" is a perfect number");
}
else
{
System.out.println(n+" is not a perfect number");
}
}
public static boolean isPerfectNumber(int n)
{
int sum = 0;
for (int i=1; i<n; i++)
{
if (n%i == 0)
{
sum = sum + i;
}
}
if (sum == n)
{
return true;
}
else
{
return false;
}
}
}
Well, you already know how to get the factors of the number, as per the if (n%i == 0) line.
So, hint only since this is almost certainly class work.
At the same point you add the factor to the sum, you should add it to a list of some description and have that made available to the calling function.
One possibility would be to return a list, the second and subsequent elements being all the factors of the given number, and the first element being the sum of those.
So, for 6, you would get the list {6, 1, 2, 3}, 12 would give you {16, 1, 2, 3, 4, 6}, and 7 would give you {7, 1}.
That way, you simply have to check the original number against the first element and, if they're equal, print out the other elements. In other words, pseudo-code such as:
input num
factorList = getFactorList(num)
if factorList[0] == num:
print num, " is perfect, factors are:"
for idx = 1 to factorList.size() - 1 inclusive:
print " ", factorList[idx]
println "."
else:
println num, " is not perfect."
I'd change isPerfectNumber to return a List of the factors that make n or null if it's not a perfect number. Then you have a single result that both contains factors and can be used to determine if n is perfect:
public static void main(String[] args) {
Scanner perfect = new Scanner(System.in);
System.out.print("Enter any integer number : ");
int n = perfect.nextInt();
List<Integer> factors = getPerfectFactors(n);
if (factors != null) {
System.out.println
(n + " is a perfect number. It's the sum of" +
factors.stream()
.map(String::valueOf)
.collect(Collectors.joining(", "));
} else {
System.out.println(n+" is not a perfect number");
}
}
public static List<Ingeger> getPerfectFactors(int n) {
int sum = 0;
List<Ingeger> factors = new LinkedList<>();
for (int i = 1; i < n; i++) {
if (n % i == 0) {
sum += i;
factors.add(i);
}
if (sum > n) { // Early return optimization, not material to the solution
return null;
}
}
if (sum == n) {
return factors;
} else {
return null;
}
}
Well in the for loop if condition if modulus is true then you know the i has to be kept in track somehow.
So I would
declare an arraylist of integers to keep track of summation numbers.
ArrayList<Integer> numbs = new ArrayList<Integer>();
Then
public static boolean isPerfectNumber(int n)
{
int sum = 0;
for (int i=1; i<n; i++)
{
if (n%i == 0)
{
numbs.add(i); //here keep track of those summation numbers
sum = sum + i;
}
}
if (sum == n)
{
return true;
}
else
{
return false;
}
}
Now while printing you can do like
System.out.println(n + " is a perfect number. " + n + " is sum of " + StringUtils.join(numbs, ","));
Don't forget to import StringUtils: import org.apache.commons.lang3.StringUtils commons-lang3 library.

I want this code to separate even and odd numbers

It prints all the even numbers, but is only printing the odd numbers 13 and 11. Not 3 or 5. Does anyone know what I am doing wrong? Thanks in advance.
public class ReadjustingArray {
public static void main (String[]args){
int[]A={13,3,4,6,8,5,10,11};
int temp=0;
for (int i=0; i< A.length; i++){
if (A[i] % 2 ==0){
temp=A[i];
A[i-1] = A[i];
temp=A[i];
System.out.print(A[i] + " ");
}
}
for (int j=0; j< A.length; j++){
if (A[j] % 2 !=0){
System.out.print(A[j] + " ");
}
}
}
}
Don't modify the array with your first loop, then your second loop will work as you expect. Alternatively, in Java 8+, you might use IntStream and filter like
int[] A = { 13, 3, 4, 6, 8, 5, 10, 11 };
IntStream.of(A).filter(x -> x % 2 == 0)
.forEachOrdered(x -> System.out.printf("%d ", x));
IntStream.of(A).filter(x -> x % 2 != 0)
.forEachOrdered(x -> System.out.printf("%d ", x));
System.out.println(); // <-- Adds a new line (and an implicit flush)
this can help you.
public static void main(String[] args) {
int[] A = { 13, 3, 4, 6, 8, 5, 10, 11 };
for (int i : A) {
if (isEven(i)) {
System.out.println(i + " is even");
} else {
System.out.println(i + " is odd");
}
}
}
static boolean isEven(int number) {
if ((number % 2) == 0) {
return true;
}
return false;
}
There is no need to modify the Array. Just print the odds in the same way you are printing the evens. Use their corresponding comparative logic.

Categories