How to go to next line while using a loop to setText in JTextArea? - jtextarea

This is my code
for (int m=0; m < i ; m++){
ta1.setText( s[m].getName().toString() + ", " + s[m].getProgramName().toString() + ", " + s[m].getUni1() + ", " + s[m].getUni2() + ", " + s[m].getUni3() + ", " );
}
It's supposed to print a line from an array of student ( called s) into a JTextArea ( called ta1 ). the problem is that it always only prints the last student in the array.
I need to print each student in a new line. could anyone help me sort it out?

When you set text on an element, the current position in the loop will take over the last one.
Try doing this.
String s = "";
for(int m = 0, m <i; m++){
s += s[m].getName.toString() + ", " + s[m].getprogramName().toString() + "\n;
}
ta1.setText(s);
Create a string and add each entry to it then add new line to end of each entry "\n"
Then do.
ta1.setText(s);

setText overwrites whatever is the current text.
You need append instead; you also need a "\n" at the end of a line.

Related

CSV file parsing in C#

Wanted to check if there is any null value in column field in the csv file and also there shouldn't be null value after / in number column, if it is null the entire row should not be written to output file.
name,number,gender,country
iva 1/001 f Antartica
aaju 2/002 m russia
lax 3/ m brazil
ana 4/004 f Thailand
vis 5/005 m
for e.g. 3rd and 5th row should not be written to output file.
using (StreamWriter file = new StreamWriter(filepathop)) {
for (int i = 0; i < csv.Length; i++) {
{
if (i == 0) {
file.WriteLine(header + "," + "num" + "," + "serial" + "," + "date");
}
else {
var newline = new StringBuilder();
string[] words = csv[i].Split(',');
string[] no = words[1].Split('/');
string number = no[0];
string serial = no[1];
newline.Append(number + "," + serial + "," + tokens[0]);
file.WriteLine(csv[i] + "," + newline);
}
}
}
}
}
}
}
You can test for null columns with string.IsNullOrEmpty(column) or column.Length == 0 like so:
if (!string.IsNullOrEmpty(serial) && !string.IsNullOrEmpty(country))
file.WriteLine(csv[i] + "," + newline);
You might want to check and remove white space, too. Depends on your input.

Swift - Update UITextView with string using IBAction without deleting old string

I am trying to send and update strings inside a UITextView using and IBAction button.
the code below works fine however, every time i push the button the old text is replaced with the new one. What I am trying to do is to always append the text to the exiting one.
Any Idea?
#IBAction func equalPressed(sender: AnyObject) {
var resultString:String = "new string"
textView.text = resultString.stringByAppendingString("= " + resultLabel.text! + ";")
}
You already know how to append strings, but you're doing it two different ways. The stringByAppendingString(_:) method is fine, but Swift's + operator is clearer. I'd rewrite your existing method as follows:
#IBAction func equalPressed(sender: AnyObject) {
let resultString = "new string"
textView.text = resultString + "= " + resultLabel.text! + ";"
}
Then, to append the text rather than replace it, it's a simple change of including the old value in the new one:
textView.text = textView.text + resultString + "= " + resultLabel.text! + ";"
Or, using the += operator (x += y is short for x = x + y):
textView.text += resultString + "= " + resultLabel.text! + ";"

Adding multiple shapes in d3

I would like to add different shapes depending on one of the properties in my json file. I found this approach by Mike:
https://groups.google.com/forum/#!topic/d3-js/4EJDu1xOh8Y
The idea is great, I'm just not sure how to adapt it. I either want to add a circle or an svg:use element (with attr("xlink:href")). They both have (of course) different attributes. So how do I do that? What do I append? In the example, the attr("d") was also used, do I need that also?
That's what I have so far but I'm not sure what to add where.
I really appreciate your help!
var type = d3.scale.ordinal()
.domain(["Q", "C"])
.range("circle","svg:use");
for(l=0;l<4;l++){
currentsvg.selectAll("path")
.data(queryArray[l])
.enter()
.append("svg:path")
.type(function(d,i) {
if (queryArray[l][i].name.substr(0,1) == "Q"){
return type("Q");
}
else if (queryArray[l][i].name.substr(0,1) == "C"){
return type("C");
}
});
}
Below is a different solution without filtering that uses the path to draw the shapes. It doesn't use the "rect" or "circle" of svg but rather just uses the path to draw the shapes. Check out here for more on paths. Note that the circle is two connecting arcs. It also classes each shape based on the data so you can have different colors, etc using CSS. Here is a fiddle.
currentsvg.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("d",function(d,i){
var path,
s = i*50,
r = 10,
w = r*2;
if (data[i] == "Q"){
path = "M" + s + " " + s + " L" + s + " " + (s+w) +
" L" + (s+w) + " " + (s+w) + " L" + (s+w) + " " + s + "Z"
}
else if (data[i] == "C"){
path = "M" + s + " " + s + " m" + -r + ", 0 " +
" a " + r + "," + r + " 0 1,0 " + r*2 + ",0" +
" a " + r + "," + r + " 0 1,0 "+ -r*2 + ",0"
}
return path;
})
.attr("class", function(d){return d == "Q" ? "rec" : "circ";})
The best way to do that is to filter the data how you want into separate data sets for each shape before you create shapes. Then you can create the shapes with that new data set.
var data = ["Q","Q","Q","C","C","Q","Q","C","Q","C"];
var circleSet = data.filter(function(d){return d === "Q";}),
squareSet = data.filter(function(d){return d === "C";});
As Lars said, that is also not how the d attribute works. Here is a working JSFiddle of the whole thing.

String search logic - not language specific

I'm having to check data entry on an address field. The client does not want users to use terms like Rd. or Rd for road, ave or ave. for avenue etc. I have no problem with most of the terms. Where I have issues is with 'Ave' lets say. If I look for ' AVE ', that's fine but it will not pick up on ' AVE' at the end of the string and if I look for ' AVE' it will get a false positive on ' Avenue' since it will find ' Ave' within that string. Anyone have an idea of how I can go about this?
Thank you for any help.
Norst
Although the Q: is not language specific, here is how I'm going about this in JS:
//function to check address for rd rd. ave ave. st st. etc
function checkaddy() {
//array of items to look for
var watchfor = Array();
watchfor[0] = " RD";
watchfor[1] = " RD.";
watchfor[2] = " AVE ";
watchfor[3] = " AVE.";
watchfor[4] = " ST ";
watchfor[5] = " ST.";
watchfor[6] = " BLVD.";
watchfor[7] = " CRT ";
watchfor[8] = " CRT.";
watchfor[9] = " CRES ";
watchfor[10] = " CRES.";
watchfor[11] = " E ";
watchfor[12] = " E.";
watchfor[13] = " W ";
watchfor[14] = " W.";
watchfor[15] = " N ";
watchfor[16] = " N.";
watchfor[17] = " S ";
watchfor[18] = " S.";
watchfor[19] = " PKWY ";
watchfor[20] = " PKWY.";
watchfor[21] = " DR ";
watchfor[22] = " DR.";
//get what the user has in the address box
var addcheck = $("#address").val();
//upper case the address to check
addcheck = addcheck.toUpperCase();
//check to see if any of these terms are in our address
watchfor.forEach(function(i) {
if (addcheck.search(watchfor[i]) > 0 ) {
alert("Found One!");
}
});
}
Perhaps you need to look for word boundary character \b. Here are some Ruby examples:
irb(main):002:0> " Avenue" =~ / AVE\b/i
=> nil
irb(main):003:0> " Ave" =~ / AVE\b/i
=> 0
irb(main):005:0> " Ave" =~ /\bAVE\b/i
=> 1
irb(main):006:0> " Ave" =~ /\bAVE\b/i
Notice how " Avenue" doesn't match while " AVE" does match. Also notice how the '\b' behaves and we get 0 and 1 respectively.
There are other characters classes as well in regular expressions. So all you need to do is formulate correct REs for your problem set.
I hope that helps.
Why would your client insist on spelling out names? The United States Postal Service actually encourages abbreviations. Not only that, they prefer addresses to be in all uppercase letters and no more than 5 lines. Such specifications are what their automated sorters were built for. But I digress.
To actually answer your question, you may consider the following code. There was a mistake in your forEach declaration. You were using i as an index, but, in fact, the forEach function uses the whole entry of the array. I modified it below. Also, because we're using a string expression in the constructor for the RegExp, the \ in the \b has to be escaped, so we add two \'s inside the string. Because we using the \b construct for word boundaries, we don't need to add extra periods into the test array. I hope you find this helpful.
//array of items to look for
var watchfor = ['RD','AVE','ST','BLVD','CRT','CRES','E','W','N','S','PKWY','DR'];
//function to check address for rd rd. ave ave. st st. etc
function checkaddy(address) {
//check to see if any of these terms are in our address
watchfor.forEach(function(entry) {
var patt1 = RegExp('.*\\b' + entry + '\\b.*','gim');
if (patt1.test(address)) {
document.write("Found " + entry);
}
});
}

Why am I getting incorrect values for string length?

My professor is teaching us Scala using Horstmann's book "Scala for the impatient", and one of our homework exercises are straight from the book; Chapter 4, exercise 2.
We are expected to read in the eBook in text format, the professor has specified that the input file should be "Moby Dick", available for free from the Guttenberg project here: http://www.gutenberg.org/ebooks/2701.txt.utf-8
My code works, as far as counting instances of words. However, he has added the requirement that we must we must format the output in two two columns, with words left justified, and counts right justified. To do so, I am determining the longest word in the book so I can figure the width of the "word" column. However, the values I am getting for the length of the strings is just wrong. In fact, it tells me that all the strings are the same length. "a" is being reported as length 26, just as is "Whale", "Ishmael", etc...
Here's the code:
object Chapter4Exercise2 extends App {
//for sorting
import util.Sorting._
//grab the file
val inputFile = new java.util.Scanner(new java.io.File("moby.txt"))
//create a mutable map where key/values == word/count
val wordMap = collection.mutable.Map[String, Int]() withDefault (_ => 0)
//for formatting output (later), the longest word length is relevant
var longestWord = 0
var theWord: String = ""
//start reading each word in the input file
while (inputFile hasNext) {
//grab the next word for processing, convert it to lower case, trim spaces and punctuation
var nextWord = inputFile.next().toLowerCase().trim().filter(Character.isLetter(_))
//if it's the longest word, update both theWord and longestWord
if (nextWord.size > longestWord) longestWord = nextWord.size; theWord = nextWord; println(theWord + " " + longestWord)
//update the map value for the key with same value as nextWord
wordMap(nextWord) += 1
}
println("Longest word is " + theWord + " at " + longestWord + " Characters")
}
The output of these lines:
if (nextWord.size > longestWord) longestWord = nextWord.size; theWord = nextWord; println(theWord + " " + longestWord)
and
println("Longest word is " + theWord + " at " + longestWord + " Characters")
is way off. It's telling me that EVERY word in the input file is 26 characters long!
Here's a small sample of what's being output:
husks 26
on 26
a 26
surfbeaten 26
beach 26
and 26
then 26
diving 26
down 26
into 26
What am I missing/doing wrong?
if (nextWord.size > longestWord) longestWord = nextWord.size; theWord = nextWord; println(theWord + " " + longestWord)
You shouldn't write multiple statements on a single line like that. Let's write this out in multiple lines and properly indent it:
if (nextWord.size > longestWord)
longestWord = nextWord.size
theWord = nextWord
println(theWord + " " + longestWord)
Do you see the problem now?
Try putting { and } around your if statement alternatives.
You can avoid this kind of pitfall by formatting your code in a structured manner - always using braces around code blocks.
if (nextWord.size > longestWord)
{
longestWord = nextWord.size;
theWord = nextWord;
println(theWord + " " + longestWord);
}
Your current code is equivalent to
if (nextWord.size > longestWord)
{
longestWord = nextWord.size;
}
theWord = nextWord;
println(theWord + " " + longestWord);

Resources