Finding the mode of an array: no output - java

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.

Related

How many times a number occurs

I need to write a program that reads an array of ints and an integer number n. The program must check how many times n occurs in the array.
Input:
The first line contains the size of the input array.
The second line contains elements of the array separated by spaces.
The third line contains n.
Output:
The result is only a single non-negative integer number.
My code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
int n = scanner.nextInt();
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int counter = 0;
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);
}
}
Test input:
6
1 2 3 4 2 1
2
My result: 1
My question is why int n = scanner.nextInt();read "1". It should "2".
Reading the n variable was in the wrong place. The solution:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int counter = 0;
int n = scanner.nextInt();
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);
}
}
You should read n after you read the array like so:
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
int[] array = new int[len];
for (int i = 0; i < len; i++){
array[i] = scanner.nextInt();
}
int n = scanner.nextInt();
int counter = 0;
for (int i = 0; i < len; i++) {
if (array[i] == n) {
counter++;
}
}
System.out.println(counter);

Loop not giving me desired matrix output

I am trying to display an array of numbers in a square matrix that increases by 1 in a snake pattern. Cant get right output. User inputs row/columns and matrix is displayed. Look at photo below. I have also attempted if statements for even/odd rows with modulo but still getting same output. (Bear with me, I am new to this, sorry about format or if I'm missing information)
http://imgur.com/a/ZDhFw
import java.util.Scanner;
public class A3_Q2 {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("[-------------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[-------------------------]");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
int arraySize = keyboard.nextInt();
while(arraySize < 3)
{
System.out.println("Lets try this again ....");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
arraySize = keyboard.nextInt();
}
int [][] pattern = new int[arraySize][arraySize];
int i = 0;
int number = 1;
while (i < arraySize)
{
for (int j = 0; j < arraySize; ++j)
{
pattern[i][j] = number;
System.out.printf("%3d", pattern[i][j]);
number++;
}
System.out.println("");
++i;
for (int j = arraySize-1; j >= 0; --j)
{
pattern[i][j] = number;
System.out.printf("%3d", pattern[i][j]);
number++;
}
System.out.println("");
++i;
}
}
}
I've changed your code so that it works. As you already mentioned, you can use the modulo operator here.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("[-------------------------]");
System.out.println("[ Array Pattern ]");
System.out.println("[-------------------------]");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
int arraySize = keyboard.nextInt();
while(arraySize < 3)
{
System.out.println("Lets try this again ....");
System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
arraySize = keyboard.nextInt();
}
int [][] pattern = new int[arraySize][arraySize];
int number = 1;
for(int i=0;i<arraySize;i++){
if(i%2==0){
for(int j=0;j<arraySize;j++){
pattern[i][j]=number;
number++;
}
}
else{
for(int j=arraySize-1;j>=0;j--){
pattern[i][j]=number;
number++;
}
}
for(int j=0;j<arraySize;j++){
System.out.printf("%3d", pattern[i][j]);
}
System.out.println();
}
}
EDIT: Tested this in IDE to make sure it works.
You first need to have have an initial value for pattern[i][j].
for (int i = 0; i < arraySize; i++) {
for (int j = 0; j < arraySize; j++) {
pattern[i][j] = arraySize*i + j + 1;
}
}
You need to then have a condition that will print out the numbers in ascending order when i is even, and descending when i is odd.
for (int i = 0; i < arraySize; i++) {
if (i % 2 == 0) {
for (int j = 0; j < arraySize; j++) {
System.out.printf("%3d", pattern[i][j]);
}
} else {
for (int j = arraySize - 1; j >= 0; j--) {
System.out.printf("%3d", pattern[i][j]);
}
}
System.out.println();
}

find all prime numbers from array

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");
}}

Java program asking for 10 numbers and puts them in an array. How do I ask for input? Is my code correct so far?

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;
}
}

Concerning "else" statement in for-loop when traversing through array

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");
}
}

Categories

Resources