ArrayList and strings - java

I have this question Write a static method which takes an ArrayList of Strings and an integer and changes the ArrayList destructively to remove all Strings whose length is less than the integer argument. i have this code so far could someone explain where I'm going wrong. it compiles but it doesn't remove any strings from the array list.
import java.util.*;
public class q4
// Shows adding a string after all occurrences of a string
// constructively in an ArrayList
{
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
ArrayList<String> a = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<words.length;j++)
{
String b =a.get(j);
if(b.length()<len)
{
a.remove(j);
}
}
System.out.println("The ArrayList is "+a);
}
}

When you remove an item of the ArrayList be sure to decrement "j". Also, although it is not common, set the for-condition to j < a.size(). Otherwise create a separate variable to store the size before the loop and then decrement it as well.
The following code should work.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
ArrayList<String> a = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<a.size(); j++)
{
String b =a.get(j);
if(b.length()<len)
{
a.remove(j);
j--;
}
}
System.out.println("The ArrayList is "+a);
}

You traverse the list from left to right and remove items as you go along. This causes a problem when removing multiple items, because the indices don't match any more.
This can be fixed quite easily by traversing the list from end to begin, instead of from begin to end.
Because now, if you remove an item, this doesn't affect the items to be removed later on:
for (int j = words.length - 1; j >= 0; j--)

import java.util.*;
public class q4
// Shows adding a string after all occurrences of a string
// constructively in an ArrayList
{
public static ArrayList<String> a;
public static ArrayList<String> presenter;
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
a = new ArrayList<String>();
presenter = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<words.length;j++)
{
String b =a.get(j);
if((b.length()<len))
{
//do nothing
}
else
{
presenter.add(a.get(j));
}
}
System.out.print("The ArrayList is " + presenter);
}
}
This is an alternative since you said the other codes didn't work, I simply transferred the "Good" data to another arraylist and printed out that one.

Related

Having trouble with figuring out how to create a nested loop with arrays

I'm currently having trouble defining the nested loop and arrays for the current problem:
Write a program that reads an integer, a list of words, and a character. The integer signifies how many words are in the list. The output of the program is every word in the list that contains the character at least once. For coding simplicity, follow each output word by a comma, even the last one. Add a new line to the end of the last output. Assume at least one word in the list will contain the given character. Assume that the list of words will always contain fewer than 20 words.
This is what I have so far
import java.util.Scanner;
public class labProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String[] userList = new String[20];
int numElements = scnr.nextInt();
char userChar = scnr.next().charAt(0);
int i;
for(i = 0; i < userList.length(); ++i) {
userList[i] = scnr.next();
}
}
}
What steps should I take to define and loop this problem?
You need to loop through each word by performing adding an inner for loop that iterates through each character in word[i]. Inside of this inner loop, you can check to see if the current character matches the target character that you want.
//loops through the list of words
for(int i = 0; i < userList.length; i++){
boolean letterExists = false;
// inner for loop will iterate through each character in wordlist[i]
for(int j = 0; j < userList[i].length; j++) {
char currentLetter = userList.charAt(j);
if(currentLetter == userChar)
letterExists = true;
}
// print if the user exists
if(letterExists)
System.out.println(userList[i]);
}
You can exchange the order of some instruction to make the array as long as you wish.
Here an example:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int numElements = scnr.nextInt(); // ask the user the elements of the array
String[] userList = new String[numElements]; // create the array
char userChar = scnr.next().charAt(0); // ask the user for the char to search
// adding the strings to the array
for(int i = 0; i < userList.length; ++i) {
userList[i] = scnr.next();
}
// searching the char in the strings and printing the matched strings
System.out.println("Matched Strings: ");
for (int i=0; i < userList.length; i++)
for (int j=0; j < userList[i].length(); j++)
if (Character.compare(userList[i].charAt(j), userChar) == 0) {
System.out.print(userList[i] + ",");
continue;
}
}
}
Consider also to not use the instruction continue, you can use a new array to store the matched strings instead.

Java: I made a program that accepts input for an integer array & displays values in a table. Trying to recreate this using a string array. Pls. help,

Java is my first programming language, and I'm still unfamiliar with how arrays work. However, I was able to make this program, which accepts user-input for an integer array; it then outputs indexes and values, to show how arrays store numbers. I would like to recreate this program using a string array, to make a table containing a list of friends.
The .length property also confuses me...
Could someone explain the .length property and help me make the string array program work?
Thank you very much.
Here is the working code for the integer array table program
import java.util.*;
public class AttemptArrayTable
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Let me show you how arrays are stored ");
System.out.println("How many numbers do you want your array to
store? ");
int arrayInput [] = new int[scan.nextInt()];
System.out.println("Enter numbers ");
for (int count = 0; count<arrayInput.length; count++)
arrayInput[count] = scan.nextInt();
System.out.println("");
System.out.println("Index\t\tValue");
for (int count2=0; count2<arrayInput.length; count2++)
System.out.println(" [" + count2 + "]"+"\t\t " + arrayInput[count2]);
}
}
Here is the code for the string array program I'm working on
import java.util.*;
public class ArrayTableofFriends
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("How many female friends do you have? ");
String arrayOfFriendsFem [] = new String [scan.nextInt()];
System.out.println("List the name of your female friends");
for(int countF = 0; countF<arrayOfFriendsFem.length; countF++)
arrayOfFriendsFem[countF]= scan.nextLine();
System.out.println("How many male friends do you have? ");
String arrayOfFriendsMale [] = new String [scan.nextInt()];
System.out.println("List the name of your male friends");
for(int countM = 0; countM<=arrayOfFriendsFem.length; countM++)
arrayOfFriendsMale[countM]= scan.nextLine();
System.out.println("How many alien friends do you have? ");
String arrayOfFriendsAliens [] = new String [scan.nextInt()];
System.out.println("List the name of your alien friends");
for(int countA = 0; countA<=arrayOfFriendsFem.length; countA++)
arrayOfFriendsAliens[countA]= scan.nextLine();
{
System.out.println("Female\t\t\t" + "Male\t\t\t" + "Aliens");
for(int countF2 = 0; countF2<arrayOfFriendsFem.length; countF2++)
System.out.println(arrayOfFriendsFem[countF2]);
for(int countM2 = 0; countM2<=arrayOfFriendsMale.length; countM2++)
System.out.println("\t\t\t" + arrayOfFriendsMale[countM2]);
for(int countA2 = 0; countA2<=arrayOfFriendsAliens.length; countA2++)
System.out.println("\t\t\t\t\t\t" +arrayOfFriendsAliens[countA2]);
}
}
.length property stores number of elements in the array. But elements are starting from 0. So, when .length = 1, then there is only one element in the array, with index 0.
It seems in your String arrays program in the for loop the <= should be changed to <
Like this:
for (int countA = 0; countA < arrayOfFriendsFem.length; countA++)

java user-defined array (and user-defined array size) returning [null, null, null, ...]

This is my first question on this site, I'm running this on NetBeans 8.0.2 and trying to print out my user-defined array but it keeps returning null values. For example if you say there are 2 employees and enter both of their names, it will return [null, null]
How to fix this error? I'm a novice.
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Arrays;
class Tips_Calculation2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("How many employees for the week?: ");
int numberOfEmps = scan.nextInt();
// counter for the if statement that should return all employees from the array
int counter = numberOfEmps;
int[] nOEarray = new int[numberOfEmps];
System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");
for(int i = 1; i <= numberOfEmps; i++)
{
String nameCycler = scan.next();
String[] namesArray = new String[i];
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
}
}
}
}
Disregard import java.text.DecimalFormat as I plan to use this import later on in my code. Thank you in advance to anyone who is kind/smart enough to respond.
First of all you never put your nameCycler to array. Second of all you create your namesArray every iteration which I think is wrong.
You're creating a brand new (full of null) array namesArray on every pass through the loop--and then never assigning anything to it. I think you're looking for something like this instead. Note that Java indexes from zero, not one.
String[] names = new String[numberOfEmps]
for(int i = 0; i < names.length; i++) {
names[i] = scanner.next();
}
System.out.println(Arrays.toString(names));
First of all, you should initialise the array outside of your loop. Secondly, you forgot to set the name to the array value(s).
Try this:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Arrays;
class Tips_Calculation2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many employees for the week?: ");
int numberOfEmps = scan.nextInt();
int[] nOEarray = new int[numberOfEmps];
System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");
String[] namesArray = new String[numberOfEmps];
for (int i = 0; i < numberOfEmps; i++) {
namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));
}
}
Replace
for(int i = 1; i <= numberOfEmps; i++)
{
String nameCycler = scan.next();
String[] namesArray = new String[i];
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
}
}
With
String[] namesArray = new String[numberOfEmps];
for(int i = 0; i < numberOfEmps; i++)
{
namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));
And see whether it works.
You never assign the name to the array and in every iteration you define the array new:
String[] namesArray = new String[numberOfEmps];
for(int i = 1; i <= numberOfEmps; i++)
{
String nameCycler = scan.next();
namesArray [i] = nameCycler ;
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
}
}
Added comments in the code to point out changes.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many employees for the week?: ");
int numberOfEmps = scan.nextInt();
// removed 'nOEarray' and 'counter'
if (numberOfEmps > 0) {
System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");
// initializing 'namesArray' outside for loop.
String[] namesArray = new String[numberOfEmps];
for(int i = 0; i < numberOfEmps; i++) { // initialized with 0 and updated condition with '<'
namesArray[i] = scan.next(); // assigning value to 'i'th position of namesArray
}
System.out.println(Arrays.toString(namesArray)); // Printing array outside for loop
}
}
"How to fix this error" not. This is not an error.
String[] namesArray = new String[i]; // step one, you declare an array of Strings
// which you don't initialize
if(counter == i)
{
System.out.println(Arrays.toString(namesArray));
//you print all the (non-initialized) elements of namesArray
//since you didn't initialize the elements, it takes the default value, which is null
}
fill the elements of the array with Strings before trying to print them.

counting the alphabets from input

I need to write a code in java, which will take the input as a string from the user and will print the count of repetition of each alphabet. I Ihave written the code but not got the correct output.
input:ppooj
output:p1,o2,j1
My code is:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello");
System.out.println("ENTER ANY STRING");
Scanner sc= new Scanner(System.in);
String[] arr= new String [5];
for(int i=0; i<5 ;i++ )
{
arr[i]= sc.next();
// getting input
}
for ( int i=0;i<5;i++){
System.out.print(""+ arr[i]);
}
int count=1;
int rep=0;
int i=0;
for ( i=0;i<5;i++)
{
//traverse
System.out.println("in first loop" + ""+ arr[i]);
for(int k=i+1; k<5;k++)
{
System.out.println("" + arr[k]);
//matching with each and every one
if(arr[i]==arr[k])
{
count++;
System.out.println("got the match" + count);
}
}
System.out.println(arr[i]+count+",");
count=1;
}
}
}
You can follow these steps.
Read input.
split the input to characters. (You can get the char[] from String)
Iterate the char[] and you can use Map<Character,Integer> to store character vs number of occurrences.
Now your map contains all characters with occurrences.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class AlphaCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string");
String str = sc.nextLine();
Map<Character, Integer> map = new HashMap<Character, Integer>();
char[] chArray = str.toCharArray();
for(char c : chArray){
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}
else{
map.put(c, 1);
}
}
for (Entry<Character, Integer> entry : map.entrySet())
{
System.out.print(entry.getKey() + "" + entry.getValue()+" ");
}
}
}
If you use only alphabets, try this approach
Take an array of size 26
Assign array with 0
let the index be the alphabet position like 0-a, 1-b ... 25-z
oop through the input string and increment the respective index position like
array[inputString.charAt(i)-'a']++;
Print the result accordingly
Use equals method to compare reference objects value. As sometimes it get struck in the heap. So, it is better to use equals method over "==" while comparing values of reference objects.
Array is a reference type object.
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello");
System.out.println("ENTER ANY STRING");
Scanner sc= new Scanner(System.in);
String[] arr= new String [5];
for(int i=0; i<5 ;i++ )
{
arr[i]= sc.next();
// getting input
}
for ( int i=0;i<5;i++){
System.out.print(""+ arr[i]);
}
int count=1;
int rep=0;
int i=0;
for ( i=0;i<5;i++)
{
//traverse
// System.out.println("in first loop" + ""+ arr[i]);
for(int k=i+1; k<5;k++)
{
// System.out.println("" + arr[k]);
//matching with each and every one
if(arr[i].equals(arr[k]))
{
count++;
System.out.println("got the match" + count);
}
}
System.out.println(arr[i]+count+",");
count=1;
}
}
}
Try this code. You can modify it as per your requirement in the application.
You can try Map with String as the key like this:
Map<String,Integer> map = new HashMap<String,Integer>();
// set value = 0 to characters from a-z.
for( int i = 'a'; i < 'z'; i++ ){
map.put(String.valueOf((char)i), 0);
}
// supposed you have this as your input array. This should be read from file.
String[] arr= {"p","p","o","o","j"};
// count the duplicated characters.
for(int i=0;i<arr.length;i++){
map.put(arr[i],map.get (arr[i])+1);
}
// remove duplicated characters in array.
List<String> list= new ArrayList<String>(new LinkedHashSet<String>(Arrays.asList(arr)));
// print result.
for (String string : list) {
System.out.print(string+map.get(string));
}

Alphabetizing strings and reversed strings?

For this program, I need to have the user input strings, which will then be put into an array along with their reversed counterparts. The entire array would then be alphabetized. So it should work like this:
Input: strawberry banana, apple, grapes
Output: apple, ananab, banana, elppa, grapes, separg, strawberry, yrrebwarts
I have the code for this, and it works to some degree. However, it only alphabetizes the reversed and the normal but separately. So it ends up looking like this:
Output: ananab, elppa, separg, yrrebwarts, apple, banana, grapes, strawberry
As you can see it is alphabetizing the words to some degree, but not how it should be. Here is my code:
import java.util.Scanner;
public class WordGame {
public static void main(String[] args) {
String reverseInput = " "; //creates an empty string where the reverse will be stored before putting it into the array
String[] wordArray = new String[1000]; //creates an array that allows for 500 words, and 500 reverses of said words
int s = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the words you would like to reverse. To finish entering words enter a blank line:");
String userInput = sc.nextLine(); //allows for user to input words
int length = userInput.length();
int i = 0;
while (!userInput.equals("")){ //runs until the user enters a blank line
reverseInput = " ";
for(i = length - 1; i >= 0; i--)
reverseInput += userInput.charAt(i);
wordArray[s] = userInput; //reverses user inputted strings by taking the last letter and putting it in front, repeating until the whole word is reversed
wordArray[s + 1] = reverseInput;
s += 2;
userInput = sc.nextLine();
length = userInput.length();
}
for(int j = 0; j < s-1; j++){ //beginning of alphabetical sorting
for(int k = 0; k < s-1-j; k++){
int l = 0;
while((int)wordArray[k].charAt(l) == (int)wordArray[k+1].charAt(l))
l++;
if ((int)wordArray[k].charAt(l) > (int)wordArray[k+1].charAt(l)){
String holder = wordArray[k];
wordArray[k] = wordArray[k+1];
wordArray[k+1] = holder;
}
}
}
for(i = 0; i < wordArray.length; i++){
if (wordArray[i]!= null){
System.out.print(wordArray[i] + " "); //prints out contents of array
}
}
}
}
I am not sure what the issue is. Any help would be much appreciated. Thanks!
As far as I can see you put an extra blank in front of your "reverseInput" with reverseInput = " ";
Because your reverse string won't start with a char you think (it starts with a blank) the result is not what you really want. Try to delete the blank and retry you code.
There are definitely easier ways to do this, depending on if you want to use Java's built in classes for this kind of thing. I just wrote this up, it accomplishes the sort with reversed Strings that you want.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Solution {
public static void main(String args[]) {
ArrayList<String> values = new ArrayList<String>();
values.add("strawberry");
values.add("banana");
values.add("apple");
values.add("grapes");
Solution s = new Solution();
values = s.sortList(values);
int itemCt = 1;
for (String item : values) {
System.out.println(itemCt + ": " + item);
itemCt++;
}
}
public ArrayList<String> sortList(List<String> strings) {
ArrayList<String> combinedList = new ArrayList<String>();
for (String str : strings) {
combinedList.add(str);
combinedList.add(new StringBuilder(str).reverse().toString());
}
Collections.sort(combinedList);
return combinedList;
}
}

Categories