NP-complete 42 Junior Poster

Okay, first of all that apparently meaningless output is NOT representing "1" in any language, not even Klingon :)

As James mentioned, the part after [B@ is an unique ID for the array so every time you recompile your code its gonna print out something different.

Now,

"1".getBytes() returns a byte array which as per your call contains '1' - the number. (Byte in java is just another integer datatype with the shortest range, -128 to 127. And a byte array doesn't mean it will give you the binary representations of the numbers it contains)

So 2 places where you went wrong:
1. You were trying to print the array itself and not its contents.
2. System.out.println (Arrays.toString(array)); as James mentioned will give you 49 which is the ASCII representation of numeric 1. (Did you try it correctly? It shoudn't have given you that [B@... stuff again! Did you add import java.util.* at the top?)

Finally, to get a clearer picture and to understand that byte array is nothing but just another int array where you can only put integers < 127 and > -128, try the following code:

public class ByteArrayExample
{
    public static void main (String args[])
    {
        byte[] array = {1, 2, 3};
        for (int i = 0; i < array.length; i++) {
            System.out.println (array[i]);
        }
    }
}
NP-complete 42 Junior Poster

So you want to echo the command line?

Well, well... consider this simple code snippet for that (from oracle's official tutorial):

public class Echo {
    public static void main (String[] args) {           
        for (String s: args) {
            System.out.println(s);
        }

        // you could have also used 
        // for (int i = 0; i < args.length; i++)
        // then inside, println(args[i])
        // the above is just a handy syntactic sugar
        // to print arrays and collections.
    }
}

Now output depends on how you give the input:

c:\yourCodeDirectory>java ab cd
ab
cd

c:\yourCodeDirectory>java "ab cd"
ab cd

c:\yourCodeDirectory>java "ab    cd  ef       gh            etc"
ab    cd  ef       gh            etc

So, moral of the story, giving inverted commas ("") around your command line input will treat the entire sequence (till you hit enter) as a single entity.

NP-complete 42 Junior Poster

that's strange... I simulated your scenario to see if i was missing something... but it worked perfectly in my case as it should!

Try running any other java code in your system... btw, are you sure your jdk is valid (was downloaded from the official Oracle site)?

NP-complete 42 Junior Poster

You mean you want to put 2 spaces, right?

If that's the case, then look at my code once again and tell me where you can change it to print 2 spaces?

NP-complete 42 Junior Poster

Doesn't the above code do that already? Please elaborate...

NP-complete 42 Junior Poster

Probably this is what you're looking for:

public class numbers {
    public static void main(String[] args) {
        final int N = (args.length);
        for (int i = 0; i < N; i++)
            System.out.print(args[i]);
        System.out.println();
        System.out.print('\"');
        for (int j = 0; j < N; j++) {
            System.out.print(args[j]);
            // this will give a space after
            // every word, except the last
            if (j < N-1) {
                System.out.print(" ");
            }
        }
        System.out.print('\"');
        System.out.println();
    }
}

Hope this helps... :)

NP-complete 42 Junior Poster

Are you sure your commnad prompt says like this:

c:\>myWork>javac Example.java
c:\>myWork>java Example

?

NP-complete 42 Junior Poster

How does the Sorting.insertionSort() method look like? Is it from any standard API?

NP-complete 42 Junior Poster

You never calculated total time. The variable TimeRequiered simply calculates the time for each change and when you print the value outside the loop it prints the last value.

To calculate total time first initialize the variable TimeRequiered to 0 at the beginning. Then change line# 44 to

TimeRequiered = TimeRequiered + (DistanceLenght/DistanceSpeed * 60);

This will get you the total time for each journey.

BTW, your variables need to be floats or doubles to handle decimals.

NP-complete 42 Junior Poster

It is possible. What do you think should be the strategy? It looks like a homework question, so we'll only provide hints. But first think of something yourself and we'll help you build on it.

Also, please specify what your input files look like so that we have an idea of how the merge is happening.

NP-complete 42 Junior Poster

@Taywin: I think you meant your loop to be :
for (int i = 1; i < array[index]; i++

and NOT
for (int i = 1; i <= array[index]; i++)

Why inclusive? Pseudo code syntax?

NP-complete 42 Junior Poster

Define a string somewhere and call it whatever... i called it str...then inside that loop use this:

// for the last word, no comma afterwards...
if (i == (aa5.length - 1)) {
    str = str + aa5[i];
} else {
    str = str + aa5[i] + ", ";
}
NP-complete 42 Junior Poster

@Greywolf333: my pleasure...:)

And Narue, thanks once again...well explained.

NP-complete 42 Junior Poster

First, always put your code in CODE tags...(and try not to post things in languages other than english)

Well, with a quick glance, here are a few things that i can see:

1) I don't think you can use new[] without specifying any size. You'll probably want to do something like

// using your variable names
int *freq = new int[limit];
int *munam = new int[k];

2) You have to initialize the freq array (the thing you did with the second for loop (with variable j)) first and NOT inside the main for loop (having variable i)

Implement these changes and let us know more...(but next time you post, please use code-tags)...
Also, indent your code properly and don't use single letters and/or your name as variables.

NP-complete 42 Junior Poster

@gahhon: I think the above examples, specially that of sirlink99's (maybe he forgot to give a name to his method) did exactly that...or maybe i don't understand your question...

In case you didn't understand sirlink99's example, here's it once again (with a method name, this time):

public double myPow(double number1, double number2) {
    return Math.pow(number1, number2);
}

The braces around the ((Math.pow(...)) is not necessary; don't know if they were confusing you...:)

NP-complete 42 Junior Poster

Thank you, Narue, for the clarifications...:)

In my original post, the NUL part was insignificant and i really wanted to highlight that C-string thing.

I wasn't too sure, because a few codes were "working", but somehow i felt it was wrong and hence asked for your confirmation...much thanks once again...:)

NP-complete 42 Junior Poster

I didn't say he was wrong only to spell NUL as NULL...well, if you check the ASCII table, '\0' is called NUL and has been named so because it has no resemblance with the NULL pointer.

Having said that, where I think Greywolf333 was wrong is that the compiler doesn't automatically appends a NUL at the end of the char array, if it isn't explicitly mentioned. I think i mentioned(read, explained) this in my post.
For example,
if you declare something like this:

char ch[] = {'a', 'b', 'c'};

the compiler will NOT insert a NUL ('\0') at the end.

If you try any standard sting library functions such as strlen(), etc. you'll get (probably) wrong results.
Why probably? Well, in most cases you'll get an array overflow...and it'll invoke undefined behavior which will be left to your compiler to interpret and it will interpret it as it deems fit. So maybe, in some compiler, your code will "work" but under the hood there will remain a very subtle bug.

Moral of the story: Always declare your C-strings either like:

char str[] = "this is a C string, and the compiler knows it, because of the inverted commas, so puts a NUL character at the end";

or, like this:

char str[] = {'h', 'e', 'l', 'l', 'o', '\0'};

Note the NUL at the end.

Hope it helps...:)

NP-complete 42 Junior Poster

@Greywolf: that's wrong!

@murnesty: by NULL you really mean '\0'...right? that's actually called NUL (single L)...
What you've declared is just a simple character array and NOT a C-string. The compiler won't make that a C-string automatically. So if you really want to make it a C-string you'll have to declare it like this:

char ch[5] = {'1','2','3','4','\0'};

Or this will also do:

char ch[] = "hello";

This time the compiler will automatically convert it into a C-string by appending the NUL character at the end.
So internally your array will look like this:
{'h', 'e', 'l', 'l', 'o', '\0'}

Hope it helps...:)

NP-complete 42 Junior Poster

@cse.avinash: i think Narue already explained that! You said nothing new!

NP-complete 42 Junior Poster

Right, it was giving me a seg-fault when newString[0] = '\0' was not done. After that change, free() is working fine.
My reasoning wsa wrong.
Should have checked...

NP-complete 42 Junior Poster

The pleasure is all mine...:)
It was quite interesting actually...

Well, There are still a few more gotchas:
1. Do not free() numberString and letterString. You never malloc()'ed them. (try to run it in gcc, and you'll get a seg-fault)
2. Your strcat() wont work because newString is not yet a C-String. So at line 18 add this:

newString[0] = '\0';

3. Also, in your for loops, loop till loopCounter < stringSize (not <=). What you were doing was taking you outside the bounds of your array.
Hope that helps.

NP-complete 42 Junior Poster

Well, its surprising, but here's the solution:
change all your if conditions to this:

if(isalpha(string[loopCounter]) || ispunct(string[loopCounter])	|| isspace(string[loopCounter]) )

i.e. dont check for == 1. The standard for isalpha (and other related functions) says that it returns a value other than zero; doesn't guarantee 1.

Strange, eh?

NP-complete 42 Junior Poster

great...then mark this thread "solved"...:)

NP-complete 42 Junior Poster

okay, firstly, repeat this a 100 times,

"I'll never call main() from other functions"

main() is supposed to be called by the OS, and it will get really angry if you call it instead..!!

so remove all those calls to main() (line no. 31 to 33) and you'll get out of that loop...

oh, btw, you'll have to pass the sides to your calculations() function like this:

void calculations (int side1, int side2, int side3)
{
    // Do calculations
}

and offcourse, change the prototype suitably...


P.S: your main logic for triangle checking is flawed...

NP-complete 42 Junior Poster

well, abstract classes are "abstract" and provides "abstraction". That's one way to look at it. Think of it like this:

They don't allow you to create objects, right? Now, why do you think that is required?
Lets take an example, say we have a Human class which has two subclasses, Male and Female.
Now, we can have male objects as well as female objects but what about human objects? Do we know how a human looks? have you ever seen a human separately?
So obviously it makes no sense to create human objects. So we mark the Human class as abstract and prevent it from being instantiated.

Obviously there are other uses to it which includes providing some default behaviors for all the subclasses that extends the abstract class. Google is always your friend.

NP-complete 42 Junior Poster

Nope, i think you didn't go through my post completely. I said his algo is correct provided you print the first two ie fibo(0) and fibo(1) separately. Also it seems you have introduced an error (a typo, maybe). Look at line no. 6 and 9 of the code which you modified previously. the OP had n=f+s once inside but you made it twice.

Well, your compact code is definitely right but is somewhat hard to read and understand.

I was talking of something like this::

#include <stdio.h>

int main(){
    int f=0,s=1,n;
    n=f+s;
    printf("%2d    %5d\n", 0, f);  //fibo(0), separately printed
    printf("%2d    %5d\n", 1, s);  //fibo(1), separately printed

    for (int i=2; i <=18; i++){
	printf("%2d    %5d\n", i ,n);
	f=s;
	s=n;	
	n=f+s;
    }
/*
now result is:

 0        0
 1        1
 2        1
 3        2
 4        3
 5        5
 6        8
 7       13
 8       21
 9       34
10       55
11       89
12      144
13      233
14      377
15      610
16      987
17      1597
18      2584

though the OP wanted upto 18 terms and that should have printed upto fibo(17) but i kept fibo(18) coz that seems to be the centre of all confusion :)
*/

}

hope it clarifies.

NP-complete 42 Junior Poster

@tesu:
The algorithm is correct. Its just that the first tw0 terms of the series must be printed separately. fibo(18) is 2584 iff fibo(0) = 0. So what you are printing as your first term should be the 2nd term (ie fibo(2) if we take the first term as fibo(0)).

generally the series is :

fibo(0)------ 0
fibo(1)------ 1
fibo(2)------ 1
fibo(3)------ 2
fibo(4)------ 3

...............
...............

fibo(18)------ 2584


hope it helps.


P.S: @xaop
once you get the logic correct spend some time on coming up with meaningful variable names. Also use proper indentation. As of now, a small advice, never use void main(). Its plain wrong (and disrespect to the creators of C).

NP-complete 42 Junior Poster

i guess this is too easy to fetch him a grade:) ...but still...i'll be more carefull next time...

and thanks for the compliment...

NP-complete 42 Junior Poster

After changing the loop condition to what you have been told, your main problem will be line no 6. Here's the modified code:

#include <iostream>
using namespace std;

int main(){
    int num, count = 1;
    cout<<"Please enter a number: ";
    cin >> num;
    while(count < num){
        cout << " " << count;
	count = count + 2;      //it shoudn't be count = num +2
    }
    cout <<" end";
}

Try to understand why its working the way its working...and you already have the technique...just be the compiler and do a dry run.

Hope it helps.

NP-complete 42 Junior Poster

firstly i congratulate you for your attempt on "being the compiler" and checking the code as the compiler would have. That's a nice approach. But unfortunately the compiler is not as logical about logical operators as it should have been. There's something called "operator precedence" which kills the fun. So when you are doing

if (num1 > num2 && num3)

the > operator gets more preference and checks whether num1 is greater than num2. Lets say this is TRUE. Then it does something like TRUE && num3. This is definitely not the way you wanted it to be. right??
So, basically you have to do something like:

if (num1 > num2 && num1 > num3)

Do this for all your IFs.

Your 2nd and 3rd code has been explained by daviddoria. Go through them and do as you have been told and come back if you have any doubts.

Happy to help.
Cheers...

empror9 commented: thanks *_^ +1
NP-complete 42 Junior Poster

@tesu:

O yes...i got carried away, actually the title of this thread is a bit misleading...


@manutd4life:

in that case the code snippet is not exactly what you want...
But i guess it'll help you come up with this algo, actually it just needs a li'l tweaking...
and my previous post showed you how to take string inputs and store them in char arrays...

good luck.

NP-complete 42 Junior Poster

well, here you go...

//first think of the max length of your array and make it a constant;
const int MAX_SIZE = 256;
//then declare your array
char sentence[MAX_SIZE];
//now you need to ask the user to enter something
printf ("please enter the string \n");
//now comes the main part...storing the user input in your array...get ready...
fgets (sentence, MAX_SIZE, stdin);

that's it...your array will get filled with whatever the user inputs (even if that is lesser than 256 chars, no probs. The function will store the input and append it with a null character. For e.g if you enter "hello" your array will look like:

sentence[] = {'h', 'e', 'l', 'l', 'o', '\0'} the other spaces will simply not matter.


BTW, to use this array in the code snippet by William Hemsworth you need to modify the function call a bit like:

int index = 0;
while ( add_letter(sentence[index++], counters) );

hope it helps.


P.S: Sometimes its a good idea to initialize your array as char sentence[MAX_SIZE + 1] ( note the + 1). This way you guarantee the space for the null character. It all depends on the coder though. Like in this example I assumed (A very foolish assumption, though) that the sentence length won't go beyond 256 and there will be at least a single space for my beloved Mr. '\0'.

NP-complete 42 Junior Poster

I second WaltP...:)

NP-complete 42 Junior Poster

If your looking for OOP design then you can give this book a try: "Head First Design Patterns" from O'Reilly. It's very good. Regarding UML you only need to learn a few basics and the rest will come along as and if you work with it. For that you can start with a book called UML distilled by Martin Fowler.

Hope it helps.

NP-complete 42 Junior Poster

First do the changes i mentioned. It will work just fine. Assign y=a[0] and change the loop conditions. Also in line no 119 change it to something like :

cout<<"The countrie with the most visitors is :"<<list[m]<< " with " <<y<< " visitors"<< endl;

you were printing out country[m] it should be list[m] as your loop goes from 0-149 and your country array has got only 2 elements.


Your function works... By logical error i meant that y=0 thing.
Enjoy.

NP-complete 42 Junior Poster

as far as your 2nd prob is concerned look at line no. 100 and 101. You forgot to change the <= to < as already advised by Fbody. Also at line no. 108 you have to change the i to k.

Other than that think about the logic of the function. I think your logic is not correct.
You again have the same problem. Assign y to the first element of the array.

NP-complete 42 Junior Poster

IMHO, I think you'll have to change your youngest_women function to something like:

void youngest_women(){
	int m=0,y=age[0];
	for(int i=1;i<count;i++){
		if(sex[i]==1){
			if(y>age[i]){
				y=age[i];
				m=i;
			}
		}
	}   //end of for
	cout<<"The youngest women visited Bulgaria is: " <<Fname[m]<<" "<<Sname[m]<<" "<<Lname[m]<<" at age of "<<age[m]<<" from "<<country[m]<<endl;
}

First of all your cout should come after the for loop.
Secondly, I changed the if condition to

if (sex[i] == 1)

This is optional (since you are taking females as 1) but I think it becomes more compiler independent(others please clarify).
Thirdly assign y to the first array element.

y = age[0];

(i think you can guess why)

hope it helps...
cheers....

NP-complete 42 Junior Poster

Thanks Dave...even i got confused for a moment.

NP-complete 42 Junior Poster

Great. glad that you liked it.

About closing threads, i don't know...i think its upto the admins and mods...lets see if others can clarify.

NP-complete 42 Junior Poster

Hi Sparkle Jam, no offense but i would just like to give you some advice...firstly start writing STANDARD code. In all probability you are using an antique compiler like turbo c++. Dump that right NOW.
Secondly NEVER USE GOTO. Repeat that a 100 times. It makes code-maintenance so very difficult.
Also, I found you were tying to return from your functions by a call to main(). You should generally never call main() as it's the property of the OS and you shouldn't be interfering.
Hope it helps.
Cheers...