I created a java program that will search for a value in array but my problem is when I input the same value in a different index, the first index is the only one that will be on output.
Example index 0 = 2, index 1 = 3, index 2 = 2
Output : array 2 is found at index 0 only
I break it on the loop to stop but if I did not do that, it will loop the Output
Here's what I want for Output: array 2 is found at index 0,2
Code:
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Buff {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter how many index :");
int v = Integer.parseInt( in .readLine());
int x;
int[] c = new int[v];
int vv;
for (x = 0; x < v; x++) {
System.out.print("Enter your value :");
c[x] = Integer.parseInt( in .readLine());
}
System.out.print("Enter your search number :");
int xx = Integer.parseInt( in .readLine());
for (x = 0; x < v; x++) {
if (c[x] == xx) {
System.out.print("array " + xx + " found at index :" + x);
break;
} else {
System.out.print("array not found");
}
}
}
}
You can also use StringBuilder if all you care is to output the indexes.
StringBuilder sb = new StringBuilder("array" + xx +" is found at index: ");
for (x = 0; x < v; x++) {
if (c[x] == xx) {
sb.append(x).append(",");
}
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb);
} else {
System.out.println("array not found");
}
The solution to to make a list of the indexes that match and populate it in your for loop.
then after the for loop is done, print out the results
List<Integer> foundIndexes = new ArrayList<>();
for (x = 0; x < v; x++) {
if (c[x] == xx) {
foundIndexes.add(x);
}
}
//now we looped through whole array
if(foundIndexes.isEmpty()){
System.out.print("array not found");
}else{
System.out.print("array " + xx + " found at index : ");
for(Integer i : foundIndex){
System.out.print(i + ",");
}
}
This will print out array 2 is found at index 0,2, with a trailing comma. It's slightly more complicated to not have a trailing comma at the last index but I will leave that up to you to figure out.
If I understand correctly the problem is the following:
You have elements in an array, you want to check if a particular value is in more than once position of the array, your problem is if you simply remove the break statement, it shows a message every time you don't find the desired number, that's frankly the only problem I see with removing the break statement.
Personally, what I'd do one of these two things:
Option A: You can create a boolean variable that changes if you find a number, then wait to deliver the "array not found" message until you have stopped searching for it, like this:
boolean found = false;
for( x=0; x<v; x++)
{
if(c[x] == xx)
{
System.out.println("array " + xx + " found at index :"+x);
found = true;
}
}
if (found = false)
{
System.out.println("array not found");
}
println does the same as print, only it introduces a \n at the end, so the response looks like this:
array 2 found at index :0
array 2 found at index :2
Instead of:
array 2 found at index :0
array 2 found at index :2
Option B: Probably more elegant solution would be to create other array that store the positions in which you have found the element you are looking for, then print them all at once, you could do this going over the array twice (one to count how many positions the array has to have, another to check the positions of the elements) or simply use an ArrayList, but since this looks like learning material I'm going to guess that's out of the question.
Also if it is possible, try to word your question better because I'm still not even sure if this is what you are asking.
Related
I need to have a program that asks the user for a number, and reports that number's index in the list. If the number is not found, the program should not print anything.
Example:
Sample Output:
1
2
3
3
4
Search for? 3
3 is at index 2
3 is at index 3
This is what I have written but the put is looping multiple times. Can you suggest fixing it?
import java.util.ArrayList;
import java.util.Scanner;
public class IndexOf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while (true) {
int input = Integer.valueOf(scanner.nextLine());
if (input == -1) {
break;
}
list.add(input);
}
System.out.println("Search for? ");
int src = scanner.nextInt();
int ind = 0;
for(int i=0; i<list.size(); i++){
int num = list.get(i);
if(src == num){
ind = list.indexOf(src);
}
System.out.println(src + " is at index " + ind);
}
}
}
EDIT
Input: 1 2 3 3 4 -1
Search for? 3 Output: 3 is at index 0 3 is at index 0 3 is at index 2 3 is at index 2 3 is at index 2 ///So it must be only one sentence for each index. Even if I put after "for" loop, it only output the first if index.
I can see a single problem in your code, that is, you print everything, not only the matches. To solve that you need to put your System.out.println into the if, like this:
for(int i=0; i<list.size(); i++){
int num = list.get(i);
if(src == num){
ind = i;
System.out.println(src + " is at index " + ind);
}
}
Let me know if anything else was wrong.
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] + " ");
}
}
}
I am trying to search an array for an int but it only give the location of the first index it finds if the int appears more than once. For example, if the number 2 appears at index 3 and 7. It will say 3 found at location 3 twice instead of saying 2 found at location 3 and 7. How can I get the additional index of the location where the number also appears.
// random_integers is an array of random integers of size 10
Arrays.asList(random_integers);
for (int n : random_integers) {
if (n == number) {
System.out.println("Search Value: "
+ number
+ " found at location: "
+ Arrays.asList(random_integers).indexOf(n)
+ " in the unsorted array");
}
}
Thank you.
That's the behavior of indexOf. Instead, use a traditional for loop and just use the current looping variable
for (int i = 0; i < random_integers.length; i++){
if (random_integers[i] == number){
System.out.println("Search Value: " + number + " found at location: " + i);
}
}
This happens because List#indexOf() has no idea about your intention to keep last index where item was found recently, so it returns first index every time. You should iterate over array by index, printing it when occurrence found:
for (int i; i < random_number.length; i++) {
if (random_integers[i] == number) {
System.out.format("Search Value: %s found at location: %s in the unsorted array", number, i);
}
}
The indexOf() method returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element.
A traditional for loop will work here.
for(int i=0; i < random_integers.length;i++){
if (random_integers[i] == number){
System.out.println("number=" + number + " location=" + i);
}
}
As what all guys said, use traditional for loop instead. If you want to use asList , try the following code:
int size = Arrays.asList(a).size();
for (int i = 0 ; i < size ; i++){
if (number == Arrays.asList(a).get(i))
System.out.println(" Search Value: " + number +
" found at location: " + i +
" in the unsorted array");
}
This code only works, if you are looking to find the current and next index value of a given array, however, if you are looking to find the index of a given value, refer to Michael's answer on this thread.
int totalLength = random_integers.length;
for (int i=0; i < totalLength; i++){
int nextIndex = i+1;
if (nextIndex == totalLength){
break;
}else{
int currentIndexValue = random_integers[i];
int nextIndexValue = random_integers[nextIndex];
}
}
I am trying to solve this, but i don't know how...
Values[10] = {1,1,4,4,2,3,3,2,1,3}
to print:
{1,2,3,4} or {1,4,2,3} (not sorted, any order, but distinct)
I also need to count the number of times each number has occurred, both without sort, new arrays or boolean methods or other data structures, please advise as i am stuck.
Is there a simple method i can use to just print the unique values/ distinct values ?
It can be accomplished if your are willing to destroy your current array. and you assume that the array is either of type Integer (so nullable) or if not there is some bound such as all int are poistive so you can use -1.
for(int i = 0; i < values.length; i++){ //for entire array
Integer currVal = values[i]; // select current value
int count = 1; // and set count to 1
if(currVal != null){ // if value not seen
for( int j = i + 1; j < values.length; j++){ // for rest of array
if(values[j] == currVal){ // if same as current Value
values[j] = null; // mark as seen
count++; // and count it
}
}
System.out.print("Number : " + currVal + " Count : " + count + "\n");
//print information
}
// if seen skip.
}
In plain english, Go through the array in 2 loops, roughly O(n^2) time.
Go to index i. If index has not yet been seen (is not null) then go through the rest of array, mark any indexs with same value as seen (make it null) and increment count varable. At end of loop print value and count. If Index has be seen (is null) skip and go to next index. At end of both loops all values will be left null.
Input : Values[] = {1,1,4,4,2,3,3,2,1,3}
Output : Values[] = {1,null,4,null,2,3,null,null,null,null}
Number : 1 Count : 3
Number : 4 Count : 2
Number : 2 Count : 2
Number : 3 Count : 3
Edit: corrected my mistake in output, pointed out by commenters.
Another solution, without creating additional objects:
Arrays.sort(values);
for(int i = 0; i < values.length; i++) {
if (i == 0 || value[i] != value[i-1]) {
System.out.println(values[i]);
}
}
And the shortest solution I can think of:
Integer[] values = {1,1,4,4,2,3,3,2,1,3};
Set<Integer> set = new HashSet<Integer>();
set.addAll(Arrays.asList(values));
System.out.println(set);
Assuming the values are guaranteed to be integers, you could also do it by incrementing a check value, scan over the array, sum the number of that check value in the array, add it to an accumulator and loop while the accumulator < array.length.
Something like this (untested):
public void checkArray(int[] toCheck) {
int currentNum = 0;
int currentCount = 0;
int totalSeen = 0;
StringBuilder sb = new StringBuilder();
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i=0; i<toCheck.length; i++) {
min = Math.min(toCheck[i], min);
max = Math.max(toCheck[i], max);
}
System.out.print("{ ");
for(currentNum = min; currentNum < max; currentNum++) {
for(int i=0; i<toCheck.length; i++) {
if(toCheck[i] == currentNum) currentCount++;
}
if(currentCount != 0) {
if(currentNum == min) System.out.print(currentCount + "(" +currentCount+ ")");
else System.out.print(", " + currentCount + " (" +currentCount+ ")");
}
totalSeen += currentCount;
currentCount = 0;
}
System.out.println(" }");
}
It should be noted that while this technically fulfills all your requirements, it will be far less efficient than gbtimmon's approach.
If your ints were {1,2,3,150000}, for example, it will needlessly spin over all the values between 4 and 149999.
Edit: added better limits from tbitof's suggestion.
Your question isn't quite clear to me, since it sounds like you want to do these things without creating any additional objects at all. But if it's just about not creating another array, you could use a Map<Integer, Integer>, where the key is the number from your original array, and the value is the count of times you've seen it. Then at the end you can look up the count for all numbers, and print out all the keys by using Map.keyset()
Edit: For example:
Map<Integer,Integer> counts = new HashMap<Integer, Integer>();
for( int i : values ) {
if( counts.containsKey(i) ) {
counts.put(i, counts.get(i) + 1);
} else {
counts.put(i, 1);
}
}
// get the set of unique keys
Set uniqueInts = counts.keyset();
my main purpose is to get this kind of a output: which shows the value and the number of times it appears in a array. Below is an example, but during the code, i will ask the user for input of data integers into an array
e.g. for the array: {-12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12}
The output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
below here is my own attempt, but for some reason i could not get the array to be stored, and used at other parts of the code:
import java.util.*;
public class Q4
{
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
int[] myarray = new int[50];
System.out.println("Enter integers into the system, to quit enter -99");
Scanner scan=new Scanner(System.in);
for(int i = 0; i<myarray.length; i++)
{
int temp =scan.nextInt();
if(temp!=(-99))
{
myarray[i]=temp;
}
if(temp ==(-99))
{
System.out.println("Successfully terminated by inputting -99");
System.out.println();
break;
}
else if(i==(myarray.length-1))
{
System.out.println("successfully filled up array fully");
System.out.println();
}
}
for(int i = 0; i<myarray.length; i++)
{
System.out.print(myarray[i]+",");
}
System.out.print("}");
int temp=0;
int number = 0;
Arrays.sort(myarray);
System.out.println("Array list: {");
for (int i = 0; i < myarray.length; i++)
{
if(temp==0)
{
temp=myarray[i];
number++;
}
else if (temp!=0)
{
if (temp==myarray[i])
{
number++;
}
else
{
temp=0;
}
}
}
System.out.print("}");
System.out.println();
System.out.println();
System.out.println("N"+"\t"+"\t"+"Count");
System.out.println(temp+"\t"+"\t"+number);
}
}
here is My output, which isnt what i wanted,
Enter integers into the system, to quit enter -99
12
3123
3123
11
22
-99
Successfully terminated by inputting -99
Array list: {12,3123,3123,11,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}Array list: {
}
N Count
3123 48
You increment number to attempt to count how many times the current array[i] has been seen, yet you never reset it's value to 0.
Also, at the end of your method, you are only printing a single row of the N Count table. If you want to print one row for each unique element of the index, don't you need to print more than one row?
There's an easier way to count the occurrences of elements in an array that doesn't require sorting it - hint, considering using a Map<Integer, Integer>.
You should try following thing.
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Scanner;
public class NumberRepetion {
public static void main(String[] args) {
int[] myarray = new int[50];
System.out.println("Enter integers into the system, to quit enter -99");
Scanner scan = new Scanner(System.in);
ArrayList<Integer> myarrList = new ArrayList<Integer>();
while (scan.hasNext()) {
int temp = scan.nextInt();
if (temp != (-99)) {
// myarray[i] = temp;
myarrList.add(temp);
}
if (temp == (-99)) {
System.out.println("Successfully terminated by inputting -99");
System.out.println();
break;
}
}
Hashtable<Integer, Integer> result = new Hashtable<Integer, Integer>();
System.out.print("Input Values {");
int currIndex = 0 ;
for (Integer val : myarrList) {
if (currIndex == ( myarrList.size() - 1 )){
System.out.print(val);
}else{
System.out.print(val + ", ");
}
currIndex++ ;
int currVal = val;
Integer integer = result.get(currVal);
if (integer == null || integer == 0) {
result.put(currVal, 1);
} else {
result.put(currVal, ++integer);
}
}
System.out.print("}");
System.out.println()
Enumeration<Integer> keys = result.keys();
System.out.println("N\t\tCount");
while(keys.hasMoreElements()){
System.out.println(" " + keys.nextElement() +"\t\t" + result.get(keys.nextElement()));
}
//System.out.println("\n\n\n Result " + result);
}
}
OUTPUT
Enter integers into the system, to quit enter -99
5
6
5
8
4
-99
Successfully terminated by inputting -99
Input Values {5, 6, 5, 8, 4}
N Count
8 1
5 1
What I would do is to make a new node class that has two instances, the value and count. Every time you encounter a new number, make a new node with the its value, and increment its count by one. Have a List of the nodes and add the node to this list. For the next input, have a loop check if the value has already been seen before, eg.
for i = 0; i <list.size; i++
if list.get(i).data == value // if it finds the value increment and break
list.get(i).count++
break;
else if i==list.size-1//if it went through the list and didn't find the value, make a new node of the value and add it to the list
make a new node
add it to the list
After it has terminated, sort the list by comparing list.get(i).values and swapping (bubble sort comes to mind but there are many ways to sort)
After that just print the values and it's count
If this isn't a lesson how to use Arrays, I strongly advocate in making contact with List, and other collections - but preferably List, and concretely ArrayList. It is so convenient! And it is easy.
There are 3 or 4 basic operations: Constructor to define a List, add elements, remove elements, iterate over all elements.
And about 50 other not so frequently used methods, and methods which use Lists and so on.
public static void main (String [] args)
{
List <Integer> myarray = new ArrayList <Integer> ();
System.out.println ("Enter integers into the system, to quit enter -99");
Scanner scan = new Scanner (System.in);
while (scan.hasNextInt ())
{
int temp = scan.nextInt ();
if (temp == -99)
{
System.out.println ("Successfully terminated by inputting -99");
System.out.println ();
break;
}
else {
myarray.add (temp);
if (myarray.size () == 50)
{
System.out.println ("successfully filled array fully up");
System.out.println ();
}
}
}
for (int i : myarray)
{
System.out.print (i + ",");
}
System.out.print ("}");
Set <Integer> hsi = new HashSet <Integer> ();
hsi.addAll (myarray);
Collections.sort (myarray);
System.out.println ("Array list: {");
int idx = 0;
for (int i: hsi) {
System.out.println (i + "\t" + Collections.frequency (myarray, i));
}
System.out.println (myarray.size ());
}
See how short and simple? Just add the elements - you don't need to know in advance how many elements it contains. No marker-fields or external values to mark the end necessary!
Usage:
java Numbers
Enter integers into the system, to quit enter -99
4 44 0 33 2 2 7 9 1 4 3 90 -99
Successfully terminated by inputting -99
4,44,0,33,2,2,7,9,1,4,3,90,}Array list: {
0 1
1 1
2 2
3 1
33 1
4 2
7 1
9 1
44 1
90 1
12
Your first idea for collecting values, you like to get by index or you want to iterate over, should be ArrayList, not a plain old array. Array is only useful in exceptional cases - when you surely know the size in advance to begin with.
ArrayLists are fast, believe it - no - don't believe it, test it!