somjit{} 60 Junior Poster in Training Featured Poster

@ G_S:

This is used for referring to this class' variable whose name is similar to the method's parameter?

a methods parameter, also called a local/static variable can be same or different to a class' variable, also called a instance variable. WHY? because they have different scopes... atleast in the above example it does. also, u should know, that a local variable lives in the stack , and an instance variable lives in the heap. so that further adds to why having the same name really doesnt matter too much.

Children inherit their parent's methods and attributes BUT using the paren't setter doesn't set the children's variables? If so, then using the childrens setter will only set the age and, id and name of ONE child and not the parent's or the other child's?

you can always download eclipse or netbeans, install it, and put this code there, and check ur ideas. thats one of the benefits of coding... that way, u can see 1st hand what effects these tweaks result in. whatever doubts you have then, you can always post here. :)

also, i agree that since we dont know what your teacher did, it would be a bad idea to compare with it. maybe you can post the code here. :)

somjit{} 60 Junior Poster in Training Featured Poster

thanks a lot :) those were very clear and helpful answers :)

somjit{} 60 Junior Poster in Training Featured Poster

inheritance is really handy in eliminating duplicate code, and making the overall code more compact, since doctor and patient have things in common, its handy to put the common stuff in a superclass.

as regards

Can't we use only the children, since they will also have the setter method created in the parent along with the parents three attributes?

class people {

    private String name;
    private int age,id;

    public void setName(String name){
        this.name = name;
    }

    public void setAge(int age){
        this.age = age;
    }
    public void setId(int id){
        this.id = id;
    }

    public void display(){
        System.out.println("name: " + name + " age: " + age + " id: " + id);
    }

}

class patient extends people{

    String disease;

    public void setDisease(String d){
        this.disease = d;
    }
    public String getDisease(){
        return disease;
    }
}

class doctor extends people{

    int salary;

    public void setSalary(int s){
        this.salary = s;
    }
    public int getsalary(){
        return salary;
    }
}


public class peopleTester {

    public static void main(String[] args){
        doctor d = new doctor();
        patient p = new patient();

        d.setName("kurt");
        d.setAge(40);
        d.setSalary(3000);
        d.setId(10);

        p.setName("jhonny");
        p.setId(4505);
        p.setAge(23);
        p.setDisease("fever");

        d.display();
        p.display();
    }

}

here, i did just use the children, and all the inheritance worked quite alright :)

the teacher used the set method OF THE PARENT CLASS to take care of the 3 common variables and then used the children's methods to set the remaining variables that were still not set.

when you use the setters of the superclass (ie, …

somjit{} 60 Junior Poster in Training Featured Poster

in an assingment, i have to implement a deque ( double ended queue ). the underlying datastructure is allowed to be arrays or linkedlist. only that im not allowed to use any prebuilt java api that does the above. (like the java.util.LinkedList api)

implementing the above using doubly linked list seems straighforward , but i was also looking for how it can be done using arrays. I did a rough sketch on my own, but was facing a bit of hurdle in the resizing methods.
on google-ing for some solution, i came across here where they were saying :

If you "float" both ends of the array, you can have constant-time inserts and deletes, except for when you need to resize the array when it fills up.

i remember that i did learn about "float"-ing an array.. but i cant recollect it, neither did i find anything substantial when i searched for it on the web.
I want to use arrays because i liked the concept of amortized running time , so wanted to try my hand at it...

any help regarding what "float" ing both ends of an array means? also any guide into an efficient way to solve the assingment will be really helpful :)

regards
somjit.

somjit{} 60 Junior Poster in Training Featured Poster

forgive my ignorance, there must be a really simple answer to this, but im unaware of it, also, tried google-ing for it, but didnt know what to look for exactly, and didnt get much good answers either.

my question is, since 2^32 is around 4Gb, so max usable RAM on 32bit pc is 4GB.

then in what way HDDs with hundreds of GBs are happily supported by the same os...

regards
somjit.

edit: i guess i found my answer here

somjit{} 60 Junior Poster in Training Featured Poster

Remember those methods aren't there just so they can be called in your main method

i found that out the hard way.. the assignment , after being checked, i was given the report that all the stats measures was 0. then i learned, that the main method wasnt even run by the checking software... it required all the heavy lifting to be done by the constructor itself... they wouldnt even touch the main. i had to modify it quite a bit based on these factors.

I notice that your API methods won't work correctly if confidenceHi or confidenceLo is called before mean and stddev.

thats true... i have to put in a call to mean() and stddev() inside the confidenceHi() n confidenceLow() methods for it to be independent of the order. so far, it seems that its being called only after mean() n stddev() , so i didnt want it to spend time calculating what it already did..

thanks for keeping up with me :)

somjit{} 60 Junior Poster in Training Featured Poster

the problem is solved, i was doing two things wrong:

  1. initialized the fraction array with the wrong value. it needs to be initialized with numOfRuns, i was doing it with arraySize

  2. classRunCount needs to be initialized with -1 instead of 0. in this way, in each new Percolation class construction, classRunCount++ will increment it, starting from 0 to N-1. previously, it was starting from 1, and giving an outOfBounds error on the last run.( this happens after fixing the fraction[] initialization with proper set up values.)

somjit{} 60 Junior Poster in Training Featured Poster

You need to rethink your design and implement the API as given, not some alternate version of the API.

yes, i had a feeling parameterized versions wont count, and rightly so.

i made a few modifications

  1. created a static fraction[] array inside the class, it keeps all the individual (count/arrSize) data in it, to be used by the mean() and stddev() methods.
    (lines 173 onwards in the code below.)

  2. created a static classRunCount variable, that keeps track of how many times the class has been called/instantiated. this helps in the way, that when last call is made, that classRunCount is used in the mean and stddev methods.

thus calculations are now done inside the class itself, so no need to call perC outside the for() loops as before.
however, the results arent correct, ie
before, in the 1st code, the mean was coming at around .59 , but here, its coming at around .0058
thats another new problem now...

public class PercolationStats{

    private int arrDim;
    private int arrSize;
    private char[][] state;
    private WeightedQuickUnionUF qu;
    private int top = 0;
    private int bottom;
    private double count;
    private static double[] fraction;

    private static int classRunCount = 0; // keeps track of the num of runs from within the class


    public PercolationStats(int N){
        classRunCount++;
        arrDim = N;
        arrSize = N*N;
        qu = new WeightedQuickUnionUF((N*N)+2); // +2 is for the virtual top n bottom site
        state = new char[N][N];

        for(int i = 0; i< N; i++){ …
somjit{} 60 Junior Poster in Training Featured Poster

On the other hand, if you just want the perC of the last run only, then just initialize perC to null where you declare it and then check for perC == null before using it after the loop. If perC == null that will mean numOfRuns is zero or less and you can handle that case specially.

this can give a solution, but if you look at my code again, the value is calculated in main() , but your answer points to getting the value from the class itself. if i can return the same value to main, instead of calculating it there, the way ur suggesting to solve the problem can be done. thanks for the idea :)

somjit{} 60 Junior Poster in Training Featured Poster

It looks like you haven't decided which perC you want,

mean = (sum of elements)/num_of_elements
which is the 1st thing i want to calculate, and it requires the count/arraySize value of each iteration( or run ).

thus mean becomes : (sum of count/arraySize of each run)/numOfRuns
so want every new perC, in a loop.

somjit{} 60 Junior Poster in Training Featured Poster

this is a homework assignment. iv made the code do what its supposed to do, and it works perfectly.
The only problem im facing now is to model the code structure according to the given API. when i try > to do so, i go into null pointer exceptions.

the posted code works perfectly. as i said, i face problems only when modelling it according to the given API, which makes it mandatory to have separate methods to calculate the mean, standard deviation, and the 95% confidence levels.

the problem is that to calculate standard deviation, (as well as the other three statistical measures) i need to have access to the fraction[] array which stores the (perC.count/arraySize) values for each iteration.
However, as the reference perC is initialized inside the for() loop of main(), it brings in issues related to scope, and (i assume) null pointer exceptions(it hasnt been mentioned in the error report). This is because calculating the stats measures through the API methods means calling perC.<method_name> from outside the for loop, but perC itself is initialized inside the for loop.
so this would give errors, as it does:

The local variable perC may not have been initialized

^ the error showing up.

somjit{} 60 Junior Poster in Training Featured Poster

code for : Percolation using Weighted Quick Union Find Algorithm.

this is a homework assignment. iv made the code do what its supposed to do, and it works perfectly.
The only problem im facing now is to model the code structure according to the given API. when i try to do so, i go into null pointer exceptions. i have somewhat understanding of why that happens, but still, cant figure out a solution.

so here is about the assignment:

Percolation: calculate how many sites are needed for a connection between top row n bottom row to take place

algorithm:

  1. open an NxN array, such that initially all 'sites' ie, elements of the array are blocked, ie their state is 'b' connect all top row elements to a 'virtual' TOP site, and all bottom row elements to a virtual 'bottom' site. sites connected to the TOP site directly(as with first row elememts) or indirectly are called 'full'

  2. iterate, opening one site in each process, assign the state of this site 'o' (for open)
    once opened, check the neighbors (up,down,left,right) for other open or 'full' members
    connect open/full neighbors,
    if connected to a 'full' site, change state of the newly opened site to 'f' (full)
    else state remains as 'o'

  3. check if TOP n BOTTOM are connected,
    if yes > system percolates, display num of open sites
    else go back to loop

following this algorithm, we have to make a code that that performs …

somjit{} 60 Junior Poster in Training Featured Poster

refreshed, n saw that u made the edit... it was fun figuring out not seeing the edit though :)
thanks a lot for ur help.. doing some final checks on the code.. should be ok now :)

somjit{} 60 Junior Poster in Training Featured Poster

The debug statemengt I'm looking at shows tcid and cwid but it does NOT show the actual array cont

yes! i realize what i was doing wrong! thank you!

    public void union(int toChange, int changeWith){
        System.out.print("in union: array before for() : ");
        for(int i : id)
        System.out.print(i + " ");

        for(int i = 0; i < id.length ; i++){
            if( id[i] == id[toChange] ){
                id[toChange] = id[changeWith];
            }           
        }
        System.out.print("  array after for() : ");
        for(int i : id)
        System.out.print(i + " ");
    }

this is working :)

somjit{} 60 Junior Poster in Training Featured Poster

but the debug statement does show a change... only in that iteration, it vanishes in the next iteration.. :(

somjit{} 60 Junior Poster in Training Featured Poster
public QuickFindUF(int n){
        System.out.print("\nin constructor... ");
        id = new int[n];
        for(int i = 0; i<n ; i++){
            id[i] = i;
        }
        for(int i : id)
        System.out.print(i + " ");
    }

i added the debug print statement to the constructor, and its geting run only once, so its not a formal re initialization, i called it so for want of any better way to explain the problem in the short space allowed in the title...

somjit{} 60 Junior Poster in Training Featured Poster
public void union(int toChange, int changeWith){
        System.out.print("in union: ");
        tcid = id[toChange];
        cwid = id[changeWith];
        System.out.format("id[%d] = %d , id[%d] = %d ",toChange,tcid,changeWith,cwid);

        for(int i = 0; i < id.length ; i++){
            if( id[i] == tcid ){
                tcid = cwid;
            }           
        }
        System.out.format("id[%d] = %d , id[%d] = %d ",toChange,tcid,changeWith,cwid);
    }

in this method, the initial and the final debug statements register a change in the value stored at the locations passed (toChange and changeWith), but the next time they are called, the changes from the previous iteration are gone... so that's what led me to think that the array is getting re initialized in some sort of way...

somjit{} 60 Junior Poster in Training Featured Poster

im learning some algorithms , and trying to come up with a version for Quick find using union find.

the algorithm works like :
1. get user input for size of the array (the array holds the data on which quickfind will work)
2. create and initialize the array based on the input size.
3. get user user input of two numbers, these are the indices of the array, and check if the values at these positions are same, then they are declared connected.
4. if not connected, ie, values at the positions aren't the same, connect/union them.. ie make them have same values.

n so on...

the problem im facing is that the array keeps re-initializing, so changes made in one iteration dont show up in the next, so connected() method doesnt work.. n im in a mess.

any help would be great :)

this is the code i came up with:

public class UF {

    public static void main(String [] args){

        inputHelper reader = new inputHelper();

        int size=0,toChange=0,changeWith=0,connected=0;
        size = reader.getMyIntger("enter size of array ");

        QuickFindUF tester = new QuickFindUF(size);


        while(connected != size){

            System.out.println("enter value pair to check: ");
            toChange = reader.getMyIntger(" "); 
            changeWith = reader.getMyIntger(" ");

            if( !tester.connected(toChange, changeWith) ){

                tester.union(toChange, changeWith);
                connected++;
                System.out.println("connection : " + toChange + " and " + changeWith + " total connections : " + connected);

            }               
            else{
                System.out.println("already connected");
            }

        }
        System.out.println("all connected, exiting program..");


    }

}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class …
somjit{} 60 Junior Poster in Training Featured Poster

@adak:

this might interest you

i just learned about this site today when i was talking to a friend of mine about the euler project site you mentioned.

one learns more when one shares :)

somjit{} 60 Junior Poster in Training Featured Poster

prime, greek, euler... u just reminded me of the phi function of the RSA algorithm :D im a big cryptography fan, especially coz of all the neat maths associated with it...

somjit{} 60 Junior Poster in Training Featured Poster

Sieve of Eratosthenes

thats one mighty cool sounding algorithm.... obviously im going to try that out first! :D

There are WAY too many algorithms to remember

had a feeling that would be the case, hence didnt want to google...
thanks a lot for the list! hoping to learn them soon.

bdw, any links that might be helpful in understanding time complexity of codes written? i would like to learn that a lot.

somjit{} 60 Junior Poster in Training Featured Poster

@adak

I'm not sure whether you wanted a more optimal program, or a simpler - clearer - program

i wanted a more optimal code for the code i posted, n the algorithm u gave was just that.. a more optimal n "professional" (if thats the correct word) of doing it.

regards the strstr() function... its quite handy.. definately suits the clearer/simpler category.

I don't know if I could have coded this up during an exam

i find it quite difficult to write actual code in pencil n paper even at home... let alone during exams. perhaps im not alone then. :)

edit: can you give a list of a few common algorithms ? i never had that subject (im not a CS guy), so googling on my own might just be a little overwhelming.

somjit{} 60 Junior Poster in Training Featured Poster

thanks a lot for the link ! i never had algorithms as a subject, so the thought that there might be an algorithm for this problem didnt occur to me.. thanks for the advice. :)

somjit{} 60 Junior Poster in Training Featured Poster

@deceptikon :
i just noticed that u were decrementing size on each recursion... i only kept that to check initially if the passed array was valid or not, but the decremented size makes it a checking condition for whether the recursion has reached the base case as well! (atleast thats what i think it does.. :| ) i wish i had thought of that. :(

i had some exams on networking at college, so couldnt concentrate on programming as much i would want to, probably the reason it took me a week to notice that nice trick...
but thanks a lot for your detailed answers, i always learn a lot from them :)

regards.

somjit{} 60 Junior Poster in Training Featured Poster

this is an exam question i failed to answer properly, im trying to work it out. the code i came up with is below, it works ok, but i was hoping if anyone could help in improving it. iv read in various threads in daniweb itself about making a code run faster etc.. havent really understood much, maybe anyone can help me understand them here, with this code if possible. thanks a lot in advance :)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void remLin(char *);

int main(){

    int index,checker,count=0,ls1,ls2;
    char *s1,*s2;

    printf("enter max length of s1:");
    scanf("%d",&ls1);
    printf("enter max length of s2:");
    scanf("%d",&ls2);

    while((getchar())!='\n'){}

    printf("\nenter s1: ");
    fgets( (s1=(char*)malloc(sizeof(char)*ls1)) , ls1 , stdin);
    remLin(s1);

    printf("\nenter s2: ");
    fgets( (s2=(char*)malloc(sizeof(char)*ls2)) , ls2 , stdin);
    remLin(s2);

    for(index=0,checker=0;s1[index]!='\0';index++){

        printf("\n\n at for() start>> location: %3d  s1 contains: %3c  count value: %3d",index,s1[index],count);

        while((s1[index]==s2[checker]) && ((s1[index])!='\0') && ((s2[checker])!='\0')){
            checker++;
            index++;        
        }

        if(checker>0)
            index=index-1; // this compensates for one extra index increment at the end of while()

        if(checker==(strlen(s2))){
            count++;        

        }
        checker=0;

        printf("\n at for()   end>> location: %3d  s1 contains: %3c  count value: %3d",index,s1[index],count);
    }

    printf("\n\ncount of %s in %s is: %d\n\n",s2,s1,count);


    return 0;
}

void remLin(char *str){
    int len=strlen(str);
    if(str[len-1]=='\n')
        str[len-1]='\0';
    realloc(str,len); // trims up the string
    printf("\nentered string: %s and its length: %d\n\n",str,strlen(str)); // strlen will not count the null terminator
}

somjit.
ps: pardon a few obvious comment lines, i just kept them there so that i can understand what i did later on. :)

somjit{} 60 Junior Poster in Training Featured Poster

@deceptikon : thank you :) i see where i made the mistake. you providing the solution with two different methods was really helpful :)
only small thingy left here is that in the 2nd method, the one you suggested, the loop is doing one extra iteration at the end.
im hoping i can fix it on my own though...
as for now, the problem is solved.

somjit{} 60 Junior Poster in Training Featured Poster

this code gives the correct result upto size 6 (i'v run this a few times, and 6 seems to be the boundary), although the intermediate steps are all insane! then onwards, from size 7, it returns minimum value 0

/*minimum of an array using recursion*/

#include<stdio.h>
#include<stdlib.h>

int findMin(int* arr,int min,int size);
int* populateArray(int size); 
void printArray(int* arr,int size);
int main(){

    int i=0,size=0,min=0;
    int* arr;

    printf("enter size of array: ");
    scanf("%d",&size);

    arr=populateArray(size);

    printf("array is: ");
    printArray(arr,size);

    min=*(arr+0);

    min=findMin(arr,min,size);
    printf("\n\nthe min value in the arr is: %d\n",min);

    return 0;   

}

int* populateArray(int size){
    int i=0;
    int* arr;

    arr=(int*)malloc(sizeof(int)*size);

    srand(time(NULL)); 
    for(i=0;i<size;i++){
        *(arr+i)=(rand()%1000); 
    }   
    return arr;
}

void printArray(int* arr,int size){

    int i;
    for(i=0;i<size;i++)
    printf("%d ",*(arr+i));
    puts("\n");
}


int findMin(int* arr,int min,int size){

    printf("in findMin() : passed values >> array:%d  min:%d  size:%d\n",*(arr),min,size);
    static int j=1;

    if(j==size){
        return min; 
    }
    else if(min>*(arr+j)){
        min=*(arr+j);
        j++;
        findMin((arr+j),min,size);  
    }
    else if(min<*(arr+j)){
        j++;
        findMin((arr+j),min,size);
    }

}

i cant understand why this is so... :(
any help regarding the matter would be great. :)

regards
somjit.

somjit{} 60 Junior Poster in Training Featured Poster

i was searching for a code to perform binary XOR addition.
Exams coming up, and needed to a quick way to create and verify standard array tables. However, i didnt find anything substantial on the internet, so made my own version of it.

can anyone take a look and tell me if there's some other(better) way to do this?
thanks in advance for your time :)
somjit.

here's the code:

#include<stdio.h>
#include<string.h>

int main(){
    int *stop,decNum1=0,decNum2=0,result=0,ip_base=2,flag=0,i=0,binLength=0,temp=0,opResult[15];
    char num1[15],num2[15];

    puts("\n");

    do{
        printf("enter two binary numbers of same length(<15):\n");

        printf(" enter 1st binary number: ");
        fgets(num1,15,stdin);
        binLength=strlen(num1);
        decNum1=strtol(num1,&stop,ip_base);// decNum1 is the dec equivalent of binary input num1(a string)

        printf(" enter 2nd binary number: ");
        fgets(num2,15,stdin);
        decNum2=strtol(num2,&stop,ip_base);

        result=decNum1^decNum2; // dec equivalent of XOR addition
        printf("\n xor output:\n\n ");

        for(i;i<binLength;i++){ // converts the dec back to binary
            temp = result%2;
            result=result/2;
            opResult[i]=temp;
        }

        for(i=binLength-1;i>=0;i--){ // prints the result in the correct order
            printf("%d",opResult[i]);
        }


        printf("\n\n repeat? 1.yes 0.no\n ");
        scanf("%d",&flag);
        while((i=getchar())!='\n'){}
        i=0;

    }while(flag==1);

    return 0;
}

i hope someone finds the code useful. :) and for anyone who might be in a tiny confusion, Info & Coding theory more generally refers binary XOR as "modulo-2 addition". :)

somjit{} 60 Junior Poster in Training Featured Poster

The easiest fix (provided the list isn't gargantuan big) is to create a temp copy of the original list to iterate thru, then you can delete from the original with no problems

yaayyy!! it works!! im sinking ships like never before!! :D

will be looking at the listiterator and the naming conventions now..
(after i sinkSomeMoreShips() that is.. :D )

this problem : solved.

thank you so much :)
somjit.

somjit{} 60 Junior Poster in Training Featured Poster

this is what the java gives me ...

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819) 
at java.util.ArrayList$Itr.next(ArrayList.java:791)                   
at BattleShipEnhanced.checkGuess(BattleShipEnhanced.java:108)         
at BattleShipEnhanced.startPlaying(BattleShipEnhanced.java:101)       
at BattleShipEnhanced.main(BattleShipEnhanced.java:134)

and regarding the temp, and Listiterator, im gonna look at your suggestions right now :) also, thanks for the nomenclature tip :) it gets confusing with all the uppercase and lowercase and where to use them n how n all......! :P

ps: i think i need to find a better word than "nomenclature".... just.tooBig()! feels misplaced everytime i write it anywhere related to programming :|

somjit{} 60 Junior Poster in Training Featured Poster

Sooner or later you will get to that place, after which you will have climbed the learning curve, and will have no further need of Scanner. In the meantime there's no harm in doing it the easy way and using Scanners.

that sounds good :)

but , as regards my code, its running into a java.util.ConcurrentModificationException problem... its like, im stating how many ships there will be, and the game setup goes fine, the program asks the user to make guesses, and sinks the ship like it should, its all seems fine, but when all the ships are sunk, and the game should end,im getting this exception... any help? (again.. :| )

i did read about this exception in the java api docs, and understand what causes it, but im a bit lost on how to modify my code so that it doesnt occur.

this is the initial (n a few later) error corrected version which is giving the above exception:

import java.util.Scanner;
import java.util.ArrayList;

class ship{
    private int shipSize=0;
    private String shipName;
    ArrayList<Integer> shipCell = new ArrayList<Integer>();


    // setters :
    public void setShipName(String name){
        shipName=name;  
    }
    public void setShipSize(int size){
        shipSize=size;  
    }
    public void setLocation(int cellLocation){
        shipCell.add(cellLocation);
    }

    // getters :

    public int getShipSize(){
        return shipSize;
    }

    //methods :

    public void putShipInBattlezone(int start){

        // int seed = (int)((Math.random()*15)+5);
        // int randomNum=(int)(Math.random()*10); // the virtual array is of size 15

        for(int i=0;i<shipSize;i++){         
            setLocation(start+i);
        }
        System.out.println("\n\nbattleship placed.. \n\n");
    }

    public boolean checkHit(int guessedLocation/*,int size*/){

        //System.out.printf("in checkHit, location passed: …
somjit{} 60 Junior Poster in Training Featured Poster

Personally I prefer not to use Scanner at all.

in a lot of videos, im seeing poeple opt for BufferdReader over Scanner, they say its more effective, ur amongst them too it seems :) ... i dont really know much about BufferedReader, nor Scanner for that matter. a few days ago, was searching on how to add user inputs, found a video using Scanner, i liked it, and so just stuck to it since then. can u give a short explanation on the advantages in using BufferedReader? a few links too perhaps?

thanks :)

somjit{} 60 Junior Poster in Training Featured Poster

maybe the simplest is a quick "throw away" nextLine after the nextInt to consume the newline and leave the Scanner at the start of the next line as expected.

this works :) but is there a better way to do this? something like check input stream untill a white space is encountered, and clear that whitespace from the stream? thus keeping the stream pristine?

somjit{} 60 Junior Poster in Training Featured Poster

my errors are fixed!! thank you so much :) but now as i run them, another error is coming in...
in this loop:

for(int i=0;i<numOfShips;i++){

                // create an instance of the ship class
                game[i]= new ship();

                //get a name for a instance to create
                System.out.print("enter name of ship: ");
                game[i].setShipName(input.nextLine());

                //set size
                System.out.print("enter size of ship: "); // ship size entered
                game[i].setShipSize(input.nextInt());       

                //place it on battlezone
                System.out.print("enter starting cell of ship: ");
                game[i].putShipInBattlezone(input.nextInt());       

                //put the newly created instance inside array list
                shipList.add(game[i]);
            }

the entire game[i].setShipName(input.nextLine()); part gets skipped, and the program goes to the part where it asks to enter size of the ship.

in C, this happened when mixing formatted and unformatted input, like getchar() after a scanf(), is something like that happening here too?? im guessing the input.nextLine() method is reading a newline character from the input stream, and hence returns without taking user input.. is that whats happening here ?? any way i can fix this... ?

thanks again :)
somjit.

somjit{} 60 Junior Poster in Training Featured Poster

i dont understand the reason why im geting the errors i am with this code... errors with arraylists, also a few other errors like symbol not found etc s.. i corrected the ones i could, but the ones (5 of them in total )im still geting, i dont understand them...

the code is my version of a battleship game found in head first java, 6th chapter..
it takes user input on number of ships, and allocates some blocks to them, when all blocks are hit, the ship sinks, and when all ships are sunk... you win the game...

this is the code:

import java.util.Scanner;
import java.util.ArrayList;

class ship{
    private int shipSize=0;
    private String shipName;
    ArrayList<int> shipCell = new ArrayList<int>();


    // setters :
    public void setShipName(String name){
        shipName=name;  
    }
    public void setShipSize(int size){
        shipSize=size;  
    }
    public void setLocation(int cellLocation){
        shipCell.add(cellLocation);
    }

    // getters :

    public int getShipSize(){
        return shipSize;
    }

    //methods :

    public void putShipInBattlezone(int start){

        // int seed = (int)((Math.random()*15)+5); // for later use, once the simpler version runs errorfree
        // int randomNum=(int)(Math.random()*10); // the virtual array is of size 15

        for(int i=0;i<shipSize;i++){         
            setLocation(start+i);
        }
        System.out.println("\n\nbattleship placed.. let the destruction begin!!\n\n......................................................");
    }

    public boolean checkHit(int guessedLocation/*,int size*/){

        //System.out.printf("in checkHit, location passed: %d  size passed: %d \n",guessedLocation,size);
        System.out.printf("in checkHit, location passed: %d \n",guessedLocation);
        boolean checkHitFlag=shipCell.contains(guessedLocation);

        if(checkHitFlag){
            shipCell.remove(guessedLocation); // arrayList shrunked         
        }
        return checkHitFlag;
    }

    public boolean checkSunk(){

        System.out.printf("\nin checksunk,\n");
        boolean sunkFlag=shipCell.isEmpty();
        return sunkFlag;
    }
    public void shipHasSunk(){
        System.out.print("Bravo!! you have sunk the %s!",shipName); 
    }   
}

class BattleShipEnhanced{
    Scanner input …
somjit{} 60 Junior Poster in Training Featured Poster

i found out the bug...

the checkSunk() method was originally this:

public boolean checkSunk(int num){
        boolean sunkFlag=false;
        if(shipCell.length==num){ // this caused my problem
            sunkFlag=true;
        }

but it needs to be this:

    public boolean checkSunk(int num){
        boolean sunkFlag=false;         
        if(shipSize==num){ // corrected version
            sunkFlag=true;
        }           
        return sunkFlag;
    }

code runs ok now :) thanks for the debugging tip :) made me go over my code one line at a time:)

somjit{} 60 Junior Poster in Training Featured Poster

(I did have a quick look at the logic, but nothing jumped out at me. I was confused by the naming vs the implementation - the naming suggests that there is one ship of length 8, but the logic seems more like 8 disconnected one-cell ships)

the book called it virtual array, as if we have a array of a certain length, and, some of the blocks get "marked" i guess, and these marked elements are our "ships", so a number of blocks can be grouped together to form a "aircraft carrier", or individual blocks can be there too, like coast guard patrol boats... and the user has to "sink" them all... and "virtual" comes in here, because instead of actually creating that really long array in memory,and physically "marking" some of its blocks, just a few numbers are taken,representing the marked blocks, and stored in the shipCell array. thus we dont have to create that really big array anymore...

and...
as regards debugging using prints, doing them now :) lets see what i end up with... :)

somjit{} 60 Junior Poster in Training Featured Poster

Rather than just trying different things, add lots of print statements to your code to display the values of all the important variables and arrays wherever they are changed.

i did that too... and thats what showed me that the do-while loop in the main() method was going 8 times(or whatever value i initialized the shipCell array with), even though i passed values like 3,4 etc, to the checkSunk() method, as it controls (to my understanding..) the running of the loop. but still nothing happened, and it keeps running 8 times... surely im not putting the statements in the right places ... but i cant figure out how to correct it... thats why i posted it here... any help would be really great :)

somjit{} 60 Junior Poster in Training Featured Poster

this code is my attempt at modifying a simple game i found in the book "head first java".. (pg-98 if anyone's interested)
the game is about sinking battleships! ...
actually... its just about declaring some blocks of a virtual array to comprise a battleship, and the user makes guesses about which blocks contain the battleship.
when all the correct blocks are guessed, the game ends, whith a display that the battleship has sunk.

my problem is that no matter how much i change the values and conditions, the for loops that control the number of times the user is asked to make a guess, always run a fixed number of time. which is equal to whatever size i declare the shipCell array in the line private int shipCell[]= new int[8]; of the 1st class... which,in this case, is 8.

this is my code for it(the nomenclature of the two classes follows from that in the book):

import java.util.Scanner;

class SimpleDotCom{
    private int hitNum=0,shipSize=0;
    private int shipCell[]= new int[8]; // this stores the blocks that comprise our battleship..
    Scanner input = new Scanner(System.in);

    // setters :

    public void setShipSize(int size){
        shipSize=size;  
    }
    public void setLocation(int cellLocation, int index){
        shipCell[index]=cellLocation;
    }
    public void setHitNum(int num){
        hitNum=num;
    }

    // getters :

    public int getShipSize(){
        return shipSize;
    }
    public int getHitNum(){
        return hitNum;
    }

    //methods :

    public void putShipInBattlezone(){

        for(int i=0;i<shipSize;i++){
            System.out.print("enter ship location (0 to 10) : ");
            setLocation(input.nextInt(),i);
        }   
    }


    public boolean checkHit(int guessedLocation,int size){

        boolean flag=false;
        for(int …
somjit{} 60 Junior Poster in Training Featured Poster

thanks :) i get it :)

somjit{} 60 Junior Poster in Training Featured Poster

this is my code, from the book Head First Java ...

class Echo {
    int count=0;

    void hello() {
        System.out.println("Helloooo.....");
    }
}

public class EchoTestDrive {
    public static void main(String[] args)  {
        Echo e1 = new Echo();
        Echo e2 = new Echo(); // output 10
        //Echo e2 = e1; // output 24
        int x = 0;

        while(x<4) {
            e1.hello();
            e1.count=e1.count + 1;
            if(x==3){
                e2.count=e2.count + 1;
            }
            if(x>0){
                e2.count=e2.count + e1.count;
            }
            x++;
        }
        System.out.println(e2.count);
    }
}

my output:

with the line Echo e2 = e1;
Helloooo.....
Helloooo.....
Helloooo.....
Helloooo.....
24

whereas Echo e2 = new Echo(); gives
Helloooo.....
Helloooo.....
Helloooo.....
Helloooo.....
10

i couldn't understand why that one line affects the output like this, and also, i'v just started learning java, so didnt know what to google either.. so posted it here. hopefully im not being too much of a pest..

thanks in advace for any help.. :)
somjit.

somjit{} 60 Junior Poster in Training Featured Poster

it's the classic stream garbage problem when mixing formatted and unformatted input.

is what one of the morderators, deceptikon, had this to say to me when i was having similar problems some time back. you can read about it more here

so back to ur code, i modified it a little. here it is:

void PrintHeader();
int TotalSales();
float OverallProfit(float totalvalue, float drinkcost, int runningcost);
float CalculateCosts();//Not used yet
int IncentiveCheck();  //Not used yet
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int teasold=0, coffeesold=0, hotchocsold=0, lattesold=0,bool=0;
    int flatwhitesold=0, totalsales=0, drinktype=0;
    float tea=1.00, coffee=1.50, hotchoc=2.00, chailatte=1.75, flatwhite=2.20;
    float totalvalue=0, runningcost=10.00, totalprofit=0, drinkcost, incentive, overallprof;
    float teacost=0.20, coffeecost=0.25, hotchoccost=0.50, lattecost=0.25, flatwhitecost=0.50;
    char yesno, dollar='$';
    PrintHeader();

    /*this loop runs for taking input, and the sales figures are shown only after all entries are made*/
    do{
          if(totalsales==500) 
            break;        
          if(bool==0){       // i declared a new variable bool, for controlling the while loop
              printf("\nAdd In Sale? Y/N: ");
              yesno=getchar();
              printf("entered value: %c\n\n",yesno);
            }  
          if ((yesno=='Y') || (yesno=='y'))
          {
               totalsales=TotalSales(totalsales);
               printf("\nDrink type?\n\n");
               printf("1.    Tea\n");
               printf("2.    Coffee\n");
               printf("3.    Hot Chocolate\n");
               printf("4.    Chai Latte\n");
               printf("5.    Flat White\n\n");
               printf("You choose: ");
               scanf("%d", &drinktype);
               switch (drinktype)
               {  case 1: teasold=teasold+1;
                            break;
                  case 2: coffeesold=coffeesold+1;
                            break;
                  case 3: hotchocsold=hotchocsold+1;
                            break;
                  case 4: lattesold=lattesold+1;
                            break;
                  case 5: flatwhitesold=flatwhitesold+1;
                            break;
                  default: printf("Please choise a valid option");
                           break;
               }
            while(getchar()!='\n'){}   
          }
          else if ((yesno=='N') || (yesno=='n'))
          {
            break;  
          }

        printf("Add more? 1 for yes, 0 if no:  ");
        scanf("%d",&bool);
        while(getchar()!='\n'){} 
    }while(bool==1);

    printf("\nTotal Sales: %d\n\n", totalsales);
    printf("Total Tea Sales: %d\n", teasold); …
somjit{} 60 Junior Poster in Training Featured Poster

put a BIG dividend in the above code, in terms of Million, and a small divisor, and the thing takes forever!!!
the only thing positive from this code , to me, is i got a sense of the rate of while loop operations.. 42 thousand loops in around 8-10 secs...(i gave up after that.. the feeling i got while the program ran was very unsettling).

facebook apparantly wanted the bitwise operator division method...

somjit{} 60 Junior Poster in Training Featured Poster

@nitin1

the division by substraction seemed pretty straight forward.. atleast for non complicated cases with small inputs. this is a simple code i came up with just sitting down with a pencil n paper ..

 #include<stdio.h>


    int main()
    {
        int divsr,divden,i=0,rem=0;
        divden=30;
        divsr=5;
        printf("before division:\n");
        printf("divident: %3d   quotient:%3d\n",divden,i);

        printf("now dividing...\n\n");
        while(divden>divsr){

            divden-=divsr;
            ++i;
            printf("divident: %3d   quotient:%3d\n",divden,i);
        }
        if((divden<divsr)&&((rem=divden)>0)){
            printf("\nafter division:\tdividend:%3d divisor:%3d quotient:%3d remainder:%3d\n",((i*divsr)+rem),divsr,i,rem);
        }
        else if((divden==divsr)){
            divden-=divsr;      // eliminates the off by one error
            ++i;        
            printf("%3d is completely divisible by %3d, remainder: 0   quotient :%3d\n",((i*divsr)+rem),divsr,i);
        }   
        return 0;
    }

u can replace the "divdn=30" lines with a printf()-scanf() pair easily.
hope it helps. :)

somjit{} 60 Junior Poster in Training Featured Poster

the draft standard is just wow!!!

man! if only the college teachers abided by stuff like these...

somjit{} 60 Junior Poster in Training Featured Poster

There's really only one true case of a function being straight up "bad" across the board, and that function is gets()

use fgets() and stay happy.. :)
use gets() and get buffer overflow! (its quite easy to understand why it does that as well..)

as regards atoi() , i guess only if the programmer knows exactly how his code will be used, he can go with atoi() if needed... but the limitations i'm reading about it, makes it bad for any real life, out-of-the-classroom coding situations anyways.

some links i found useful:

  1. gets() being bad: read here
  2. atoi() being bad: read here and here

Fortunately, gets() was removed in the latest revision of the C standard.

any links to some good C11 resources ? the page i refer to most of the time is C89 standard.. the cplusplus.com

somjit{} 60 Junior Poster in Training Featured Poster

but anyone who says strtok() is evil and should never be used is an idiot.

i think all this bad hype about strtok() is only coz people who dont know about these issues with it, put it in their code n think everythings gonna work fine,
and then, they hit run ....... and crash! :P

hence the frustration, leading it to the evil tag.. :P
satan's parser!!

somjit{} 60 Junior Poster in Training Featured Poster

actively and intentionally goes against its design

a lot of ppl suggest strtok() for parsing... just shows how many ppl dont read (what can be said as) "the fine print" associated with a function...
daniweb's clearing stuff out.. so thats good :)

on another note, what is strtok() good/designed for?
there was this part in that page :

The correct way to use strtok is to pass it a copy of the string unless you know that it’s ok to modify it.

so thats how strok() should only be used?

the 2nd code in that page also feels good.. :)

somjit{} 60 Junior Poster in Training Featured Poster

im reading this page about strtok() being bad... and i quite like it... has quite a detailed explanation of things..

for those interested, this page has a nice and short definition of re entrancy, and also this page,... though its a bit hard to understand (to me!)

somjit{} 60 Junior Poster in Training Featured Poster

strtok uses the name of the string on its first invocation, NULL thereafter for the same string.

that sounds good... any code exapmples?