hiddepolen 32 Posting Whiz in Training

No, I dont agree.
First of all, you are creating a constructor which returns a String. That is not possible, all constructors are voids.
Next, toString() methods should just return a straight string, why would you call a Constructor?

DavidKroukamp commented: but true anyhow +7
hiddepolen 32 Posting Whiz in Training
public class TestProg2{
  public static void main(String args[]){
    String filler1="Rank";
    String filler2="Suit";
  Card card = new Card();
  System.out.println(card);
  }  
}

class Card{
  public String Card(){ 
    String test="of"; 
    return test;
  }
public String toString () {
   return "This is the toString() method in the Card Class";
}
}
hiddepolen 32 Posting Whiz in Training

Please use the CODE tags, to make the code readable.

Your code looks OK, what's actually wrong with it?
A tip for any future Java coding: Use Java naming conventions: Classes start with a capital letter (MyClassIsThis), and variables and methods start with a lowercase letter (myMethodIsHere, myVariablesName).

hiddepolen 32 Posting Whiz in Training
Integer.toHexString(myInt)
hiddepolen 32 Posting Whiz in Training

I think the best solution is to:
- make a class with:
- four variables: x1, x2, y1 and y2.
- keep a ArrayList<LineClass> of your generated lines
- draw each line in the ArrayList on your JPanel using g.drawline(line.x1, line.y1, line.x2, line.y2) where line is the element of the ArrayList

hiddepolen 32 Posting Whiz in Training

Hi

This is what I've made of it, usually I don't code an entire program, but this was fun, and the code was good. I modified the program quite a bit, you don't have to use all the things I did, but you can learn from it I hope.

- I made a do {} while {} loop around the entire program, to repeat the guessing
- I changed the way pins are checked
- I changed the printing of the number of pins
- I changed the random number generating

import java.io.*;
import java.util.*;

public class Main {
	private BufferedReader reader = new BufferedReader (new InputStreamReader (System.in));
	private int[] guess = new int[4];
	private int[] secret = new int[4];
	private int turn = 1;

	public static void main(String[] args) throws IOException {
		new Main ();

	}
	Main() throws IOException {

		//	intro //
		System.out.println ("Hi and welcome to the game Mastermind!! :)\nMade by Jakob Petersson\n\n");

		//	secret = {(w,x,y,z): w,x,y,z € {1,2,3,4,5,6}} //
		for (int i = 0; i < secret.length; i++)
			secret[i] = new Random ().nextInt (6) + 1;

		//	print the answer //
		System.out.println ("The secret: " + secret[0] + secret[1] + secret[2] + secret[3]);

		do {
			// ask for quess //

			for (int i = 0; i < 4; i++) {
				do {
					System.out.println ("Guess number " + (i + 1) + ": ");
					guess[i] = Integer.parseInt (reader.readLine ());
				} while (!(guess[i] >= 1 && guess[i] <= 6));

			}

			System.out.println …
hiddepolen 32 Posting Whiz in Training

Oh! I'm sorry, I thought I said 'if'. (I'm Dutch, so my English is not really good.)

Yes, if you indent your code manually, you'll find out eventually. I still think starting programmers should learn to code with IDE's, because they'll learn a lot faster, and never forget little stupid problems you would make in Notepad.

stultuske commented: nothing against using IDE's, but it's better not to depend completely on them. btw: mijn nederlands is hoogstwaarschijnlijk ook beter dan mijn Engels :) +12
hiddepolen 32 Posting Whiz in Training

Great, good job! I probably should have called it something else, but that's hard to describe...

If I find out why the second problem is there, I'll tell you (haven't found out yet)!

hiddepolen 32 Posting Whiz in Training

Inside the Set class:

public void removeObject(T anObject)
               throws CannotRemoveException
       {
         String paramClass = anObject.getClass().getName();
         String currClass;
         int removalCount = 0;
         
         T removeObject = null; // removeObject is my temporary object (not an official name)
       // Logic ...
         for (T currT: theList)
         {
            currClass = currT.getClass().getName();

            if (currClass.equals(paramClass))
            {
               if (currT.equals(anObject))
               {
            	   removeObject = anObject; // set removeObject as anObject
                  System.out.println("Member found and has been removed from "
                          + "the set.");
                  removalCount++;
               }              
            }
         }
         if (removeObject != null)
        	 theList.remove (removeObject); // remove the object from the list, when the loop is finished.
         
         if (removalCount == 0)
         {
             throw new CannotRemoveException();
         }
       }

(I hope for your instructor that he has not written this part...)

hiddepolen 32 Posting Whiz in Training

Looks great!

Please mark the thread as solved, if it is solved!

hiddepolen 32 Posting Whiz in Training

OK, lets go through it.

<html>
    <head>
        <title>Vaja 6.2</title>
        <style>
			.cell {
				background-color: #000;
			}
		</style>
        <script type="text/javascript">

            function enterSize()
                {
                x=prompt("Enter width:")
                y=prompt("Enter height:")
                
                for(var i=0; i<x; i++)
                {
                    document.write("<table id=table border=1 cellpadding=0 cellspacing=0>")
                    document.write(" <tr>")
                    
                    for (var j=0; j<y; j++)
                    {
						var maxVal = x>y ? x : y;
                        document.write(" <td width=40 height=40 class='cell' id='cell" + (i*maxVal+j) + "'>")
                        document.write(" </td>")
                    }
                    document.write(" </tr>")
                    document.write("</table>")                }

    
            }
            </script>
            <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body >
        <div><script>
            enterSize();
			var maxVal = x>y ? x : y;
			for (var i=0; i<x; i++) {
				for (var j=0; j<y; j++) {
					if ((i+j) %2 == 0)
						$('#cell'+(i*maxVal+j)).css('background-color', '#0F0');
					else
					$('#cell'+(i*maxVal+j)).css('background-color', '#FFF');
				}
			}
			$('.cell').click(function () {
				if ($(this).css('background-color') == 'rgb(0, 255, 0)')
					$(this).css ('backgroundColor', 'rgb(255, 0, 0)');
				else if ($(this).css('background-color') == 'rgb(255, 0, 0)')
					$(this).css ('backgroundColor', 'rgb(0, 255, 0)');
				else if ($(this).css('background-color') == 'rgb(255, 255, 255)')
					$(this).css ('backgroundColor', 'rgb(0, 0, 0)');
				else if ($(this).css('background-color') == 'rgb(0, 0, 0)')
					$(this).css ('backgroundColor', 'rgb(255, 255, 255)');
			});
            </script></div>
    </body>
</html>

What have I done:
- I made a maxVal for the problem with all the squares when y was bigger than x, and used that instead.
- I used jQuery for handling the clicks. The css function returns an rgb string, so you have to use that.

If you want to write some javascript yourself, go ahead, I like this.
Also, I reccommend trying to understand what I have done. Maybe you will learn something from it?

hiddepolen 32 Posting Whiz in Training

OK, you are now mixing three different types of changing the background colour.

- In the HTML, (bgcolor=grey)
- In the jQuery ($('#cell'+(i*x+j)).css('backgroundColor', '#0F0');)
- In your method (sivo.style.backgroundColor = "red";)

I would stick to either plain CSS, jQuery(using $(*).css(), your Javascript (using *.style.*), or HTML. The easiest for the things you want is still jQuery, but plain Javascript you type yourself will also work.
Anyway, I'd definately leave out the HTML, and code that part in CSS.

hiddepolen 32 Posting Whiz in Training

@skracer

Look into your code, and all our comments. Start learning, and dont copy our code. You should be able to find the problem by trying, and more trying, until it works! Programming is never going to itsself, you have to put some time in it!

hiddepolen 32 Posting Whiz in Training

Formulate the problem.

What do you have, what do you want, so what needs to change. Change exactly that...

hiddepolen 32 Posting Whiz in Training

OK, modified it a bit:

<html>
    <head>
        <title>Vaja 6.2</title>
        <script type="text/javascript">

            function enterSize()
                {
                x=prompt("Enter width:")
                y=prompt("Enter height:")
                
                for(var i=0; i<x; i++)
                {
                    document.write("<table id=table border=1 cellpadding=0 cellspacing=0>")
                    document.write(" <tr>")
                    
                    for (var j=0; j<y; j++)
                    {
                        document.write(" <td width=40 height=40 class='cell' id='cell" + (i*x+j) + "'>")
                        document.write(" </td>")
                    }
                    document.write(" </tr>")
                    document.write("</table>")                }

    
            }
            </script>
            <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body >
        <div><script>
            enterSize();
			for (var i=0; i<x; i++) {
				for (var j=0; j<y; j++) {
					if ((i+j) %2 == 0)
						$('#cell'+(i*x+j)).css('backgroundColor', '#0F0');
				}
			}
            </script></div>

        
    </body>
</html>

Please start thinking a little for yourself. I'm sure you could have managed to think of this yourself.

hiddepolen 32 Posting Whiz in Training

A counter is the variable in the for loop (a in the first, b in the second, c in the third).

I would suggest the following, made from your code:

for (int a=0;a <= 5; a++){
	for( int b= 0; b <= 5; b++){
		println("b = " + b);
		if(b ==5)
			println("loop terminated " + a);
	}
		
}
hiddepolen 32 Posting Whiz in Training

My suggestion:

When te button is clicked:
- disable the button.
- Make a new thread, with a while loop in it.
- Check whether the startTime - currentTime is bigger then the needed time.
- If it is, enable the button.

You should pass the button as a parameter into the thread, so you can enable it.

Any questions, please ask!

hiddepolen 32 Posting Whiz in Training

I thinking I'd use jQuery to select each square, and change the color. In your for loops you can generate IDs for your squares.

hiddepolen 32 Posting Whiz in Training

There is no 'printf()' in Java. This is C++ syntax.

Use

System.out.println("Sum is " + sum);

or

System.out.println(String.format("Sum is %f", sum));

is you want to format.

Also, be careful using (i-2)/i. i is an Integer, and (i-2)/i will always result in 0 if you don't explicitly tell Java to use it as a float (like this: ((float)i-2)/(float)i).

Changed code:

public static void main(String[] args) {
		float sum=0;
		for (int i=3; i<=99; i+=2) {
			sum += (((float)i - 2) / (float)i);
		}
		System.out.println (String.format (" sum %f\n", sum));
	}

Good luck.

hiddepolen 32 Posting Whiz in Training

With calling repaint, the GUI should call on paintComponent(Graphics g). Have you overridden that? Put a console output there to check if it is called.

hiddepolen 32 Posting Whiz in Training

What exactly is your question?

hiddepolen 32 Posting Whiz in Training

Write a small program, implementing keyListener. On the key pressed method, you print out te character.

hiddepolen 32 Posting Whiz in Training

I think it would help if you let the LinkedBinaryTree class implement Iterable<E>.
Then, you should be able to iterate in a for loop.

hiddepolen 32 Posting Whiz in Training

Great! Just keep trying: that is the only way to get 'C++ logic' :).
In some time, it will come to you, I am sure.

If I'd have to change the loop, I would do it like this:

case 1:
do {

        cout << "Please type in the student ID number\nof the student you want to search,\nthen press enter.\n";
        cin >> stdIDInput;
        cout << "\nStudent ID  Student Name         Course Code  Credit Points\n\n";
        cout << setiosflags(ios::left);
        bool found = false;
            for(j = 0; j < NUMRECS; j++)
            {
                if(stdIDInput == stdRec[j].studentID)
                {
                    found = true;
                    cout << setw(12) << stdRec[j].studentID
                         << setw(21) << stdRec[j].studentName
                         << setw(13) << stdRec[j].courseCode
                         << setw(5)  << stdRec[j].creditPoint << endl;
                }
                
            }
                if(!found)
                {
                    cout << "Not Found.\n";
                }
       cout << "Would you like to search for a another student ? Y or N.\n";
       cin >> choice;
} while (choice != 'N');
 pause ();
        break;

I made a do/while loop, so that when the user enters 1, it always searches one time. When the user enters a correct number, the user is displayed, if no users are found, the Not Found is displayed. Finally, the user is asked if he wants to search again.

hiddepolen 32 Posting Whiz in Training

Aah, I get it.

If the contents of one line are always in the same order, you can use the following:

while (myInputFile.hasNext())
         {
            strLine = myInputFile.nextLine();
            
            StringTokenizer strTokenizer = new StringTokenizer(strLine, ";");
            
StringBuilder output = new StringBuilder();
strTokenizer.nextToken();
strTokenizer.nextToken();
output.append("StationID: " + strTokenizer.nextToken()+"\n");
output.append("Name: " + strTokenizer.nextToken());
output.append("Location: " + strTokenizer.nextToken()+"\n");
strTokenizer.nextToken();
output.append("Latitude: " + strTokenizer.nextToken()+"\n");
output.append("Longitude: " + strTokenizer.nextToken()+"\n");
        
OutputFile.println(output);

         }

I think this is the best way. Try it, maybe there are other options, but I can't think of any better at the moment.

hiddepolen 32 Posting Whiz in Training

What I can see from the picture, is that you need to clear your screen on a repaint().

Two ideas:
- Call super.paint(g); in the first line of your paint method. This is the paint method of the super class, it might help.
- Call a clearRect(0,0,getWidth(), getHeight());. This clears the screen, and might do the job.

Let me know if it works.

hiddepolen 32 Posting Whiz in Training

I made a boolean, which has the value if any user has been found. If after the for() loop the value is still false, no user has been found, and the message can be displayed.

bool found = false;
for (j = 0; j < NUMRECS ; j++) {
        if (stdIDInput == stdRec[j].studentID)
        {  
found = true;
            cout << setw(12) << stdRec[j].studentID
                 << setw(21) << stdRec[j].studentName
                 << setw(13) << stdRec[j].courseCode
                 << setw(5)  << stdRec[j].creditPoint << endl;    
        }
if (!found) {
cout << "The user was not found in our database.";
}
}
C++newbie chick commented: uber-helpful! +1
hiddepolen 32 Posting Whiz in Training

Thanks, good luck!

hiddepolen 32 Posting Whiz in Training

But draw the triangle (0,0)(1,0)(2,0)! Ofcourse the area is 0, because we have three points in one line.

Use (0,0), (2,3) and (4,1) to check.

cecsFTL commented: Very helpful! +1
hiddepolen 32 Posting Whiz in Training

What are a, b and c then in the method I gave you?
If you use it like this, it should work...

public boolean isValid () {
double a = getSideAB();
double b = getSideBC();
double c = getSideCA();
return !(a+b<c || b+c<a || a+c<b || a == 0 || b == 0 || c == 0);
// return false if any of the statements are true, else return false.
}
hiddepolen 32 Posting Whiz in Training

I think you messed up the position variable in the button handler a bit. I changed the code to this, and it works:

public void actionPerformed(ActionEvent event) {
		if (event.getSource () == nextButton) {
			if (position < productArray.length - 1)
				position++;
			else
				position = 0;
		} else if (event.getSource () == firstButton) {
			position = 0;
		} else if (event.getSource () == lastButton) {
			position = productArray.length - 1;
		} else if (event.getSource () == prevButton) {
			if (position > 0)
				position--;
			else
				position = productArray.length - 1;
		}
		displayProduct ();

	}
hiddepolen 32 Posting Whiz in Training

I think it would be better to return null instead of "". That way, the rest of the methods can check easier if there was any 'real' return.

xiangzhuang commented: thansk for the reply +0
hiddepolen 32 Posting Whiz in Training

Ah, yes, I was thinking of something entirely different.
My suggestion then, should solve all the problems:

public boolean isValid () {
return !(a+b<c || b+c<a || a+c<b || a == 0 || b == 0 || c == 0);
// return false if any of the statements are true, else return false.
}
hiddepolen 32 Posting Whiz in Training

Nice program :)

The problem is the use of static. When you use static, the value of the variable is class dependent, and not object dependent.

Example:

class A {
A(int a) {
this.a = a;
}
public static int a; // Note: STATIC
}

class B {
void doSomething () {
A.a = 1;
// A.a = 1
A.a = 5;
// A.a = 5

// Note: I never created any object of A. Because of the static flag, I can just use the class.

new A(6);
// A.a  = 6
}
}
class A {
A(int a) {
this.a = a;
}
public int a; // Note: NOT STATIC
}

class B {
void doSomething () {
A a1 = new A(1);
// a1.a = 1
A a2 = new A(2);
// a1.a = 1 and a2.a = 2

// Note: Each object keeps is own values, because a is now object dependent.
}
}

Good luck!

hiddepolen 32 Posting Whiz in Training

Any three points in a 2D system should be valid. (0,0) (2,3) (4,4) is a valid triangle.
Think of some invalid points: they don't exsist, or I haven't found any :)...

hiddepolen 32 Posting Whiz in Training

One question from my side: Do you want to save 1 digit after the comma, or you you want to remove the last digit of the number?

Assuming you want to remove one digit:
- Make a string out of the double, adding
- Copy the string, but without the last character
- Copy another string, with only the last character of the first string.
- Check if the value of the single last digit is 5 or higher, and set a boolean
- If the boolean is false, use the value of the string of the second step.
- Otherwise, use the value string, and add 1 to the last digit of the double.
- Print out the generated number.

There are other options ofcourse, but this is one I have used once, it worked.

hiddepolen 32 Posting Whiz in Training

Taywin is right here. You don't want to check is a+b > c, that is valid for any triangle. You should check for a+b < c. Make sure that your isValid method includes: a+b < c, a+c < b and b+c < a. If any of them are true, you have an invalud triangle.

hiddepolen 32 Posting Whiz in Training

I understand: I actually did not know that. Ive always compaired strings like this, with no errors. I'll look into this, and sorry for the wrong answers.

hiddepolen 32 Posting Whiz in Training

OK. Say I have got an array with numbers, and I want to print it to a file. I would use this code:

class Test {
int [] myIntArray = new int [5];

public static void main (String[] args){
new Test();
}
Test () {

try {
			BufferedWriter out = new BufferedWriter (new FileWriter ("myTextFile.txt"));
                   for (int i=0; i<myIntArray.length; i++){
			out.write("");
}
			out.close ();
		} catch (FileNotFoundException e) {
			System.out.println("Error!");
		} catch (IOException e) {
			System.out.println("Error!");
		}
}
}

Just try it yourself, and integrate it in your program.

hiddepolen 32 Posting Whiz in Training

Great, the program works for me!

Can you mark this thread as solved?

hiddepolen 32 Posting Whiz in Training

I think you don't understand the concept of static, and exceptions. Those things are VERY different.

Static:
When you make a method or variable static, you call it not using a variable, but using the class it is part of.
In your case: You did not make any instance of your main class, and you just call your methods from that class.
My example:

class Test {
	
	public static void main(String[] args) {
		new Test ();
	}
	
	Test () {
		B.sayHiFromB ();
		A objectA = new A();
		objectA.sayHiFromA ();
	}
	
	private class A {
		public void sayHiFromA () {
			System.out.println ("Hi from A");
		}
	}
	private static class B {
		public static void sayHiFromB () {
			System.out.println ("Hi from B");
		}
	}
}

will output:

Hi from B
Hi from A

As you can see, I have to make an object from the A class to call the method. I don't have to make a B object, I can call it straight from the B class.

Exceptions:
An Exception is an error. Certain methods throw Exceptions, this means that an error can exsist in such a method. You should use a try/catch block surrounding the method call, to catch it:

class Test {
	
	public static void main(String[] args) {
		new Test ();
	}
	
	Test () {
		A objectA = new A();
		try {
			objectA.sayHiFromA ();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println ("Program exits.");
	}
	
	private class A …
hiddepolen 32 Posting Whiz in Training

What error are you getting?

private String save="/Users/dlaxman92/Desktop/Java /SocialPlanner2";

Two problems. You have to point to a file, not a folder. Also, the program will save to "C:/Users/dlaxman92/Desktop/Java /SocialPlanner2".

If you just use:

private String save="savedFile.txt";

It might work.

Please reply with your results.

hiddepolen 32 Posting Whiz in Training

You're right. As I said in my last post, the problem is not which IDE he uses (we could discuss for quite some time aobut that :) ), but the fact that he uses one.

Too much off-topic :)

int computer = Math.random();
computer = 3 * Math.random;

I think you forgot the () there. Try

int computer = Math.random()*3;

Also:

esle if (computer = player)

Will not work. Instead of comparing player and computer, you are assigning the value of player to computer.
Change = to ==, and spell 'else' correct.

Good luck!

hiddepolen 32 Posting Whiz in Training

A class is a collection of properties, which can be initialised into any amount of objects. An object is an instance of a class, which has all the properties defined in the class.

To use a class:

public class MyName {
private:
int myInt;
float myFloat;
bool myBool;
public:
int getMyInt();
float getMyFloat();
bool getMyBool();
void setMyInt(int i);
void setMyFloat(float f);
void setMyBool (bool b);
}
hiddepolen 32 Posting Whiz in Training

so do I only need 1 input variable now (double d) for d because d is adding them in the sum method?

Look at the method. It is not just double d, but double...d, with three dots. This means you can put any amount of variables in there, even an array. Try it yourself.
Now you can use as many variables you want to sum up, and the same way is used to call the sum method in the average method.

hiddepolen 32 Posting Whiz in Training

You should except any number of variables as input in your method, like this:

public static double sum(double... numbers)
	{
		double add_num;
                for (double d: numbers)
		add_num += d;
		return add_num;
	}
public static double average(double... numbers)
	{
		double avg_num;
		avg_num = sum(numbers)/ numbers.length;
		return avg_num;
	}
}

Also read: http://www.java-tips.org/java-se-tips/java.lang/how-to-pass-unspecified-number-of-arguments-to-a-m.html

hiddepolen 32 Posting Whiz in Training

A null pointer exception means you are trying to access a variable, which has not been initialized. The line number is also displayed with the error, so you know which variable the error is about.

Try fixing that, and if you run into trouble, ask me.

hiddepolen 32 Posting Whiz in Training

You are asking us to make en entire program for you?
Forget it ;)

If you have your entire code, but with a problem, feel free to ask me, i'll help you!
However, first give some effort, and TRY!

Good luck!

hiddepolen 32 Posting Whiz in Training

Nikki!

You dont get the idea of this forum. Do you have any idea what you're talking about when you create a program?
You have to actually know c++ a little, to do anything. It doesnt look like you do. Make your program first, compile it, test it, compile it again until it works. IF there is any ERROR that you dont understand, please feel free to ask, but dont just write down what we tell you, with "Is this OK?" next to it...

You posted exactly what you posted in your first post, which was just some arrogant words, telling US to make a program for you? Good luck man...

VernonDozier commented: Well said. +11
hiddepolen 32 Posting Whiz in Training

OK: here's the deal.
DO NOT USE GoTo, unless VERY neccesary. Usually there's no need to use it.
Why dont you look at your code, I modified it a bit:
(I like to use bools for loops, if you dont, use somthing else. Switches can also work!)

#include <iostream>
#include "Windows.h"
using namespace std;

int x,y,z;
bool b1 = true, b2 = true;


int main()
{
	while (b1) {
		cout<<"Allow me to edit registry\n";
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
		system("wait");
		cout<<"Did You Press YES?!   1 = Yes I did , 2 = No I did not!\n";
		cin>>y;
		cin.ignore();
		if (y == 1) {
			b1  = false;
		}
		else if (y == 2) {
			while (b2) {
				cout<<"Would you like to allow the program to try editing the registry again?   1 = Yes , 2 = No, Just quit\n";
				cin>>z;
				cin.ignore();
				if (z == 1){
					b1 = false;
					b2 = false;
				}
				else if (z == 2){
					return 0;
				}
				else {
					cout<<"You either pressed a number that is not on the menu, or a letter... Retry!\n";
				}
			}
		}
		else {
			cout<<"You either pressed a number that is not on the menu, or a letter... Retry!\n";
		}
	}
	cout<<"Registry Editing Finished... You pressed yes to allow the program access :)\n";

	system("pause");

	return 0;
}

You could also use switch, which makes the code look a lot nicer:

#include <iostream>
#include "Windows.h"
using namespace std;

int x,y,z;
bool b1 = true, b2 = true;


int main()
{
	while (b1) …