Using for loops to calculate the certificate of deposit [duplicate] - java

This question already has answers here:
Difference between setText() and append()
(5 answers)
Closed 6 years ago.
For a highschool project I created a for loop that displays the 5 songs I initialised. I put it under the a button called btnInitializeActionPerformed so when the initialized button is pressed, it displays the songs, however it only displays the last song, what am I doing wrong?
Here is the loop
Collections.addAll (strSongArtist, "Dont Stop Believing", "this", "hello", "Think", "No");
for (int i = 0; i < strSongArtist.size(); i++) {
String valueContent = strSongArtist.get(i);
txtOutput.setText( valueContent);
}
when I display strSongArtist like this in side the for loop:
System.out.println(strSongArtist.get(i));
Btw my teacher gave an example of outputing the code like this:
txtOutput.setText( strSongArtist.get(rn.nextInt(strSongArtist.size())).toString());
but I have no idea how to use this either?

Your problem is that you are calling txtOutout.setText() during each loop iteration.
So, even if textOutput is some label/panel whatsoever that would be able to display more than string ... what you are doing is that you are telling it to only display that one string that you are passing to it.
Meaning: you have a loop that produces 5 individual strings. If you want those 5 strings to show up together, you have to build something that contains all those 5 individual strings.
You can either do that by collecting the results of your "get(i)" calls using a StringBuffer; or you call setTest() with the result of "getText() + "\n" + get(i)" ...

Every time the loop runs it is setting the text of txtOutput to the value of the valueContent, so it will display the last artist at the end of the loop. You should at least create a string and append each artist to it and set the text at the end of the loop
String artists = "";
for (int i = 0; i < strSongArtist.size(); i++) {
artists += strSongArtist.get(i) + ", ";
}
txtOutput.setText( artists );

Related

How should I print out the position of the first occurrence of a specific letter in a String? [duplicate]

This question already has answers here:
Java: method to get position of a match in a String?
(14 answers)
Closed 2 years ago.
Say my string is as follows
String str = "What is up tod?";
I want to use an accessor method to print out the position of the first occurrence of the letter "t". What is an efficient use of code to use? I also want to ensure that it doesn't try to tell me the occurrence of the second "t". Please keep in mind I am searching for how to do this in Java.
Any help or link to similar question is greatly appreciated.
Unless I'm missing something, use String.indexOf(int) like
String str = "What is up tod?";
System.out.println(str.indexOf('t'));
Which outputs the first match
3
Alternatively, iterate the characters of the String from left to right checking for 't'; if you find it, print the index and terminate the loop. Like,
String str = "What is up tod?";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 't') {
System.out.println(i);
break;
}
}

Problems Formatting .CSV Output

I am currently programming an assignment for a class of mine. I am trying to print to my output file to a csv file. The problem is, after I end my second print statement, my output doesn't line up after starting the print statement in my while loop.
For example, here is my code:
oFile = new PrintStream(new File("output.csv"));
oFile.println("First Name" + "," + "Last Name" + "," + "Lecture Section"+","+"Lab Section"+","+"Lab 1"+","+"Lab 2"+","+"Lab 3"+","+"Lab 4"+","+"Lab 5"+","+"Lab 6"+","+"Lab 7"+","+"Lab 8"+","+"Lab 9"+","+"Lab 10");
loadLectureArray();
loadLabArray();
sortClassSections();
for (int i = 0; i < stud.size(); i++) {
oFile.println(stud.get(i).getStudFirstName() + ","+stud.get(i).getStudLastName()+","+stud.get(i).getStudLectureNum()+","+stud.get(i).getStudLabNum()+",");
while (numLab < 10 && i < stud.size()) {
oFile.println(labStud.get(i).grades.getStudLabGrade()[numLab]);
numLab++;
}
numLab = 0;
}
After I execute my while loop, my new data is printed in-between my header and other data. Some of the code is not perfect, but currently I am just seeking advice about reformatting my output to line back up with the print statements.
This is my first time exporting a file to csv, so if there is something I am doing wrong or need to change, please let me know! I hope you can make sense out of what I'm trying to ask for. Thanks in advance!
well, println always prints a newline, so you get a newline after every grade. you should be able to get what you want using oFile.print(...) instead of oFile.println(...) inside the for loop and just one oFile.println() at the very end of it.
i also noticed that the test for i < stud.size() in the head of the while loop is redundant since nothing should be changing either i or stud.size() between this test and the same test in the head of the for loop.

Taking an element of An ArrayList and passing it as an argument [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am having a bit of a hiccup with this ArrayList. I am trying to store one or more elements from a String array into an Array list and assigning it to some string variable. My goal is to store keywords into an array list which i could use to search a text file. I can't seem to store found keywords into the array list Can someone help me figure this issue out? Here's some snippets from my code.
public static void main(String args[]) throws ParseException, IOException
{
List<String> matches = new ArrayList<String>();
String[] keywords = {"day", "book", "office", "hour",
"date of a test", "number of assignments", "sure",
"current assignment", "due day"};
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
int count = 0;
for (int i = 0; i < keywords.length; i++) {
if (input.contains(keywords[i])) {
matches.add(keywords[i]);
parseFile(keywords[i]);
}
}
}
And here is my parseFile method
public static void parseFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
// break;
}
}
}
One of the first things I'd do, is check that the stuff is actually going in to the array, so I'd have this:
if(matches.size() == 0)
{
System.out.println("There's nothing in here");
}
That way at least you know that there's nothing there, so then there's no point doing the rest of the program. You should always test your exit condition early where possible that way you save a bit of time, and energy, and allows for quicker debugging. But I digress.
So to add the stuff in to the array list you'd need to do the following:
for (int i = 0; i < keywords.length; i++)
{
String value = keywords[i];
System.out.println("Current Value is: " + value);
matches.add(value);
}
You can't just add an array element as the add method in ListArray is expecting a String. So you need to set the current content of the array to a String then pass THAT in to your matches.add function as above, so when I ran that program on my box, (just the main bit that is) I got the following output.
Current Value is: day
Current Value is: book
Current Value is: office
Current Value is: hour
Current Value is: date of a test
Current Value is: number of assignments
Current Value is: sure
Current Value is: current assignment
Current Value is: due day
Size of matches is: 9
Matches[i]: day
Matches[i]: book
Matches[i]: office
Matches[i]: hour
Matches[i]: date of a test
Matches[i]: number of assignments
Matches[i]: sure
Matches[i]: current assignment
Matches[i]: due day
Also for the record, you need to do the same when you're iterating through your matches as well, so let's say you want to print out your ArrayList, then you'd need to do the following:
for(int i = 0; i < matches.size(); i++)
{
String value = matches.get(i);
System.out.println("Matches[i]: " + value);
}
You'd need to get the string within the array list, you can't just give it an index, as that will not work, again you need to assign it to a string and then pass that back.
If in doubt, dive on to the Java ArrayList API, and have a look at what arguments the functions take.
Hope that helps.

How do I print an array without the first term?

I'm writing a program to open up links based on a command entered into a console. The command is "/wiki >term array<", and it will open up a web browser with the wiki open and the term array sent through the search function of said wiki.
Here is my current code for building the term array to send to the search field:
SearchTerm = Arrays.toString(StringTerm).replace("[", "").replace("]", "").replace(",", "");
Now, all that does is get all terms passed the word "/wiki" in my slash command and prints them into a list. It also removes commas and square brackets to make what it prints cleaner.
-- I want to add a specific parameter for the first term in the array, so if it is a specific code such as "/wiki wikipedia chickens" is entered, it will send the user to wikipedia with the term "chickens" searched instead of the default wiki with the terms "wikipedia chickens" searched.
Using the current code that I have to build the term array I need to use Arrays.toString in order to print the whole array in a readable fashion, but I don't want it to print the first term in the array after it passes through my keyword filter?
When I use this code:
WIKI_HYPERLINK = WIKI_WIKIPEDIA + StringTerm[1] + StringTerm[2] + StringTerm[3] + StringTerm[4] + StringTerm[5];
It uses array terms 1 - 5, but if there are only 3 entered terms it will throw an error, and if there are more than 5 it will throw an error.
So my question is: How do I get a whole array excluding the first term?
You could use StringBuilder in a loop
// StringBuilder with initial String
StringBuilder builder = new StringBuilder(WIKI_WIKIPEDIA);
for (int i=1; i < stringTerm.length; i++) {
builder.append(stringTerm[i]);
}
String searchTerm = builder.toString();
You could try something like this:
String outputString = "";
for (int i = 1; i < StringTerm.Length; i++)
{
outputString += StringTerm[i];
}
You may also be able to use a for each loop if there is something like if (Array.Element != 0) in Java, but I don't know of one. Just edit the code above to get it in the format you need.

Not Displaying Array List properly?

I only have one arrayList and I want the out put to print in table format I know with Arrays you would need to use a nested for loop one for the rows and the other for the columns, How would I be able to have my output be in a table format when using arrayList my for loop:
System.out.print("Inv/Mo.\tRate\tYears\tFuture Value\n");
for (int i = 0; i < FutureValueArrayList.size(); i++)
{
String FutureValueArray = FutureValueArrayList.get(i);
System.out.print(FutureValueArray + "\t");
}
my for loop gives me an output like this:
$100.00 2.0% 2 $2,450.64 $150.00 2.0% 2 $36,420.71
The bold values are a second entry by the user. How do I get it to display on the second line and for every new entry of values it outputs it line by line as opposed to everything in one line? I tried print/println and it still out puts everything in the first line.
Use Guava library where is Joiner.on(" ").join(arraylist); it produces nicely formatted output, you can define even custom iterators or filters in guava.
https://code.google.com/p/guava-libraries/wiki/StringsExplained#Joiner
To format output better you can use stringObject.replace(x,y); which allows you to replace symbols by e.g. \n - new line or you can add more spaces ...
String str = sentence.replace("and", " ");

Categories

Resources