GWT Java - Server Side "for loop" not working - java

I am reading in a file in which each row has a column no, row number, detail. The file is sorted on column then row. I want to place the detail in a csv file in the correct row and column. So I am testing for change in row number and then add in line breaks ("\n").
The issue is that the System.out.println on each side of the for loop is being displayed in the log; however, the loop its self is not triggered (i.e., the line break is not added and the System.out.println is not appearing in the log.
The code is:
System.out.println("New row - " + Integer.parseInt(report.getReportDetailRow())+ " greater than current row - " + currentRow);
currentCol = 0;
//Add line breaks
int j = Integer.parseInt(report.getReportDetailRow());
for(int i = currentRow; i > j; i++){
System.out.println("Append line break");
fileContent.append("\n");
}
System.out.println("After append");
currentRow = Integer.parseInt(report.getReportDetailRow());
if (currentCol == Integer.parseInt(report.getReportDetailColumn())){
fileContent.append(report.getReportDetailDetails() + ",");
currentCol++;
}else{
//Add columns
for(int i = currentCol; i == Integer.parseInt(report.getReportDetailColumn()); i++){
fileContent.append(",");
}
fileContent.append(report.getReportDetailDetails() + ",");
currentCol = Integer.parseInt(report.getReportDetailColumn());
}
Please note that I have use "i > j" instead of "i == j" to try to force a result.

In your statement for iterating through the rows, you have
for(int i = currentRow; i > j; i++)
If j is the number of current rows, then you need to change your condition to i < j to go through them all.

for(int i = currentRow; i > j; i++) {
System.out.println("Append line break");
fileContent.append("\n");
}
The loop above would either result in an infinite loop or never get triggered(your case)
Infinite if i is already greater than j. It would never terminate with i++ for every iteration
Never execute if i is less than j, since the condition states i>j.
You might want to change the conditional statement inside the loop to correct this to either i==j or i<j
for(int i = currentRow; i == j; i++) // in which case replacing this with an `if(i==j)` would do the needful
or
for(int i = currentRow; i < j; i++) // to iterare from initial i upto j

Related

Skipping first line on a loop

I want to add data to a dataset to display some values on a graph. On some files, the first line is a description of the columns (like "Timestamp" or something else). I need my code to test if the first line contains integer or float values and if not to skip this line and add data to dataset from 2nd line.
This is my code:
for (int i = 0; i < listOfLists.size(); i++) {
for (int j = 1; j < listOfLists.get(i).size(); j++) {
if (listOfLists.get(i).get(0).matches("\\d+(?:\\,\\d+)?") || listOfLists.get(i).get(0).matches("\\d+(?:\\.\\d+)?")) {
datasetBar.addValue(Float.parseFloat(listOfLists.get(i).get(j).replace(",",".")),columnsLabel[i].getText(), ""+listOfLists.get(0).get(j));
} else if(listOfLists.get(i).get(1).matches("\\d+(?:\\,\\d+)?") || listOfLists.get(i).get(1).matches("\\d+(?:\\.\\d+)?")){
datasetBar.addValue(Float.parseFloat(listOfLists.get(i).get(j).replace(",",".")),columnsLabel[i].getText(), ""+listOfLists.get(0).get(j));
The problem is that I get an error when he's trying to represent String on the plot of the bar chart
List of lists is a list of columns. Each column of the file is added into a list and each list into the listOfLists.
I tried to use on the else if block: listOfLists.get(i).remove(0) but it didn't worked. (in next loops it keeped removing the first line of the remaining list.
Thanks in advance!
You can check in the outer loop, before inner loop:
if (i == 0 && listOfLists.get(i).get(0).matches(/\\d+(?:[\\.,]\\d+)?)/) == false) {
continue; // skip first line
}
BTW: You should not call remove method while iterating list because you will get ConcurrentModificationException.
It could be something like this:
for (int i = 0; i < listOfLists.size(); i++) {
for (int j = 0; j < listOfLists.get(i).size(); j++) {
if (j==0){ // Only test if it is a string in position [0]
boolean isNumber = listOfLists.get(i).get(0).matches("\\d+(?:\\,\\d+)?") || listOfLists.get(i).get(0).matches("\\d+(?:\\.\\d+)?");
if (!isNumber) continue; // If it is not a number, skip it
}
// Add to database, because it is a number
datasetBar.addValue(Float.parseFloat(listOfLists.get(i).get(j).replace(",",".")),columnsLabel[i].getText(), ""+listOfLists.get(0).get(j));
Hope it will help anyone to understand.
for(int i = 0; i < n; i++){ /* i = 0 means position of i is 0 which is 1st line */
if(i != 0 ){ /* and as our purpose is skipping first line so I will only continue when i is not equal 0 like this we can skip first line in this if block */
continue;
}
}

Algorithm output to length starts new line

I am trying to format the output from what I have written to display a list of primes (Eratosthenes) to a certain number results per line. Do they need to placed into an Array to accomplish this? I have not come across a way to implement their division besides .split("");, which would render a single line for each and the Oracle site's System.out.format(); argument index to specify length. Yet, these require the characters to be known. I am printing it with the following, which of course creates an infinite line.
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
System.out.print(count + ", ");
}
}
Is there a way to simply call System.out.print("\n"); with an if(...>[10] condition when System.out.print() has run for instance 10 times? Perhaps I am overlooking something, relatively new to Java. Thanks in advance for any advice or input.
By using a tracker variable, you can keep track of how many items have been displayed already so you know when to insert a new line. In this case, I chose 10 items. The exact limit is flexible to your needs.
...
int num = 0;
//loop
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
if (num == 10) { System.out.print("\n"); num = 0; }//alternatively, System.out.println();
System.out.print(count + ",");
num++;
}
}
...
You can just simply create some int value e.g.
int i = 1;
...and increment it's value everytime Sysout is running.
Something like this:
int i = 1;
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
if (i%10 == 0)
System.out.print(count+ "\n");
else
System.out.print(count + ", ");
i++;
}
}
Try this:
int idx=1;
int itemsOnEachLine=10;
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
System.out.print(count+(idx%itemsOnEachLine==0?"\n":","));
idx++;
}
}
you go increasing a counter (idx) along with every write, every 10 increments (idx modulus 10 == 0), you will be printing a new line character, else, a "," character.

Why do I get unreachable statement error in Java?

I'm putting together a code for a hailstone sequence I found in an online tutorial, but in doing so I ran into an unreachable statement error. I don't know if my code is correct and I don't want advice in correcting it if I'm wrong(regarding the hailstone sequence, I want to do that myself..:) ). I just want help in resolving the "unreachable statement" error at line 19.
class HailstoneSequence {
public static void main(String[] args) {
int[][] a = new int[10][];
a[0][0] = 125;
int number = 125;
for (int i = 0;; i++) {
for (int j = 1; j < 10; j++) {
if (number % 2 == 0) {
a[i][j] = number / 2;
number = number / 2;
} else {
a[i][j] = (number * 3) + 1;
number = (number * 3) + 1;
}
}
}
for (int i = 0;; i++) {
for (int j = 0; j < 10; j++) {
System.out.println(a[i][j]);
}
}
}
}
This is an infinite loop:
for(int i=0;;i++){
Whatever comes after it never get executed (i.e. is unreachable).
In your first for loop:
for(int i=0;;i++){
....
}
You do not define the ending condition. e.g.
for(int i=0; i<10; i++){
....
}
Therefore the loop never exits.
Your first infinite loop of for(int i=0;;i++) stops any other code from being reached.
There is an infinite loop # line 7
You forgot to set an exit condition
for(int i=0;here;i++){
This might create unexpected behaviour.
Your first for statement (in the 6'th line) is an infinite loop therefore it stops further code to be reached.
for(int i=0;;i++)
You have problem at line number 6 in your first for loop.
for(int i=0;;i++) {
Here since your don't have any exit conditions, code is going in the infinite loop and the loop never exits. Whatever outside the scope of this for loop will be unreachable since your first loop is never existing.
Consider adding the exit condition (such as break or return etc.) inside your for loop to prevent this behavior.

Doesn't enter in the "for-loop"?

Here is my code :
private String SerialNo;
private String FirmVersion;
public String GetSerial(int[] Data){
System.out.println("GetSerial Debug : Data => "+Data);
for (int i = 2;i==13;i++){
System.out.println("In the FOR => ok ");
if (i != 9){
SerialNo = SerialNo + Data[i];
}
if (i == 9){
SerialNo = SerialNo + ".";
}
}
System.out.println("SerialNo => "+ SerialNo);
return SerialNo;
}
My problem : I can't "enter" in the FOR
So my sysout of "In the FOR => ok", never shows and all the "actions" aren't done.
What am I doing wrong ?
ps : I'm sure that I'm compiling the right file.
The loop condition is never satisfied; i = 2 in the begin, the first check would fail, so all the loop would fail. Maybe it should be changed for:
for (int i = 2; i <= 13; ++i)
Examine your for statement:
for (int i = 2; i==13; i++)
This actually means the following:
assign 2 to i
Check whether i equal to 13. If yes, continue loop, exit otherwise.
Since i is not 13 in the first iteration of loop you never enter it. I believe that you wanted to write
for (int i = 2; i <= 13; i++)
In this case you will iterate from 2 to 13 inclusively. The condition of for loop means "do I have to remain iterating?" and not "do I have to escape?"
Change for (int i = 2; i == 13; i++) to for (int i = 2; i <= 13; i++).
The second argument is the loop condition which has to be true to run the loop.
Your condition became false at first iteration so control never goes to loop body.
for loop syntax:
for(initialization; condition; increment/ decrement){
//your code
}
So here you will have to use some appropriate condition to enter into the loop.
So for example :
for (int i = 0; i <= 13; i++) // for 0 to 13 increment
or
for (int i = 10; i >= 0; i--) // for 10 to 0 decrement
for (int i = 2;i==13;i++){}
It enters but failed at first condition check and for-loop exits.
It should be -
for (int i = 2;i<=13;i++)
You have initialized i=2
for (int i = 2;i==13;i++)
And condition is i==13 which will become false ultimately flow never enter into for loop
try to change the code like this
for (int i = 2;i<=13;i++)
Statement is not good should be like the one below:
for (int i = 2; i<13; i++) or for (int i = 2; i<=13; i++)
See compared simple while loop in the case of your for loop.
Think about int i =2; value set and i == 13 condition
Do you think it will work?
for (int i = 2;i==13;i++){
//do something
}
Same to below *while loop* explanation
int i = 2;
while (i == 13) {
//do something
i++;
}
I am sure it will work
for (int i = 2;i < 13;i++){
//do something
}
Same to below **while loop**
int i = 2;
while (i < 13) {
//do something
i++;
}
The flow of the for loop is: init statement-> condition check-> goes inside loop or outside depending on the condition outcome.
Here, since you've said i=2 ,then i==13 is false; it'll never go inside the loop.
You could use the ?: operator in the for loop and then modify your if statements a bit I guess..

how to print a number triangle in java

I need to produce a triangle as shown:
1
22
333
4444
55555
and my code is:
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)  
{          
System.out.print(i); 
}      
System.out.print("\n");        
}
Producing a triangle the opposite way
1
22
333
4444
55555
What do i need to do to my code to make it face the right way?
You need 3 for loops:
Upper-level loop for the actual number to be repeated and printed
first inner level for printing the spaces
second inner level for to print the number repeatedly
at the end of the Upper-level loop print new line
Code:
public void printReversedTriangle(int num)
{
for(int i=0; i<=num; i++)
{
for(int j=num-i; j>0; j--)
{
System.out.print(" ");
}
for(int z=0; z<i; z++)
{
System.out.print(i);
}
System.out.println();
}
}
Output:
1
22
333
4444
55555
666666
I came across this problem in my AP CS class. I think you may be starting to learn how to program so heres what I'd do without giving you the answer.
Use a loop which removes the number of spaces each iteration. The first time through you would want to print four spaces then print 1 one time(probably done in a separate loop).
Next time through one less space, but print i one more time.
You need to print some spaces. There is a relation between the number of spaces you need and the number (i) you're printing. You can print X number of spaces using :
for (int k = 0; k < numSpaces; k++)
{
System.out.print(" ");
}
So in your code:
int i, j;
for(i = 1; i <= 5; i++)
{
// Determine number of spaces needed
// print spaces
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
use this code ,
int i, j,z;
boolean repeat = false;
for (i = 1; i <= 5; i++) {
repeat = true;
for (j = 1; j <= i; j++) {
if(repeat){
z = i;
repeat = false;
while(z<5){
System.out.print(" ");
z++;
}
}
System.out.print(i);
}
{
System.out.print("\n");
}
}
You can use this:
int i, j;
int size = 5;
for (i = 1; i <= size; i++) {
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
for (j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.print("\n");
}
This line:
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
Is going to print the left spaces.
It uses the old printf with a fixed sized string like 5 characters: %5s
Try it here: http://ideone.com/jAQk67
i'm having trouble sometimes as well when it's about formatting on console...
...i usually extract that problem into a separate method...
all about how to create the numbers and spacing has been posted already, so this might be overkill ^^
/**
* creates a String of the inputted number with leading spaces
* #param number the number to be formatted
* #param length the length of the returned string
* #return a String of the number with the size length
*/
static String formatNumber(int number, int length){
String numberFormatted = ""+number; //start with the number
do{
numberFormatted = " "+numberFormatted; //add spaces in front of
}while(numberFormatted.length()<length); //until it reaches desired length
return formattedNumber;
}
that example can be easily modified to be used even for Strings or whatever ^^
Use three loops and it will produce your required output:
for (int i=1;i<6 ;i++ )
{
for(int j=5;j>i;j--)
{
System.out.print(" ");
}
for(int k=0;k<i;k++)
{
System.out.print(i);
}
System.out.print("\n");
}
Your code does not produce the opposite, because the opposite would mean that you have spaces but on the right side. The right side of your output is simply empty, making you think you have the opposite. You need to include spaces in order to form the shape you want.
Try this:
public class Test{
public static void main (String [] args){
for(int line = 1; line <= 5; line++){
//i decreases with every loop since number of spaces
//is decreasing
for(int i =-1*line +5; i>=1; i--){
System.out.print(" ");
}
//j increases with every loop since number of numbers
//is decreasing
for(int j = 1; j <= line; j++){
System.out.print(line);
}
//End of loop, start a new line
System.out.println();
}
}
}
You approached the problem correctly, by starting with the number of lines. Next you have to make a relation between the number of lines (the first for loop) and the for loops inside. When you want to do that remember this formula:
Rate of change*line + X = number of elements on line
You calculate rate of change by seeing how the number of elements change after each line. For example on the first line you have 4 spaces, on the second line you have 3 spaces. You do 3 - 4 = -1, in other words with each line you move to, the number of spaces is decreasing by 1. Now pick a line, let's say second line. By using the formula you will have
-1(rate of change) * 2(line) + X = 3(how many spaces you have on the line you picked).
You get X = 5, and there you go you have your formula which you can use in your code as you can see on line 4 in the for loop.
for(int i = -1 * line +5; i >= 1; i--)
You do the same for the amount of numbers on each line, but since rate of change is 1 i.e with every line the amount of numbers is increasing by 1, X will be 0 since the number of elements is equal to the line number.
for(int j = 1; j <= line; j++){

Categories

Resources