I am a beginner coder at my Uni. We are tasked with reading a text file, verifying all the first letters of each word are capital, and then they are put in alphabetical order. I am trying to tackle one point at a time. So I decided to go with verifying all the first letters are capital by just making my own array of words and then figuring out how to do it from a text file after. This is what I have so far and it's nothing
I have tried Character.isUpperCase(arr.charAt(0));
but i am gettin an error
public void sortStrings() throws IOException {
String[] arr = {"Zebra", "test","Butter"};
String[] arr2 = {"Legends","Apex","Best"};
for(int i = 0; i < arr.length; i++) {
if(Character.isUpperCase(arr.charAt(0)));
}
Cannot invoke charAt(int) on the array type String] is the error I am getting with arr.charAt(0)
Appreciate any tips !
You forgot the index to access the item in your array. Replace arr.charAt(0) with arr[i].charAt(0)
String[] arr = {"Zebra", "test","Butter"};
for(int i = 0; i < arr.length; i++) {
if(Character.isUpperCase(arr[i].charAt(0)))
doSomethingHere();
}
Related
I'm tasked to take the words out of a txt file and then eliminate the duplicates and print out the rest. However there seems to be something weird going on when I place the for loop used to print out the array of words that are taken from the txt file.
When I do
for (String word:arr)
{
words = word.split(" ");
for (int i = 0; i < words.length; i++)
{
// Printing the elements of String array
System.out.print(words[i] + " ");
}
}
where, arr is an array of string; filled with sentences from the text file , and words is the individual words of the text file stored in array of strings, printing the array words will give what it is supposed to,
however when I do
for (String word:arr)
{
words = word.split(" ");
}// not nested so happens seperately
for (int i = 0; i < words.length; i++)
{
// Printing the elements of String array
System.out.print(words[i] + " ");
}
I only obtain 4 words out of the hundreds that are stored in the txt file.
Can someone help explain this? Thanks in advance!
In the second case you are processing outside of the first for, and you process just the last String that is in your array. Words variable gets overwritten in each itteration. My suggestion is to learn how to debug, it will greatly help you to learn.
I am trying to print user input from an array to display in java. When i run this, it just prints out "null" for each amount no matter what the user inputs. I am a beginner at java and want to learn more about arrays, and I can't seem to figure this out.
String itemAmount = ss.getInputString("How many items?");
int amount = Integer.parseInt(itemAmount);
String[] Items = new String[amount];
for (int i = 0; i < Items.length; i++) {
ss.getInputString("Please enter items?");
}
for (int i = 0; i < Items.length; i++) {
ss.println((Items[i]));
}
Also, how would i be able to print the items, for example user inputs 3 items -> "Eggs", "Bacon", "Tomato" how would I print this to show in a line separated by commas.
I'm not sure what gt is, but since you're using it this way
String itemAmount = gt.getInputString("How many items?");
I guess it's some sort of wrapper around the standard input.
You can use it the same way to populate an array, one item at a time.
for (int i = 0; i < Items.length; i++) {
Item[i] = gt.getInputString("Please enter items?");
}
You seem to be able to use the array in the other loop, so I'll assume you don't need further explanation.
Then to print them on a single line, separated by a comma you can use the join method of String (note: you need to convert your array to a List, first)
String joinedString = String.join(", ", Arrays.asList(Items));
I think you are checking the length of wrong array/string in second for loop. It should be Items.length not Appliances.length
I asked a question about the following method a while ago and came up with quite different question. Suppose I have String A B -> C or A B -> carry sum or X Y Cin -> Cout Sum. How can I extract the words before -> without including ->? And then extracting the words after ->?
public void parseContactsLine(String line)
{
String[] words = line.split("->");
for(int i = 0; i < words.length; i++)
{
}
}
Your first split for "->" will separate into two strings the list of words of each side.
Then you can re-split by spaces using .split("\\s"); to get a list of each words.
You would end up with
String[] wordsAfterLambda = line.split("->")[1].split("\\s");
for(String s : wordsAfterLambda)
System.out.println(s);
Notice that I used a for-each instead of for which I tend to prefer when there is no need to keep the index.
Edit
As per your comment, the [1] is to access the array value and not linked to the split itself, it is the same as doing
String[] words = line.split("->");
String[] wordsAfterLambda = words[1].split("\\s");
I have String Array of a good couple hundred lines of code. I have two other String Arrays, one with values I want to replace, and the other with the value I want it to replace to. I need to go through each line of the original code and check each line if it contains anything that I need to replace, and if it does, replace it. I want to replace it to a totally different String Array, so that the original is still left unchanged. This is what I have, but it's not exactly working.
for(int i=0; i<originalCode.length; i++) {
if( originalCode[i].contains("| "+listOfThingsToReplace[i]) ) {
newCode[i]=originalCode[i].replaceAll(("| "+listOfThingsToReplace[i]), ("| "+listOfReplacingThings[i]));
}
}
Obviously I need more counting variables somewhere (especially because originalCode.length !=listOfThingsToReplace.length), but I can't figure out where. Would I need more for loops? I tired doing that... but "Exception in thread "main" java.lang.OutOfMemoryError: Java heap space"... Any help please?
I think this should do the trick if I'm understanding the problem correctly
// New Code Array
String[] newCode = new String[originalCode.length];
for (int i=0; i<originalCode.length; i++) {
// New Code Line
String newCodeLine = originalCode[i];
// Iterate through all words that need to be replaced
for (int j=0; j<listOfThingsToReplace.length; j++) {
// String to replace
String strToReplace = listOfThingsToReplace[j];
// String to replace with
String strToReplaceWith = (j >= listOfReplacingThings.length) ? "" : listOfReplacingStrings[j];
// If there is a string to replace with
if (strToReplaceWith != "") {
// then replace all instances of that string
newCodeLine = newCodeLine.replaceAll(strToReplace, strToReplaceWith);
}
}
// Assign the new code line to our new code array
newCode[i] = newCodeLine;
}
Hey guys, I'm new to Java (well, 3/4 of a year spent on it).
So I don't know much about it, I can do basic things, but the advanced concepts have not been explained to me, and there is so much to learn! So please go a little but easy on me...
Ok, so I have this project where I need to read lines of text from a file into an array but only those which meet specific conditions. Now, I read the lines into the array, and then skip out on all of those which don't meet the criteria. I use a for loop for this. This is fine, but then when I print out my array (required) null values crop up all over the place where I skipped out on the words.
How would I remove the null elements specifically? I have tried looking everywhere, but the explanations have gone way over my head!
Here is the code that I have to deal with the arrays specifically: (scanf is the scanner, created a few lines ago):
//create string array and re-open file
scanf = new Scanner(new File ("3letterWords.txt"));//re-open file
String words [] = new String [countLines];//word array
String read = "";//to read file
int consonant=0;//count consonants
int vowel=0;//count vowels
//scan words into array
for (int i=0; i<countLines; i++)
{
read=scanf.nextLine();
if (read.length()!=0)//skip blank lines
{
//add vowels
if (read.charAt(0)=='a'||read.charAt(0)=='e'||read.charAt(0)=='i'||read.charAt(0)=='o'||read.charAt(0)=='u')
{
if (read.charAt(2)=='a'||read.charAt(2)=='e'||read.charAt(2)=='i'||read.charAt(2)=='o'||read.charAt(2)=='u')
{
words[i]=read;
vowel++;
}
}
//add consonants
if (read.charAt(0)!='a'&&read.charAt(0)!='e'&&read.charAt(0)!='i'&&read.charAt(0)!='o'&&read.charAt(0)!='u')
{
if (read.charAt(2)!='a'&&read.charAt(2)!='e'&&read.charAt(2)!='i'&&read.charAt(2)!='o'&&read.charAt(2)!='u')
{
words[i]=read;
consonant++;
}
}
}//end if
//break out of loop when reached EOF
if (scanf.hasNext()==false)
break;
}//end for
//print data
System.out.println("There are "+vowel+" vowel words\nThere are "+consonant+" consonant words\nList of words: ");
for (int i=0; i<words.length; i++)
System.out.println(words[i]);
Thanks so much for any help received!
Just have a different counter for the words array and increment it only when you add a word:
int count = 0;
for (int i=0; i<countLines; i++) {
...
// in place of: words[i] = read;
words[count++] = read;
...
}
When printing the words, just loop from 0 to count.
Also, here's a simpler way of checking for a vowel/consonant. Instead of:
if (read.charAt(0)=='a'||read.charAt(0)=='e'||read.charAt(0)=='i'||read.charAt(0)=='o'||read.charAt(0)=='u')
you can do:
if ("aeiou".indexOf(read.charAt(0)) > -1)
Update: Say read.charAt(0) is some character x. The above line says look for that character in the string "aeiou". indexOf returns the position of the character if found or -1 otherwise. So anything > -1 means that x was one of the characters in "aeiou", in other words, x is a vowel.
public static String[] removeElements(String[] allElements) {
String[] _localAllElements = new String[allElements.length];
for(int i = 0; i < allElements.length; i++)
if(allElements[i] != null)
_localAllElements[i] = allElements[i];
return _localAllElements;
}