concatenation output problem (toString Array) - java - java

I am trying to display the output as "1(10) 2(23) 3(29)" but instead getting output as "1 2 3 (10)(23)(29)". I would be grateful if someone could have a look the code and possible help me. I don't want to use arraylist.
the code this
// int[] Groups = {10, 23, 29}; in the constructor
public String toString()
{
String tempStringB = "";
String tempStringA = " ";
String tempStringC = " ";
for (int x = 1; x<=3; x+=1)
{
tempStringB = tempStringB + x + " ";
}
for(int i = 0; i < Group.length;i++)
{
tempStringA = tempStringA + "(" + Groups[i] + ")";
}
tempStringC = tempStringB + tempStringA;
return tempStringC;
}

The problem is that you are appending all of the indices to one String and all of the elements to another, and then concatenating the two.
Instead, try building one String (and remember to use StringBuffer/StringBuilder, since it is more efficient than String concatenation):
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Groups.length; i++) {
sb.append(i+1).append('(').append(Groups[i]).append(')');
}
return sb.toString();
}

You should use :
// int[] Groups = {10, 23, 29}; in the constructor
public String toString()
{
String tempStringB = "";
for(int i = 0; i < Group.length;i++)
{
tempStringB = (i==0?"":" ")+ tempStringB + (i+1) + " "+ "(" + Groups[i] + ")";
}
return tempStringB;
}
But by the way using a StringBuffer would be clever especially if your Group become bigger

Related

How to split a String twice and automatically create a table (with n elements)?

(Absolute beginner here)
My Goal is a table in which the elements in a separated array in one row are seperated by a comma and a new row after a space (" ").
A new row HAS to start after the space (meaning I can't replace it with let's say a dot).
I think my biggest problem is that I can't get "pretty 105" (notice the space) separated. It always counts as one element.
Right now the String only has 8 elements but you've to imagine the String being VERY long.
At first I want to split the String (including "pretty 105")
In the loop, I tried to make it to 'jump' after "pretty" because it should be splitting here
public static void main(String[] args) {
String str = "104,Jeans,B&B,pretty 105,Shoes,Nike,nice";
List<String> Row = Arrays.asList(str.split(" "));
List<String> List = Arrays.asList(str.split(","));
StringBuilder buf = new StringBuilder();
buf.append("<html>" +
"<body>" +
"<table>" +
"<tr>" +
"<th>Number</th>" +
"<th>Name</th>" +
"<th>Maker</th>" +
"<th>Description</th>" +
"</tr>");
for (int j = 0; j < Row.size(); j++) {
int i = j*4;
for (; i < List.size(); i++) {
if (i<1+i) {
buf.append("<tr><td>")
.append(List.get(i))
.append("</td>");
}
else if (i>=1+i) {
buf.append("<td>")
.append(List.get(i))
.append("</td>");
}
else if (i>3+i) {
buf.append("<td>")
.append(List.get(i))
.append("</td></tr>");
break;
}
}
}
buf.append("</table>" +
"</body>" +
"</html>");
String html = buf.toString();
System.out.println(buf);}
In this example, the expected result is:
Number Name Maker Description
104,Jeans,B&B,pretty
105,Shoes,Nike,nice
But in the example above every one of them has its own line - except for "pretty 105":
104
Jeans
B&B
pretty 105
.
.
.
Is that what you want ?
public class Main {
public static void main(String[] args) {
String str = "104,Jeans,B&B,pretty 105,Shoes,Nike,nice";
final String join = String.join("\n", str.split(" "));
System.out.println(join);
}
}
EDIT:
public static void main(String[] args) {
String str = "104,Jeans,B&B,pretty 105,Shoes,Nike,nice";
final String[] lines = str.split(" ");
StringBuilder buf = new StringBuilder();
buf.append("<html>" + "<body>" + "<table>" + "<tr>" + "<th>Number</th>" + "<th>Name</th>" + "<th>Maker</th>" + "<th>Description</th>" + "</tr>");
for (String line : lines) {
buf.append("<tr><td>")
.append(line)
.append("</td><td>");
}
buf.append("</table>" + "</body>" + "</html>");
System.out.println(buf);
}

How can I align my text in the terminal? (Java)

My code accepts 3 arguments, first (args[0]) is the text file, second (args1) is the number of characters per line and the final argument (args[2]) is not yet implemented but is the option of the alignment (Left, Center or Justify).
Right now, I am trying to implement the left alignment and here is my code (the alignment code comes the last):
try {
System.out.println("usage: java AlignText" + args[0] + " " + args[1] + "
" + args[2]);
String[] text = FileUtil.readFile(args[0]);
int paragraphs = Integer.parseInt(args[1]);
StringBuilder builder = new StringBuilder();
for (String string : text) {
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(string);
}
String str = builder.toString();
StringBuilder sb = new StringBuilder();
int i = str.indexOf(" ",paragraphs);
while (i>0){
sb.append(str.substring(0, i).trim());
sb.append("\n");
str = str.substring(i);
if(str.length()>paragraphs){
i = str.indexOf(" ", paragraphs);
}
else {
i = -1;
}
}
sb.append(str.trim());
sb.toString();
//System.out.println(sb.length());
String[] lines = new String[100];
int count = 0;
int index = 0;
for(int j=0;j<sb.length();j++){
if(sb.charAt(j) == '\n') {
lines[index] = sb.substring(count,j).trim();
System.out.printf("%20s"+"\n", lines[index]);
//System.out.println("\n");
count = j;
index++;
}
}
And here is my output:

Why my getName() method is not starting from the first row in my csv file?

public int getRank(int auxYear, String auxName){
//FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
String resourceName = "/Users/User/Desktop/coursera/week4_babybirths/babybirths/testing/yob" + auxYear + "short.csv";
File auxFile = new File(resourceName);
if(auxFile.exists()){
FileResource auxFr = new FileResource(auxFile);
//FileResource auxFr = new FileResource();
int auxRank = 0;
for (CSVRecord auxRec : auxFr.getCSVParser(false)){
if (auxRec.get(1).contains(auxGender)){
auxRank += 1;
String auxN = auxRec.get(0);
if (auxRec.get(0).contains(auxName)){
return auxRank;
}
}
}
}
the getName method is reading another csv file and not staring from the first row, below the code :
public String getName(int auxYear, int auxRank, String auxGender){
////FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
String resourceName = "/Users/User/Desktop/coursera/week4_babybirths/babybirths/testing/yob" + auxYear + "short.csv";
File auxFile = new File(resourceName);
if (auxFile.exists()){
FileResource auxFr = new FileResource(auxFile);
int auxCount = 0;
for (CSVRecord auxRec : auxFr.getCSVParser()){
String auxStr = auxRec.get(0);
if (auxRec.get(1).contains(auxGender)){
auxCount += 1;
String auxStr1 = auxRec.get(0);
if (auxCount == (auxRank-1)){
return auxRec.get(0);
}
}
}
}
I use also :
public String yourNameInYear(String auxName, int auxYear, int auxNewYear, String auxGender){
int auxRank = getRank(auxYear, auxName, auxGender);
return getName(auxNewYear, auxRank, auxGender);
}
public void testYourNameInYear(){
String auxName = yourNameInYear("Isabella", 2012, 2014, "F");
System.out.println("Isabella" + " born in " + 2012 + " would be " + auxName + " in " + 2014);
}
by default YourNameInYear will call getRank this one will open the yob2012short.csv then after processing, getName will be called and open yob2014short.csv. I don't know why this one is not starting from the first row ?
try to use this
if (auxRec.get(1).contains(auxGender)){
String auxStr1 = auxRec.get(0);
if (auxCount == (auxRank-1)){
return auxRec.get(0);
}
auxCount += 1;
}
as I gess auxCaunt must be your current row so if you increment it from 0 to 1 then you do call the getName with an auxRank equals to 0 (first row may be 0 not 1) so 0 is not equal to 1 so it will loop until auxRank equals 2

running time error when trying to implent a keyword frequency counter in my parser java

I want to implement my input reading method into my main class, I want use my code to parse. It's been fixed now. thanks.
String x;
int count = -1;=
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
}
private List<String[]> termsDocsArray = new ArrayList<String[]>();
private List<String> allTerms = new ArrayList<String>(); //to hold all terms
private List<double[]> tfidfDocsVector = new ArrayList<double[]>();
/**
To start with your code
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
should be in it's own method like .
private void doSomething(){
//This variable will hold all terms of each document in an array.
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
Secondly in ur given code u have written like
int count = -1;=
which accounts to this error Syntax error on token "=", { expected.It should be
int count = -1;
And since all your code is simply written in class without any method so it is giving you the error saying { expected.
Please make sure you have copied the code correctly.

This is making my program freeze

every time this starts my program freezes, and I can't figure out why.
It doesn't give any errors, it just freezes.
Is it possible I've created some kind of endless loop?
public static String[] DataVoorList(int coureur) throws SQLException{
ArrayList datalijst = new ArrayList();
String query = ""
+ "SELECT rd_datum, rd_locatie, rd_code "
+ "FROM racedag WHERE rd_code in( "
+ "SELECT i_rd_code "
+ "FROM inschrijvingen "
+ "WHERE i_c_nummer = " + coureur + ");";
ResultSet rs = Database.executeSelectQuery(query);
int i=0;
while (rs.next()){
String datum = rs.getString("rd_datum");
String locatie = rs.getString("rd_locatie");
String totaal = "" + datum + " - " + locatie;
datalijst.add(i, totaal);
i++;
int codeInt = rs.getInt("rd_code");
String code = ""+codeInt;
datalijst.add(i, code);
i++;
}
return Race.StringDataVoorList(datalijst);
}
public static String[] StringDataVoorList(ArrayList invoer){
int lengte = invoer.size();
String[] uitvoer = new String[lengte];
int i =0;
while (i < uitvoer.length){
uitvoer[i] = ""+invoer.get(i);
}
return uitvoer;
}
EDIT: I've solved the increment. However, it still freezes.
EDIT 2: I think I have located the problem (but I can be wrong)
public static String[] DataVoorList(int coureur) throws SQLException {
System.out.println("stap 1");
ArrayList datalijst = new ArrayList();
String query = ""
+ "SELECT rd_datum, rd_locatie, rd_code "
+ "FROM racedag WHERE rd_code in( "
+ "SELECT i_rd_code "
+ "FROM Inschrijvingen "
+ "WHERE i_c_nummer = " + coureur + ");";
ResultSet rs = Database.executeSelectQuery(query);
System.out.println("stap 2");
int i = 0;
while (rs.next()) {
String datum = rs.getString("rd_datum");
String locatie = rs.getString("rd_locatie");
String totaal = "" + datum + " - " + locatie;
datalijst.add(i, totaal);
System.out.println("stap 3");
i++;
int codeInt = rs.getInt("rd_code");
String code = "" + codeInt;
datalijst.add(i, code);
i++;
System.out.println("stap 4");
}
return Race.StringDataVoorList(datalijst);
(I've changed the while loop to a for loop)
public static String[] StringDataVoorList(ArrayList invoer) {
int lengte = invoer.size();
String[] uitvoer = new String[lengte];
for (int i = 0; i < uitvoer.length; i++) {
uitvoer[i] = "" + invoer.get(i);
}
return uitvoer;
}
}
this is being called from here:
public MijnRacedagenScherm() throws SQLException{
initComponents();
int gebruiker = Inloggen.getNummer();
String[] DataVoorList = Race.DataVoorList(2);
int lengte = DataVoorList.length;
System.out.println("resultaat is " + DataVoorList[0]);
int i = 0;
while (i < lengte) {
ListRacedagenCoureur.setListData(DataVoorList);
i = i + 2;
}
System.out.println("lengte is " + lengte);
}
This is a new screen, but in the previous screen I get a unreported SQL exception over this:
private void ButtonZienRacedagActionPerformed(java.awt.event.ActionEvent evt) {
new MijnRacedagenScherm().setVisible(true);
}
Well, um... In this section:
while (i < uitvoer.length){
uitvoer[i] = ""+invoer.get(i);
}
Where is i incremented?
Indeed it is, this
int i =0;
while (i < uitvoer.length){
uitvoer[i] = ""+invoer.get(i);
}
You never increment i.
As stated problem is in your while loop.
for loop is more suitable for iterating over indexed data type
for (int i = 0; i < uitvoer.length; i++) {
uitvoer[i] = ""+invoer.get(i);
}
How many rows are you processing? The way you append strings is quite slow, maybe it's not freezing anymore but just taking a long time to complete.

Categories