Checking for specific integers in an array - java

First post here so I'm hoping I don't screw up.
My task is to have a user enter an array of 10 integers and then input another integer separately and have the program either retrieve that number if it's in the array, or give an error if not.
I'm having trouble comparing the inputted integer with those in the array.
Here's part of my code, with the rest found below:
try{
System.out.print("Please enter 10 integers to store in an array and then press enter: ");
for(int index = 0; index < numbers.length; index++)
numbers[index] = input.nextInt();
if(numbers.length==10){ //method doesnt work properly if you input over 10 integers, only if you input less
System.out.print("Thanks for entering 10 integers. Now input an integer to check: ");
int compare = input.nextInt();
if(numbers[index] == compare){ //this is where the error is I believe
System.out.print(compare); //here too
}
http://pastebin.com/U5PdJgr6
Thank you in advance!

If you're using java-8, you can perform that easily using an IntStream
boolean contained = IntStream.of(inputtedNumbers)
.anyMatch(x -> x == numberToSearch);

Turn
if (numbers[index] == compare) {
System.out.print(compare);
}
Into
boolean found;
for (int number : numbers) {
found = number == compare;
if (found) break;
}
if (found) System.out.print(compare);
else throw new Exception("Number Not Found");
P.S. You don't need to check to make sure numbers.length is still 10. The length of an array is always final and can't change.

package integerarrayexceptions;
import java.util.Scanner;
import java.util.InputMismatchException;
public class IntegerArrayExceptions {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numbers[] = new int[10];
try{
System.out.print("Please enter 10 integers to store in an array and then press enter: ");
for(int index = 0; index < numbers.length; index++)
numbers[index] = input.nextInt(); //The loop only applies to this statement.
if(numbers.length==10){
System.out.print("Thanks for entering 10 integers. Now input an integer to check: ");
int compare = input.nextInt();
for (int index2 = 0; index2 < numbers.length; index2++) {
if(numbers[index2] == compare){
System.out.print(compare);
}
}
}
}
catch (InputMismatchException MismatchException)
{
System.out.print("One or more values entered is not an integer.");
}
}
}

There's a loop missing after you entered the compare value:
for (index = 0; index < numbers.length; index++) {
if(numbers[index] == compare){
System.out.print(compare);
}
]

You try to use the variable "index" outside the "for" loop, where it does not exist...

Related

Searching an array with user input and printing all elements that have this value

I'm trying to search an array for a certain value and display all the elements which contain this value in java. For example, the user selects the number 5, there are 3 projects stored in the array with this value so all 3 of those will be printed out. My code is compiling ok, but when I run it, it jumps to the else statement, even if I am inputting a number that is in the array..
Any help would be amazing. Here's my code:
case 3:
//display all elements with the same state
//get number user wishes to search for
boolean found = false;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the number you wish to search for");
//read user input
num = input.nextInt();
//traverse array
int k = 0;
for(k=0; k < myMonths.length; k++){
if(myMonths[index] == num){
found = true;
break;}
if(found){System.out.println(k);}
else{System.out.println("not found");}
}
break;
Here's the array:
//Menu loop
int myMonths[] = new int[5];
int index = 0;
int num;
while(choice !=6){
switch (choice){
case 1:
//int n = number of projects
int n = 1;
Scanner sc = new Scanner(System.in);
System.out.println("How many months was your project?");
for(int i=0; i<1; i++){
int a = sc.nextInt();
//if months is lesser than 2/greater than 12
if((a < 2) || (a > 12)){
System.out.println("Please enter an amount between 2 and 12 months");}
//if months is between 2 and 12 add it to the array
else{myMonths[index++] = a;} }
break;
First, you should be using k instead of index. Second, you shouldn't be printing "not found" (or testing for that) on every iteration. You should limit variable scope as much as practical. And you also mention wanting to find all matching indices so you shouldn't terminate the loop prematurely; I think you wanted something like
//assume the value isn't present.
boolean found = false;
//read user input
int num = input.nextInt();
//traverse array
for(int k = 0; k < myMonths.length; k++) {
if (myMonths[k] == num){
found = true;
System.out.println(k); // don't break or the loop ends early.
}
}
//this test can only be done after you iterate **all** values.
if (!found) {
System.out.println("not found");
}

Working on a random challenge, but having a problem with

//Java nested loop, if the user input less than 1 and Great than 11 it must display error message. Implementing java nested for loops.
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the size: ");
int size = input.nextInt();
if (size < 1 && size > 11)
System.out.println("INVALID NUMBERS");
for (int rows = size; size > 0; rows++) {
for (int colums = size; colums < 11; colums++) {
System.out.print("#");
}
}
System.out.println();
}
}
Tags
if(size<1 && size>11)
size can not both be less than 1 AND greater than 11.
You'll need a logical OR here:
if(size<1 || size>11)
Not exactly sure what you mean, but to my understanding this is what you're looking for?
int size=input.nextInt();
if(size<1 || size>11) {
System.out.println("INVALID NUMBERS");
}
else{
for (int rows=size;size>0;rows++){
for(int colums=size;colums<11;colums++){
System.out.print("#");
}
}
}
First of all question is not very elaborative and does not mention what the end result should look like.
To my understanding, this code will result in infinite loop when size entered is greater than 0, because of the line:-
for (int rows = size; size > 0; rows++) , the loop will be infinite because the test condition is always greater than zero.

Program to find majority element of an input array doesn't work

I'm trying to find the majority element using Boyer and Moore approach. The program should ask the user to input "n" number of lines on the first line, then there will be "n" numbers followed "n" lines as input. (Ex: user input 5 on the first line, then there will be 5 numbers followed)
Next, use Boyer and Moore approach to find the majority element of an input array. If the majority element doesn't exist in the input array, then execute -1. My program output shows 0 no matter what input I entered. Would you please check it and correct my program?
Output example:
4
12
12
1
12
12
/Or: 3 11 2 13 -1
public static void main (String[]args)
{
int a[] = new int [1000000];
Scanner sc = new Scanner (System.in);
// User input n number of lines
int numberOfLine = sc.nextInt();
//Loop to have n elements as input
for (int i = 1; i<= numberOfLine; i++)
{
a[i] = sc.nextInt();
}
// Call method to display majority element
getMajorityElement(a);
sc.close();
}
//Method to Find M.E using Boyer & Moore approach
public static void getMajorityElement(int [] array)
{
int majorityElement = array[0];
int count = 1;
for (int index = 1; index<array.length; index++)
{
if(majorityElement==array[index])
{
count++;
}
else if(count==0)
{
majorityElement = array[index];
count = 1;
}
else
{
count --;
}
}
// Check if candidate M.E occur more than n/2 times
count = 0;
for (int index = 0; index<array.length; index++)
{
if(array[index]==majorityElement)
{
count++;
}
}
if (count > array.length/2)
{
System.out.println(majorityElement);
}
else
{
System.out.println("-1");
}
}
The reason you get this behavior is that your array of 1,000,000 elements has a majority element of zero: only the initial three or four items are set, while the rest of the items are occupied by zeros - the default value of an int in Java.
Fix this problem by allocating at size once the length is entered. You also need to fix the code that reads input to make sure that the data ends up at indexes 0..numberOfLine-1:
Scanner sc = new Scanner (System.in);
// User input n number of lines
int numberOfLine = sc.nextInt();
int a[] = new int [numberOfLine];
//Loop to have n elements as input
for (int i = 0 ; i < numberOfLine ; i++) {
a[i] = sc.nextInt();
}

How to print out even-numbered indexes for arrays in Java?

I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}

Sorting even numbers from original array

I have to create a program that reads an arbitrary number of positive integers from the user and store them into an array. The number of input data is not more than 100. After the user finishes the program should remove all even integers and place them in another array leaving all odd integers in the original array with no holes. It should display the contents in the original array as the order of input, the contents of the even integer array with a count, and the contents of the original array after taking out all even integers with a count
No third array should be used
Im having trouble displaying the original array and original integer array after taking out the even integers. here is my code so far
import java.util.*;
public class Arrays
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter in any amount of positive numbers, Enter -1 when finished");
int i=0;
int nextElm=0;
int a,b;
int[] origArray = new int[100]; /* Two arrays at length 100*/
int[] evenArray = new int[100];
while((i<origArray.length && i<evenArray.length)&& nextElm!= -1)
{
System.out.println("Enter next number: ");
nextElm = scan.nextInt();
if (nextElm%2 != 0)//Sorts even numbers
{
origArray[i]= nextElm;
}
else
evenArray[i] = nextElm;
i++;
}
System.out.print("\n");
System.out.println("Even Array: ");
for (b=0; b<evenArray.length;b++)
{
if (evenArray[b]== -1)
{
evenArray[b]= 0;
}
if(evenArray[b]!= 0)
{
System.out.print(evenArray[b]+" ");
}
}
System.out.print("\n");
System.out.println("Original Array: ");
for(a=0; a<origArray.length && a<evenArray.length; a++)
{
if (origArray[a]== -1)
{
origArray[a]= 0;
}
if(origArray[a]!= 0)
{
System.out.print(origArray[a]+" " + evenArray[a]);
}
}
System.out.print("\n");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter in any amount of positive numbers, Enter -1 when finished");
int i = 0;
int nextElm = 0;
int a, b;
int[] origArray = new int[100]; /* Two arrays at length 100 */
int[] evenArray = new int[100];
while (nextElm != -1) {
System.out.println("Enter next number: ");
nextElm = scan.nextInt();
if (nextElm > 0) {
origArray[i] = nextElm;
i++;
}
}
int x = 0;
System.out.println();
// Displays original array and sorts even numbers to even array +
// original count
System.out.printf("\nTotal count of original array is : %d", i);
System.out.println();
for (int orgNumber : origArray) {
if (orgNumber != 0) {
System.out.print(orgNumber + " ");
}
if (orgNumber % 2 == 0) {
if (orgNumber != 0) {
evenArray[x] = orgNumber;
x++;
}
}
}
System.out.println();
// Displays sort even numbers to even array + even count
System.out.printf("\nTotal count of even array is : %d", x);
System.out.println();
for (int evenNumber : evenArray) {
if (evenNumber != 0) {
System.out.print(evenNumber + " ");
}
}
// Displays sort odd numbers from original array + odd count
System.out.printf("\nTotal count of orignal array without even is : %d", i - x);
System.out.println();
for (int oddNumber : origArray) {
if (oddNumber % 2 != 0) {
System.out.print(oddNumber + " ");
}
}
}
This should work perfectly if I understood your question well. Hope you find this helpful.
You want three separate loops. One for inputting the values (I would suggest the while construct as you have done) and one for sorting the values.
Your input loop should read in a new number each time and only quit when the user wants to. For example, if the user inputs a negative number, then your loop will quit. Like this:
System.out.println("Enter any number of numbers; enter a negative when finished.");
int nextElm = 0;
int count = 0;
while (nextElm >= 0) {
nextElm = scan.nextInt();
origArray[count] = nextElm;
count++;
}
// This is where you would put a print statement that prints the original array with a count.
Now after this, use the java.util.Arrays.copyOf() method to trim out the empty elements of the array, like so:
origArray = java.util.Arrays.copyOf(origArray, count+1);
Next, use a for loop to iterate through the array, and move even numbers to the other array. This is the tricky part, because removing items from an array requires iteration to move each value to it's previous index.
int j = 0;
for (int i=0; i<count; i++){
if (origArray[i] % 2 == 0){
evenArray[j] = origArray[i]; //add even number to evenArray
j++; //move to next index of evenArray
for (int k=i; k<(origArray.length-1); k++){
origArray[k] = origArray[k+1]; //store next value in current index
}
}
}
Then finally, use the java.util.Arrays.copyOf() method to trim out the empty elements of the array again, like so:
evenArray = java.util.Arrays.copyOf(evenArray, j+1);
Disclaimer: This was all coded from the hip so let me know if I missed something or did something incorrectly.

Categories