Finding all Index's of specific Element in ArrayList (Int) - java

I recently got into Java Programming (Maybe it's already getting too hard for me), and I'm doing some exercises daily to practise. One of the challenges I need to do, is to search an Element (int), and if it's in the Array, the Index should be displayed (All index's should be displayed if Element duplicates found in Array).
Here's the code I have so far!
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("");
// implement here finding the indices of a number
System.out.println("Search for?");
int arraySize = list.size();
int numToSearch = Integer.valueOf(scanner.nextLine());
for(int i = 0; i <arraySize-1; i++){
int pos = list.indexOf(numToSearch);
if(list.indexOf(i)==pos){
System.out.print(numToSearch+" is at Index: "+pos);
}
}
}
}
So far I've managed to get it to print the Index of the Element I search for, but it only does it for the first correct Index it finds.
Sorry for the clunky code, haven't yet learnt much in terms of neat code!

In the last loop, you were checking the equality between the index of numToSearch in list and the index of 0...arraySize-2 in list. Unless I am understanding the question incorrectly, the correct approach should be checking the equality of each array member and numToSearch. Then print out the string with the current index you are at.
This could be represented like this:
for (int i = 0; i < arraySize; i++) {
if (list.get(i) == numToSearch) {
System.out.println(numToSearch + " is at Index: " + i);
}
}

Related

Trying to sort user input into alphabetical order with Java, why won't this code work?

For some reason when I try to ask a user for names so I can add them to a list and sort them alphabetically, this code will not print anything out. It will not even get past the while loop, does anyone have any idea what the problem is? Also another question; how can you execute some code if the user presses the enter button when asked for input value, would it just be null? Thanks!
import java.util.Scanner;
import java.util.*;
public class project16u
{
public static void main(String[] args)
{
int n;
String input = "nothing";
String temp;
ArrayList<String> names = new ArrayList<String>();
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
while(!input.equals("done")){
input = s1.nextLine();
names.add(input);
}
for (int i = 0; i < names.size()-1; i++)
{
if (names.get(i).compareTo(names.get(i+1))>0)
{
temp = names.get(i);
names.add(i, names.get(i+1));
names.add(i+1, temp);
i=0;
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < names.size() - 1; i++)
{
System.out.print(names.get(i).toString() + ",");
}
System.out.print(names.get(names.size()-1));
}
}
add inserts the name at the requested index. Thus, in your case, you will have two copies of the same name in the list, rather than the one you intended.
You probably want to use set instead.
You may need to change the loop condition to
s1.hasNextLine() && !input.equals("done")

Finding specific value inside an Array (not List)

I am learning about arrays and I did quiet a few experiments, most of them went well, however now I'm stuck.
What I want to archive is, find if an specific value (String, int or whatever), exists inside an Array and if it does, use that value for something i.e the code below which I basically count how many times that value was present inside the array:
package arraysOnly;
import java.util.*;
public class ArrayContainsString
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int arraySize = 0;
int wordCount = 0;
System.out.println("How many words are you gonna type?: ");
arraySize = sc.nextInt();
String[] words = new String[arraySize]; // Simple array, the size of which will be decided from the user-input
for(int count = 0; count < arraySize; count++)
{
System.out.println("Enter your " + (count+1) + ": ");
words[count] = sc.next();
}
//Basically this is the part I'm having troubles
if(in_array("ubt", $words)
{
wordCount++;
}
}
}
I know about this,
if(Arrays.asList(words).contains("ubt"));
which basically converts the array into an List / ArrayList or whatever, however I want to treat this as an array only if possible.
An array is the wrong data structure; a Set is the weapon of choice:
Set<String> words = new HashSet<>()
for (int count = 0; count < arraySize; count++) {
System.out.println("Enter your " + (count+1) + ": ");
words.add(sc.next());
}
if (words.contains("ubt"))
wordCount++;
}
The contains() method of a HashSet completes in constant time not matter how large the set is. Although performance is irrelevant for small input sizes like this usage, it's good to get in the habit of choosing the right tools for the job. It also makes your code cleaner.
Generally speaking, don't use arrays unless you absolutely have to; they are only rarely used in commercial code.
The simple solution
public static boolean contains(String toFind, String[] strings) {
for (String str : strings) {
if (str.equals(toFind)) return true;
}
return false;
}
EDIT:
To increase it after the user inputs a word, use this in the loop:
System.out.println("Enter your " + (count+1) + ": ");
words[count] = sc.next();
if (words[count].equals("ubt")) wordCount++;
You can just iterate over array
for (String str : array){
if(str.equals("ubt")){
wordCount++;
}
}
Edit:
It's just equivalent to a normal for loop
for(int i=0; i<array.length; i++) {
if(array[i].equals("ubt")){
wordCount++;
}
}

How to make a functioning to do list in java

I am trying to make a functioning to do list with a limit of 10 elements, however I am having an issue with two major things in the to do list.
The first is that after I first compile and run the program and select to add elements to the list, that functions properly, but if I add two elements and the 'stop' sentinel, when I select the next option to print the to do list, I am presented with a list, showing my two elements and then the stop sentinel along with 7 null values in the list. So the first issue I am having is to get rid of the null values, I attempted using a counter as you can see in my code however that was not proving to be effective.
The next issue that I am having is that I am trying to make it so that you can add to the list, so once you select to add more things to the list, the new options the user writes, rewrites over them in the array and prints out the new values and not along with the old ones. I am assuming that can be done through some sort of recursion method but I am having a hard time figuring it out.
Any help would be greatly appreciated!
Thanks!
import java.util.Scanner;
public class ToDo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX = 10;
String[] list = new String[MAX];
int choice = 0;
while (choice != 3) {
System.out.println();
System.out.println("Type 1 to add a new thing to your to do list.");
System.out.println("Type 2 to print the to do list.");
System.out.println("Type 3 to exit the program.");
System.out.print("Select an option: ");
choice = input.nextInt();
int count = 0;
if (choice == 1) {
System.out.println("Keep hitting enter after to do's, if you want to stop, type 'stop'.");
for (int i=0;i<MAX;i++) {
list[i] = input.nextLine();
if (list[i].equals("stop")) break;
count++;
}
}
if (choice == 2) {
for (int index = 0;index < list.length; index++) {
System.out.println(list[index]);
}
}
}
}
}
As I have mentioned in the comment, you can use an ArrayList instead of String[] to make your processing much easier.
But if you want to use the array itself, there are 3 minor issues with your code.
In your choice 1 for loop, start the loop from count,
for (int i=count;i<MAX;i++) {
list[i] = input.nextLine();
if (list[i].equals("stop")) break;
count++;
}
In your choice 2 for loop, end the loop before reaching count,
for (int index = 0;index < count; index++) {
System.out.println(list[index]);
}
And move your count initialization outside the while loop.
int count = 0;
But beware, if you decide to implement removing tasks, this could get complicated and using ArrayList would become much simpler.
Instead of using a fixed size array of Strings, use an ArrayList of Strings. Then you can add elements to it as you go.
Make sure to
import java.util.ArrayList;
Declaration syntax is
ArrayList<String> myList = new ArrayList<String>();
Add elements to your list with the add() method:
myList.add(input.nextLine())
You don't need that inner for loop, instead break out of the while loop of input options when you've iterated through it 10 times.
To solve your problem of "stop" being in your list, check that the input is "stop", and stop, before you attempt to add to the list.
It is better to use ArrayList but if you still want to stick to String[] then the following program will work for you:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX = 10;
String[] list = new String[MAX];
int choice = 0;
while (choice != 3) {
System.out.println();
System.out.println("Type 1 to add a new thing to your to do list.");
System.out.println("Type 2 to print the to do list.");
System.out.println("Type 3 to exit the program.");
System.out.print("Select an option: ");
choice = input.nextInt();
String userEnteredItem;
if (choice == 1) {
System.out.println("Keep hitting enter after to do's, if you want to stop, type 'stop'.");
for (int i=0;i<MAX;i++) {
userEnteredItem = input.nextLine();
if(!userEnteredItem.isEmpty()) {
list[i] = userEnteredItem;
if (userEnteredItem.equals("stop")) {
break;
}
count++;
} else {
i--; // Do not increase index for empty item.
}
}
}
else if (choice == 2) {
for (int index = 0;index < count; index++) {
System.out.println(list[index]);
}
}
else {
input.close();
}
}
}
It keeps track of user items in static int count and it also closes the scanner when you do not need it.

How to sort a string array as they are entered in Java without using the Array or Collection classes?

I have to first take as input the number of strings to be sorted. As they are entered, I have to sort them in ascending order, not at the end. The first part came out fine, but I don't know how to sort them (preferred method per instructor is the compareto method) when I have nothing to compare until it's entered. I cannot use the Arrays class or Collection class, which means I have to work around it to test my ingenuity.
Does anyone have any tips or pseudo code to lead me in the right direction?
Thanks.
Here is the code:
import java.util.*;
public class Sort_as_Inserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of elements to be sorted: ");
String element_number = input.nextLine();
String[] user_word = new String[Integer.parseInt(element_number)];
for (int i = 0; i < Integer.parseInt(element_number); i++)
{
System.out.print("Element " + (i + 1) + ": ");
user_word[i] = input.nextLine();
}
System.out.println();
}//end Main Method
}//end Class
I am supposed to sort these elements as they are put in, not after (which makes it even more difficult for me). I cannot use anything in the Arrays class or Collection class to sort them. They have to be sorted in ascending order. So, if a user types "4" as the number of elements, then types "Cherry, Banana, Orange, Apple," it will output: "Apple, Banana, Cherry, Orange."
Looks like you need Insertion Sort. Google it and try to understand the concept. Then try implementing it. Once you got that far you will probably have questions about specific parts where you struggle (if you'll struggle at all).
I got it and it worked as intended. It took some thinking, but it's done. I wanted to post my completed code for future questions from others.
import java.util.Scanner;
public class Sort_as_Inserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of elements to be sorted: ");
int array_size = input.nextInt();
String[] user_words = new String [array_size];
input.nextLine();
for (int i = 0; i < user_words.length; i++)
{
System.out.print("Element " + (i + 1) + ": ");
user_words[i] = input.nextLine();
}//end for
System.out.println();
sortStrings(user_words);
printTheArray(user_words);
}//end Main
public static void sortStrings(String[] words) {
/**
* This method will utilize an Insertion Sort Algorithm
*/
for (int i = 0; i < words.length; i++)
{
for(int j = i + 1; j < words.length; j++)
{
if(words[i].compareToIgnoreCase(words[j]) > 0)
{
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}//end if
}//end inner for
}//end outer for
}//end sortSTrings Method
public static void printTheArray(String[] the_words) {
/**
* This following code block will print the array, and format it properly
* so there is no comma after the last word in the array.
*/
if (the_words.length >= 1)
{
System.out.print(the_words[0]);
}
for (int i = 1; i < the_words.length; i++)
{
System.out.print(", " + the_words[i]);
}
}//end printTheArray Method
}//end Sort_As_Inserted Class

Dynamic Array Algorithm

As part of a homework assignment, we are supposed to create an array that will resize itself if the user attempts to input more data to a new index that is out of bounds. We are not allowed to use any libraries like hashsets, arraylists, etc. My code works, however, the length of the array always ends up being one larger than what is required. I know the problem lies in the nature of the while loop because it will grow and then add, but I don't know how I would fix it.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class DynamicArray
{
public static void main(String[] args)
{
Scanner kb = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.print("Enter a desired length for an array: ");
String[] x = new String[kb.nextInt()];
int index = 0;
System.out.print("Enter as many Strings as desired, separated by a new line. Type in \"end\" to print out the contents of the array.");
String input = kb.nextLine();
while(!input.equalsIgnoreCase("end"))
{
if (index < x.length)
{
x[index] = input;
}
else
{
String[] temp = new String[x.length + 1];
for (int i = 0; i < x.length; ++i)
{
temp[i] = x[i];
}
temp[index] = input;
x = temp;
}
++index;
input = kb.nextLine();
}
for (int i = 0; i < x.length; ++i)
{
System.out.println(x[i]);
}
System.out.println(x.length);
}
}
I know the problem lies in the nature of the while loop because it will grow and then add […]
Not at all. The problem lies in the way Scanner.nextInt() and Scanner.nextLine() work. Scanner.nextInt() will read in an integer, but will not swallow the newline after the integer. So the first thing Scanner.nextLine() sees is that newline, and it thinks it sees an empty line, which is what it returns. So x[0] is a the empty string.
You can see this a bit more clearly if you change this:
System.out.println(x[i]);
to this:
System.out.println(i + ": " + x[i]);
because then you'll see that the first thing it prints is 0:.
By the way, your approach in general is very inefficient, since it requires creating many more arrays than are actually needed. Instead of increasing the size of the array by one, it's much more efficient to double the size of the array, and keep track of its length separately (rather than using x.length). (Admittedly, in your case, efficiency is probably a non-issue, since you're taking input from the user, and there's no way that the user will type in elements anywhere near as fast as Java can copy the array; but in general, that's the best way to design a dynamically-resizeable array.)

Categories