I'm trying to solve a problem where I need to find all the even numbers only. I need to input 5 numbers, and if none of the numbers are even I want to print Even number not found in array.
So my problem is when I iterate through the for-loop, my code prints Even number not found in array. It prints for each non-even number, which is not what its suppose to do obviously. I need some kind of hint. This is not homework btw, it is a problem found on Programmr.com. Here is my code:
import java.util.Scanner;
public class ArrayEven {
public static void main(String args[]) {
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int x, arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
if (i == 4)
break;
}
for (int i = 0; i < arr.length; i++) {
x = arr[i] % 2;
if (x == 0) {
System.out.println(arr[i]);
}
else if (x != 0) { //this is obviously wrong. Do I need another for-loop for this?
System.out.println("Even number not found in array.");
}
}
}
}
You can use a boolean here,
Initialize boolean variable with false
if you found any even than set the boolean as true
and check that boolean in your if condiion.
Example :
boolean isAvailble = false;
...
// Some code
...
for (int i = 0; i < arr.length; i++) {
x = arr[i] % 2;
if (x == 0) {
System.out.println(arr[i]);
isAvailble = true;
}
}
if (! isAvailable) {
System.out.println("Even number not found in array.");
}
public static void main(String args[]) {
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int x, arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
if (i == 4)
break;
}
boolean evenFound = false;
for (int i = 0; i < arr.length; i++) {
x = arr[i] % 2;
if (x == 0) {
System.out.println(arr[i]);
evenFound = true;
}
}
if(!evenFound){
System.out.println("Not found");
}
}
Related
I am making a program that is going to print out based on who is the winner. (More details about
the task in the link) https://open.kattis.com/problems/vote
I have trouble with printing out "no winner" at the right value. I am tryng to print out "no winner" only when all elements in my arrayList is the same. ex.
arr = [10, 10, 10]
then print out:
"no winner"
How do i check if all elements in a arrayList is equal?
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class B {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int testCase = sc.nextInt();
for (int i = 0; i < testCase; i++ ) {
int candidate = sc.nextInt();
int maximum = 0;
int winner = 0;
boolean tie = false;
ArrayList<Integer> votes = new ArrayList<>();
for (int j = 0; j < candidate; j++) {
int nVotes = sc.nextInt();
votes.add(nVotes);
}
int imax = votes.indexOf(Collections.max(votes));
int max = Collections.max(votes); // max winner
int in = votes.indexOf(votes);
int index = imax + 1;
int sum = 0;
for(int o = 0; o < votes.size(); o++)
{
sum = sum + votes.get(o);
if (votes.get(o) == votes.get(o) ) {
tie = true;
}
}
if (max > (sum / 2)) {
System.out.println("majority winner " + index);
}
else if (max < (sum / 2)) {
System.out.println("minority winner " + index);
}
else if (votes.get(i) == votes.get(i)) {
System.out.println("no winner");
}
}
}
}
Try using what you've done to set the tie case to true, like:
else if (tie == true) {
System.out.println("no winner");
}
I want to create a program that will ask the user to input 5 integers using array and determine all the prime numbers entered. But I have difficulty with it. What seems to be the problem? I use JCreator for this.
import java.util.Scanner;
public class PrimeNumbers{
public static void main (String[] args){
int[] array = new int [5];
Scanner in = new Scanner (System.in);
System.out.println("Enter the elements of the array: ");
for(int i=0; i<5; i++)
{
array[i] = in.nextInt();
}
//loop through the numbers one by one
for(int i=0; i<array.length; i++){
boolean isPrime = true;
//check to see if the numbers are prime
for (int j=2; j<array[i]; j++){
if(array[i]%j==0){
isPrime = false;
break;
}
}
//print the number
if(isPrime)
System.out.println(array[i] + " are the prime numbers in the array ");
}
}
}
You are checking the loop counters, not the values in the array. Try something like
for (int j=2; j<array[i]; j++){
if(array[I]%j==0){
isPrime = false;
break;
}
I haven't tested this.
UPDATE
To print out the results either print each on as it is found, or, copy the prime numbers into an output array and then print that when you have finished the checks. The details will depend on the language you are using.
Please note, you are not using a very efficient detection algorithm; Google for a better one.
You can check all integer numbers until root of the required number
Pseudo code:
for(i=2; i<sqrt(number);i++){
if(number/i===0){
//not prime number
}
}
Find all prime numbers from the array.
package com.myfirstproject;
public class array_Uni_work {
public static void main(String[] args) {
int[] array = {6,48,47,7 , 98,51,87,99,2,0,1,191,157};
// loop through the numbers one by one
for (int i = 0; i < array.length; i++) {
boolean isPrime = true;
if (array[i] == 1)
isPrime = false;
else {
// check to see if the numbers are prime
for (int j = 2; j <= array[i] / 2; j++) {
if (array[i] % j == 0) {
isPrime = false;
break;
}
}
}
// print the number
if (isPrime){
if (array[i] == 0){}
else {
System.out.print(array[i] + " , ");
}
}}
System.out.println(" Are the prime number in the array ");
}
}
public static void main(String[] args) {
int[] array = new int[5];
Scanner in = new Scanner(System.in);
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < 5; i++) {
array[i] = in.nextInt();
}
// loop through the numbers one by one
for (int i = 0; i < array.length; i++) {
boolean isPrime = true;
if (array[i] == 1)
isPrime = false;
else {
// check to see if the numbers are prime
for (int j = 2; j <= array[i] / 2; j++) {
if (array[i] % j == 0) {
isPrime = false;
break;
}
}
}
// print the number
if (isPrime)
System.out.println(array[i] + " is a prime number in the array ");
}
}
Here is more efficient code finding prime number. We only need to check the odd number up to the square root of N, assume the number is greater than 2.
boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
This is the simplest form of finding the prime numbers from the given array. We can also use scanner by assigning n instead of an array to check whether if it is a prime or non prime from the given input(commented in program).Hope this helps you..!!
public static void main(String[] arg) {
int a[]= {1,2,3,4,5,6,7,8,9,10}; //int n=0 or n=values
int num =0;
String primeNumbers = "";
for (int i = 0; i <= a.length; i++) /*change a.length to n*/
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from given array :");
System.out.println(primeNumbers);
}
}
Since you have asked for 5 number explicitly, the code has hardcoded for 5 numbers
import java.util.Scanner;
public class PracticeTest {
public static void main(String args[]) {
int arr[] = new int[5];
Scanner sc = new Scanner(System.in);
System.out.println("Enter 5 numbers");
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
}
checkPrimeNumbers(arr);
}
public static void checkPrimeNumbers(int arr[]) {
loop1:
for (int j = 0; j < arr.length; j++) {
loop2:
for (int i = 2; i < arr[j]; i++) {
if (arr[j] % i == 0) {
continue loop1;
}
}
System.out.print(arr[j] + " ");
}
}
}
This is the simplest way to accept 'n' integers and display the prime and non prime numbers present in that array. Without using functions
import java.util.Scanner;
// Author Dot-Coin
public class The_Prime {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of the array");
int size=sc.nextInt();
int Primer[]=new int [size];
int Non_Primer[]=new int [size];
int Numbers[]=new int [size];
int counter=0;int j=0,k=0,m=0,n=0;
System.out.println("Enter the numbers ");
for(int i=0;i<size;i++)
Numbers[i]=sc.nextInt();
for(int i=0;i<size;i++)
{
if(Numbers[i]==1||Numbers[i]==0)
{
continue;
}
for(n=1;n<=Numbers[i];n++)
{
if(Numbers[i]%n==0)
counter++;
}
if(counter>2)
{
Non_Primer[k]=Numbers[i];k++;counter=0;continue;
}
if(counter==2)
{
Primer[m]=Numbers[i];m++;counter=0;
}
}
System.out.println("The prime numbers are");
for(k=0;k<Primer.length;k++)
{
if(Primer[k]==0)
{
j++;continue;
}
else
System.out.println(Primer[k]);
}
if(j==Primer.length)
System.out.println("Null");j=0;
System.out.println("The Non prime numbers are ");
for( k=0;k<Non_Primer.length;k++)
{
if(Non_Primer[k]==0)
{
j++;continue;
}
System.out.println(Non_Primer[k]);
}
if(j==Non_Primer.length)
System.out.println("Null");
}}
This program asks for the user to input 10 numbers and is converted into an int array. If the array is lucky (contains the numbers 7, 13, or 18) then it prints out the sum of all the numbers in the array. If it does not contain those then it is false and it only prints the sum of all the even numbers.
How do I correctly ask for this input? How do I get the sum of the even numbers in the array? Is any of the other code incorrect?
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as the input.
int[] test = {1,2,3,4,5,6,7};
luckyNumber1 = {7};
luckyNumber2 = {13};
luckyNumber3 = {18};
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
public static int sum(int [ ] value) {
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
public static int sumOfEvens (
public static boolean isLucky (int[] array) {
if ( (int == luckyNumber1) || (int == luckyNumber2) || (int == luckyNumber3 )
return true;
else
return false
}
// write the static methods isLucky, sum, and sumOfEvens
}
You have an array of size 9. Instead it should be of size 10. So, Change the initialization to
int[] a=new int[10];
Use modulo operator % or remainder operator in Java to find out even or odd numbers.
int evenSum = 0;
for(int j=0;j<a.length;j++){
if(a[j]%2 == 0){
//even numbers
evenSum = evenSum + a[j];
}else{
//odd numbers
}
}
return evenSum;
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
There's something wrong with your loop, it should be
for (int j = 0; j < 9; j++)
With this fix it should correctly prompt the users for 9 numbers. Change to 10 for the array and the loop it would takes in 10 number.
Sum of evens
static int sumOfEvens(int array[]) {
int sum = 0;
for(int i = 0; i < array.length; i++>) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
Input
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
import java.util.Scanner;
public class MyMain1 {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as
// the input.
int[] luckyNumbers = { 7, 13, 18 };
int[] a = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Please enter numbers...");
for (int j = 0; j <= 9; j++) {
a[j] = sc.nextInt();
}
sc.close();
boolean sumAll = false;
for (int i : a) {
for (int j : luckyNumbers) {
if (i == j) {
sumAll = true;
break;
}
}
if(sumAll) {
break;
}
}
if (sumAll) {
System.out.println("Summing all : " + sumAll(a));
} else {
System.out.println("Summing Only Even : " + sumEven(a));
}
}
public static int sumAll(int[] value) {
int total = 0;
for (int j : value) {
total = total + j;
}
return total;
}
public static int sumEven(int[] value) {
int total = 0;
for (int j : value) {
if (j % 2 == 0) {
total = total + j;
}
}
return total;
}
}
So I'm just trying to see if the elements of my array are divisible by the sum, I think something is wrong with my for-loop that sums up the elements of the array, any tips on how I should proceed?
public static void main(String[] args) {
int apa[] = {3,3,3};
System.out.print(allEqual(apa));
}
public static boolean allEqual(int[] a) {
int summa = 0;
boolean svar = true;
for (int i = 0; i <= a.length; i++) {
summa +=a[i];
}
if (summa % a.length == 0) {
return svar;
} else {
svar = false;
return svar;
}
}
Array indexes in Java range from 0 through length - 1, so for your array of length 3, the maximum index is 2. Stop your for loop before you get to length, or else you'll run off the end of the array with a[3] and you'll get the ArrayIndexOutOfBoundsException you have observed. Change
for (int i = 0; i <= a.length; i++) {
to
for (int i = 0; i < a.length; i++) {
You have:
for (int i = 0; i <= a.length; i++)
You probably mean:
for (int i = 0; i < a.length; i++)
As accessing a[a.length] will always lead to an ArrayIndexOutOfBoundsException (valid index range is [0, a.length-1]).
You could also use this syntax to eliminate the possibility of that mistake, if you don't actually need to do anything with the index itself in the loop:
for (int value : a)
summa += value;
All of this, of course, assumes a != null.
public static void main(String[] args) {
int apa[] = {3,3,3};
System.out.print(allEqual(apa));
}
public static boolean allEqual(int[] a) {
int summa = 0;
boolean svar = true;
for (int i = 0; i < a.length; i++) { // <-- HERE
// if i == a.length, an ArrayIndexOutOfBoundsException will be raised
summa +=a[i];
}
if (summa % a.length == 0) {
return svar;
} else {
svar = false;
return svar;
}
}
I'm writing a program that takes 10 numbers as input and displays the mode of the numbers using parallel arrays and a method that takes an array of numbers as a parameter and returns the value that appears most often in the array. PROBLEM: However, when I run my program it has absolutely no output, also, I am not sure how to implement the parallel arrays.
Does anyone know?
Thank you.
import java.util.Scanner;
public class Mode {
public static void main(String[] args) {
}
public int computeMode(int[] nums) {
Scanner scanner = new Scanner(System.in);
int maxValue = -1;
int maxCount = 0;
int x = 0;
//count how many times nums[i] appears in array
System.out.println("Enter 10 numbers: ");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
} catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
scanner = new Scanner(System.in);
i = -1;
continue;
}
for (i = 0; i < nums.length; i++) {
int count = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] == nums[i]) {
count++;
}
}
if (count > maxCount) {
maxValue = nums[i];
maxCount = count;
System.out.println("The mode is: " + maxValue);
}
}
}
return maxValue;
}
}
The main function is empty, so it does not anything,
and the function doesn't need any parameter, because you read the numbers with the scanner
I think you need this:
import java.util.Scanner;
class Mode {
public static void main(String[] args) {
computeMode();
}
public static void computeMode(){
int nums[]=new int[10];
Scanner scanner = new Scanner(System.in);
int maxValue = -1;
int maxCount = 0;
int x = 0;
//count how many times nums[i] appears in array
System.out.println("Enter 10 numbers: ");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
nums[i]=x;
}
catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
i =i -1;
scanner.nextLine();
continue;
}
}
for (int i = 0; i < nums.length; i++) {
int count = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] == nums[i]) {
count++;
}
}
if (count > maxCount) {
maxValue = nums[i];
maxCount = count;
}
}
System.out.println("The mode is: " + maxValue);
}
}
The code writes x, but never reads it; reads nums, but never writes it; and implements computeMode, but never calls it.