Printing user input in array says null - java

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

Related

Unable to obtain values if for loop placed in a different line of code

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.

How can i loop through my String array and find the amount of occurrences of multiple strings?

I have an array in my modularized program and i am trying to find the amount of times Strings appear in the array. I cannot post my code as it violates my schools honor code, just looking some help....I cannot use any classes besides JOptionPane. Java code.
i am not sure cause you dont post your code but i know you want that :
String[] yourArray = {"test", "1234","test"};
String yourStringTest = "test";
int occurence = 0;
for(int i = 0; i < yourArray.length;i++) {
if(yourStringTest.equalsIgnoreCase(yourArray[i])) {
occurence++;
}
}
System.out.println("the string "+yourStringTest+" appear :"+occurence);

I want to print an element from an array

in my program I want the user to be able to print an element from an array. This is how far I've and I can't think of what to put next?
public void viewClub() {
System.out.println("Please enter the name of the country whose details you would like to see");
String Name = input.next();
for (int i = 0; i < countryList.size(); i++) {
Country x = countryList.get(i);
if (Name.equalsIgnoreCase(x.getName())) {
}
You anyways have x.getName in which x points to ith element of the array. So even if you just do a sys out for
x.getName()
you will get the value.
Hope this be of some help
Happy Learning :)
You want to output the details of a country that the user inputs. To do this, you will need a function in your country class that returns a string containing the details of that country:
System.out.println(x.getCountryDetails());
You don't want to output the name, because the user already knows that.
After you find the country, you should break out of your loop, to stop further processing:
for (int i = 0; i < countryList.size(); i++)
{
if (name.equalsIgnoreCase(countryList.get(i).getname()))
{
System.out.println(countryList.get(i).getCountryDetails());
break; //Exit the for loop because you found the specified country
}
}
firstly you take a array in your program, then by using buffered input streams or any other take the input from the user, store it into the array and then print the array index which contain the values

Retrieve string from list if we know the index

Is there a way to retrieve a string from an ArrayList if we know the index of the string we want to retrieve? for example in this string:
String text2 = "if(AGE_Y>15){\r\n"
+ "x=PROPERTY_LENGTH;\r\n"
+ "}";
The list this string is added to would look like : if, (, AGE_Y, >, 15, ), {, ...
Now if we loop through the list and add each item to a StringBuilder and define the index for each item:
for (int i = 0; i < list.size(); i++)
{
a=list.get(i);
strBuilder.append(a);
index = strBuilder.length() - a.length();
}
We will know exactly at what index we have the string "PROPERTY_LENGTH" for example.
My question is, how can we retrieve the string "x" from the List? I'm asking because at the line above "x"(or whatever that variable will be named) I want to insert something else in the StringBuilder. Normally we could do something like:
String previous=list.get(indexOfPropertyLength-2);
strBuilder.insert(index-previous.length-1,"string to insert");
Is this at all possible?
Firstly you can rewrite your list iteration to work more efficiently:
for (int i = 0; i < list.size(); i++) {
a=list.get(i);
index = strBuilder.length(); // (you don't have to calculate an index)
strBuilder.append(a);
}
To address the title of your question, if you want to simply find a String in a List given an index, you can of course use myList.get(myIntIndex);. However, it seems that you're asking how to find an index given a String: myList.indexOf(myString) or something of that nature. If you could be a bit clearer, we might be of more help. Are you writing a hybrid assembler or compiler?

Remove Null elements from a (String) Array in Java

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;
}

Categories

Resources