Loops inside of loops/Replace can't make them work - java

I want to delete all the vowels from every word inside of an array. So I came up with this:
public class AnotherExercise {
public static void main (String[] args){
String[] intruments = {"cello", "guitar", "violin", "double bass"}; //the array of words
String[] vowels = {"a", "e", "i", "o", "u"}; // the array of vowels
String[] intruments2 = new String[5]; //the array of wrods without vowels
String nothing = ""; // used to replace a vowel to nothing
for (int i = 0; i < 4; i++){ // first for loop to go through all of the intruments
for(int e = 0; e < 5; e++){ //second for loop to go through all the vowels
intruments2[i] = intruments[i].replaceAll(vowels[e], nothing); //replacing vowels
//and storing them in a new array
}
System.out.println(intruments2[i]); //outputting the words without vowels
}
}
}
From all the options I tried, I guess this one was the best, but still I can't make it work, it outputs:
cello
gitar
violin
doble bass
The weirdest part in my opinion is that it does replace "u". It may be a silly mistake but I can't figure it out.

Method String.ReplaceAll receives regex as first argument. It allows you to remove all vowels in one shot:
public class AnotherExercise {
public static void main (String[] args){
String[] intruments = {"cello", "guitar", "violin", "double bass"};
String[] intruments2 = new String[5];
String nothing = "";
for (int i = 0; i < 4; i++){
intruments2[i] = intruments[i].replaceAll("a|e|i|o|u", nothing);
System.out.println(intruments2[i]);
}
}
}
And, yes, about the problem with your version. In the inner loop you always apply replacement to initial version of the string. So you get results only from the last attempt ‒ letter 'u'.

Related

Java, extract integer values within defined characters from long string

I have a program where I receive a long string in the format
characters$xxx,characters$xx,characters$xx, (....)
x is some digit of some integer with an arbitrary number of digits. The integer values are always contained within $ and ,.
I need to extract the integers into an integer array then print that array. The second part is easy, but how to extract those integers?
an example string: adsdfsh$1234,khjdfd$356,hsgadfsd$98,ghsdsk$4623,
the arraay should contain 1234, 356, 98, 4623
below is my basic logic
import java.util.Scanner;
class RandomStuff {
public static void main (String[]args){
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
int count =0;
// counts number of $, because $ will always preceed an int in my string
for(int i=0;i<input.length();i++ ){
if (input.charAt(i)=='$')
count++;}
/* also I'm traversing the string twice here so my complexity is at least
o(2n) if someone knows how to reduce that, please tell me*/
int [] intlist = new int[count];
// fill the array
int arrayindex =0;
for (int i=0; i<input.length();i++){
if (input.charAt(i)=='$'){
/*insert all following characters as a single integer in intlist[arrayindex]
until we hit the character ','*/}
if (input.charAt(i)==','){
arrayindex++;
/*stop recording characters*/}
}
// i can print an array so I'll just omit the rest
keyboard.close();
}
You can use a regular expression with a positive lookbehind to find all consecutive sequences of digits preceded by a $ symbol. Matcher#results can be used to get all of the matches.
String str = "adsdfsh$1234,khjdfd$356,hsgadfsd$98,ghsdsk$4623";
int[] nums = Pattern.compile("(?<=\\$)\\d+").matcher(str).results()
.map(MatchResult::group)
.mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(nums));
It can done like this
var digitStarts = new ArrayList<Integer>()
var digitsEnds = new ArrayList<Integer>()
// Get the start and end of each digit
for (int i=0; i<input.length();i++){
if(input[i] == '$' ) digitsStarts.add(i)
if(input[i] == ',') digitEnds.add(i)
}
// Get the digits as strings
var digitStrings = new ArrayList<String>()
for(int i=0;i<digitsStart.length; i++ ) {
digitsString.add(input.substring(digitsStarts[i]+1,digitEnds[i]))
}
// Convert to Int
var digits = new ArrayList<Int>
for(int i=0;i<digitString;i++) {
digits.add(Integer.valueOf(digitStrings[i]))
}
In a very simple way:
public static void main(String[] args) {
String str = "adsdfsh$1234,khjdfd$356,hsgadfsd$98,ghsdsk$4623";
String strArray[] = str.split(",");
int numbers[] = new int[strArray.length];
int j = 0;
for(String s : strArray) {
numbers[j++] = Integer.parseInt(s.substring(s.indexOf('$')+1));
}
for(j=0;j<numbers.length;j++)
System.out.print(numbers[j]+" ");
}
OUTPUT: 1234 356 98 4623

I want to print the arrayList in reverse by passing the arraylist to a new stack in java

This assignment ask to implement printWordRun so that it prints whatever word run it can find starting from the beginning of the input list words. The word run should be printed in reverse order, with each word on a separate line. PrintWordRun is a method which takes a parameter called words which is an ArrayList<String>. The word run is a series of words in the input list, where each word is longer in length than the previous. The word run ends once we either encounter the end of the list, or we encounter a word whose length is equal to or shorter than the previous word.
The array is:
I
am
cat
with
happy
dog
sitting
the result should be:
happy
with
cat
am
I
To get full credit for this assignment, I have to use a stack to print it as I have done, but I cannot get the word "happy" into the stack. My output is:
I
am
cat
with
public class Program {
private void printWordRun(ArrayList<String> words) {
// Here is the code I Wrote.
Stack<String> wordRun = new Stack<>();
for(int i = 1; i < words.size(); i++) {
String str1 = words.get(i-1);
String str2 = words.get(i);
if(str2.length() < str1.length()) {
break;
}
if(str1.length() < str2.length()){
wordRun.push(str1);
}
System.out.println(wordRun);
}
}
public static void main(String[] args) {
Program program = new Program();
program.testPrintWordRun();
}
private void testPrintWordRun() {
ArrayList<String> words = new ArrayList<>();
words.add("I");
words.add("am");
words.add("cat");
words.add("with");
words.add("happy");
words.add("dog");
words.add("sitting");
System.out.println("Testing printWordRun...");
printWordRun(words);
System.out.println();
}
}
Here is one way to construct the printWordRun function:
Stack<String> wordRun = new Stack<>();
int maxLength = 0;
for(String s : words) {
if(s.length() > maxLength ) {
maxLength = s.length();
wordRun.add(s);
} else
break;
}
while(!wordRun.isEmpty())
System.out.println(wordRun.pop());
Just store a value of the current, maximum length and use this to compare your current string.
Output:
Testing printWordRun...
happy
with
cat
am
I
Start by adding the word to the stack with add(int index, E element) to insert the last item as first, and break the loop if the condition doesn't match afterwards.
private void printWordRun(ArrayList<String> words) {
// Here is the code I Wrote.
Stack<String> wordRun = new Stack<>();
for (int i = 1; i < words.size(); i++) {
String str1 = words.get(i);
String str2 = words.get(i - 1);
wordRun.add(0, str2);
if(str2.length() >= str1.length()) {
break;
}
}
System.out.println(wordRun); // [happy, with, cat, am, I]
}

Java: How to fill out two arrays, alternating between the two

I have a program that has two String arrays defined and initialized. I now want to accept inputs from the user to fill out the indexes of each array. I want the user to input index[i] for array 1 and then index[i] for array 2 and so on until both arrays are filled.
I attempted to use a nested loop to do this, but I was getting an out of bounds error.
Unfortunately, Google was not helpful as I kept finding the .fill() method, which I cannot currently use in my course.
The code below contains elements for the rest of the program which I haven't written. The below code is meant to complete the first part of the program and that is to get the list of words into the first two arrays and then output them to make sure they were filled correctly.
EDIT: Even though I got my answer, I tried updating the question for clarity. It looks like I was vastly overthinking the problem. It was my first time working with more than one array.
import java.util.Scanner;
public class LabProgram {
public static int findWordInWordList(String[] wordList, String wordToFind, int numInList) {
return -1; //Will replace words in a sentence, to be used coded and used later.
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] ogWords; //words to replace.
String[] newWords; //words to replace with.
String[] sentence; //the sentence that will be searched and have words replaced.
int pairSize; //size of the first two arrays.
pairSize = sc.nextInt();
ogWords = new String[pairSize];
newWords = new String[pairSize];
for (int i = 0; i < ogWords.length; i++) {
ogWords[i] = sc.next();
for (int j = 0; j < newWords.length; j++) {
newWords[j] = sc.next();
}
}
for (int i = 0; i < pairSize - 1; i++) { //Testing arrays
System.out.println(ogWords[i] + " " + newWords[i]);
}
}
}
The final for loop is just to test that the arrays were filled correctly, which isn't working right now :p.
Unless I've misunderstood your question, I think you're after:
for (int i = 0; i < pairSize; i++) {
ogWords[i] = sc.next();
newWords[i] = sc.next();
}

Determine if two words are anagrams

I recently took a quiz asking me to determine if elements in an array were anagrams. I completed an implementation, but upon running their tests, I only passed 1 of 5 test cases. The problem is, they wouldn't allow me to see what the tests were, so I'm really unsure about what I failed on. I've recreated my answer below, which basically multiplies the letters in a word and adds this number to an array. It then compares the numbers in one array to the numbers in the other, and prints true if they are the same. I'm basically asking what are some scenarios in which this would fail, and how would I modify this code to account for these cases?
public class anagramFinder {
public static void main (String[] args){
String[] listOne = new String[5];
listOne[0] = "hello";
listOne[1] = "lemon";
listOne[2] = "cheese";
listOne[3] = "man";
listOne[4] = "touch";
String[] listTwo = new String[5];
listTwo[0] = "olleh";
listTwo[1] = "melon";
listTwo[2] = "house";
listTwo[3] = "namer";
listTwo[4] = "tou";
isAnagram(listOne,listTwo);
}
public static void isAnagram(String[] firstWords, String[] secondWords){
int firstTotal = 1;
int secondTotal = 1;
int[] theFirstInts = new int[firstWords.length];
int[] theSecondInts = new int[secondWords.length];
for(int i = 0;i<firstWords.length;i++){
for(int j = 0;j<firstWords[i].length();j++){
firstTotal = firstTotal * firstWords[i].charAt(j);
}
theFirstInts[i] = firstTotal;
firstTotal = 1;
}
for(int i = 0;i<secondWords.length;i++){
for(int j = 0;j<secondWords[i].length();j++){
secondTotal = secondTotal * secondWords[i].charAt(j);
}
theSecondInts[i] = secondTotal;
secondTotal = 1;
}
for(int i=0;i<minimum(theFirstInts.length,theSecondInts.length);i++){
if(theFirstInts[i] == theSecondInts[i]){
System.out.println("True");
} else {
System.out.println("False");
}
}
}
public static int minimum(int number,int otherNumber){
if(number<otherNumber){
return number;
} else {
return otherNumber;
}
}
}
In my above example that I run in the main method, this prints True True False False False, which is correct
Copying my answer from a similar question.
Here's a simple fast O(n) solution without using sorting or multiple loops or hash maps. We increment the count of each character in the first array and decrement the count of each character in the second array. If the resulting counts array is full of zeros, the strings are anagrams. Can be expanded to include other characters by increasing the size of the counts array.
class AnagramsFaster{
private static boolean compare(String a, String b){
char[] aArr = a.toLowerCase().toCharArray(), bArr = b.toLowerCase().toCharArray();
if (aArr.length != bArr.length)
return false;
int[] counts = new int[26]; // An array to hold the number of occurrences of each character
for (int i = 0; i < aArr.length; i++){
counts[aArr[i]-97]++; // Increment the count of the character at i
counts[bArr[i]-97]--; // Decrement the count of the character at i
}
// If the strings are anagrams, the counts array will be full of zeros
for (int i = 0; i<26; i++)
if (counts[i] != 0)
return false;
return true;
}
public static void main(String[] args){
System.out.println(compare(args[0], args[1]));
}
}
The idea of multiplying ASCII codes isn't bad, but not perfect. It would need a deep analysis to show that two different words could have the same products, with the given range of 'a' to 'z', and within reasonable length.
One conventional approach would be to create a Map for counting the letters, and compare the Maps.
Another one would sort the letters and compare the sorted strings.
A third one would iterate over the letters of the first word, try to locate the letter in the second word, and reduce the second word by that letter.
I can't think of a fourth way, but I'm almost certain there is one ;-)
Later
Well, here's a fourth way: assign 26 prime numbers to 'a' to 'z' and (using BigInteger) multiply the primes according to the letters of a word. Anagrams produce identical products.

how do i make it so nextLine equals two strings in an array

I am trying to get my string letters to show me the index for every letter given as input. For example when I input a it returns 0 which is the index. Currently if I input a word with letter a and b it wont return anything. But it should return 0 and 1.
String[] code = {"a", "b","c", "d", "e"};
String letters=input.nextLine();
for (int i=0;i<code.length;i++) {
if (letters.equals(code[i])) {
System.out.print(i);
}
}
You have to treat both elements the same way, as in:
for (char charFromUser : letters.toCharArray()) {
for (int i=0; i < code.length; i++) {
if (code[i] == charFromUser) {
... print i
In other words: you intend to compare characters, one by one. Then using equals() on the complete string given by the user doesn't help you.
You'll need to loop through your input character by character in order to return more than one letter's index number
Try somethink like this :
char[] List={'a','b','c','d'};
int count=0;
for(int i=0;i<List.length;i++){
for (int j=0;j<input.length();j++) {
if(input.charAt(j)==List[i]){
count++;
}
}
}
System.out.println(count);
you can try with this agine
public class StringTest {
public static void main(String[] args) {
String[] code = {"a", "b", "c", "d", "e"};
Scanner input = new Scanner(System.in);
while (true) {
System.out.printf("please input:");
String letters = input.nextLine();
boolean isMatch = false;
for (int i = 0; i < code.length; i++) {
if (letters.equals(code[i])) {
isMatch = true;
System.out.println(i);
}
}
if (!isMatch) {
System.out.println("not equal");
}
}
}
}
As #GhostCat answered, you are not comparing the characters in your input one by one with the values in your array. Another alternative is to use the built-in String::indexOf method to get this even easier:
String code = "abcde";
String letters = input.nextLine();
for (char c : letters.toCharArray()) {
System.out.print(code.indexOf(c));
}
Input >> ab
Output >> 01

Categories