Quantcast
Channel: Programming Forums
Viewing all 51036 articles
Browse latest View live

Incompatible Types?

$
0
0
Every time I compile the code, I keep getting an "incompatible types" error for the emboldened section and I cannot understand why. Can someone please point out my probably very obvious error.

Scanner input = new Scanner(System.in); //creates code to use input function
        
        System.out.println("Type in the number of students there are: ");
        String strStudents = input.nextLine();
        int students;
        students = Integer.parseInt (strStudents);
        
        System.out.println("Type in the number of grades there are: ");
        String strGrades = input.nextLine();
        int grades;
        grades = Integer.parseInt (strGrades);
        
        String[][]gradebook = new String[students][grades];
        String strInput;
        
        //enters a for loop that asks for the grade and then checks to see what letter grade was received
        for (int x = 1;x <= students; x++) {
                strInput = JOptionPane.showInputDialog (null,"Type in the name for student number " + x);
                [b]gradebook[x-1] = strInput;[/b]
            }

Change color of "user" in login message

$
0
0
Hi all,

I have a login message, what intergrates a text with the user, however, I would like the username with which the user logged in with to be RED.

The username does show up, however, NOT in red :(


 Private Sub frm_main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim r As Color
        r = Color.Red


        Dim user As String
        user = frm_login.txt_username.Text



        'frm_login.txt_username.Text
        Me.ControlBox = True
        Me.Text = ""
        Me.WindowState = FormWindowState.Maximized

        lbl_main.Text = "Welcome On Board at A. Hartrodt " & user & vbCrLf & vbCrLf & " This learning platform will allow you to interactively learn about Hartrodt and all the different services that it offers worldwide. We are pleased to welcome you to Hartrodt and look forward to working hand in hand with you as we guide you though this learning experience." & vbCrLf & vbCrLf & " Along with your hard cover manual, this online platform will be crucial in proving all the necessary fundamental information to kick start your learning process"


Matlab Image Processing/Analysis help

$
0
0
This is my first time using Matlab so I'm sorry if this isn't clear enough. Thanks in advance for any reply.

I'm currently doing a project on Matlab which is due in the next 4 weeks so this is a little urgent. The project should allow a user to input 2 images and the system should then compare them for similarity. I've already made the GUI and allowed the user to input the images and the system can check if the images are the same.

I want to be able to compare how the two images are similar in terms colour, texture, patterns, quality etc.

I'm very confused about how to compare/analyse the images for similarity. If any one can point me to the right direction as to what libraries/methods I need for the project or what to do next would be perfect.

Thanks, Mo

Working on a DivCon problem...

$
0
0
So doing a problem over on SPOJ The actual problem is here

The problem is quoted below. So my current plan of attack was to throw all the points into an X Array and an Y Array, from there sort everything and then I kind of get confused on how to act on the which line is better? Any help or suggestions would be great. Thanks!

Quote

Anne and Brenda found some cookies scattered on the lattice points in the 2D coordinate system. They agreed to divide them in the following manner.

First, Anne draws a vertical line (that is, a line with the equation x = c, for any real number c) somewhere in the plane. Then Brenda draws a horizontal line (y = d) somewhere in the plane. Now they have divided the plane in four quadrants.

Anne gets all the cookies lying in the upper right and the lower left quadrant, and Brenda gets all the cookies lying in the upper left and the lower right quadrant. Cookies which lie on the vertical or the horizontal line are ignored.

Anne's goal is to maximize the number of cookies she gets, knowing that Brenda plays optimally (in order to maximize her number of cookies).

Input

In the first line of input there is an integer T (1 ≤ T ≤ 600), the number of test cases.

Each test case starts with an integer N (1 ≤ N ≤ 1000), the number of cookies. In the next N lines there are coordinates (Xi, Yi) of the cookies, integers in the interval [1, 1000]. There can be multiple cookies at the same point.

Output

For each of the T cases, output in a separate line the maximal number of cookies Anne can surely get.

Example

Input:
2
5
1 1
4 1
4 5
5 1
3 3
11
7 10
7 11
7 10
7 11
6 6
5 5
4 8
1 5
1 6
1 4
7 1

Output:
2
5

calculating state and sales tax

$
0
0
A program that will ask the user to enter the amount of a purchase. The program should then compute the state sales tax and county sales tax. Assume the state sales tax is 4% and the county sales tax is 2%. The program should display the amount of the purchase, the state sales tax, the county sales tax, the total tax, and total cost of the purchase.


 public class Source1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        double Purchaseamount= 30; 
        double Statetax = 4.00;
        double Countytax = 2.00;
        double sum, totalcost;  
        
        //Calculate total tax
        Statetax=(Statetax/100.0);
        Countytax=(Countytax/100.0); 
        sum = Statetax + Countytax;
        totalcost = Purchaseamount + sum; 

        //Display the following output
        System.out.print("Enter the Purchase amount ");
        System.out.println(Purchaseamount);
        System.out.print("Purchase amount: $");
        System.out.println(Purchaseamount);
        System.out.print("State tax: $");
        System.out.println(Statetax);
        System.out.print("County tax: $");
        System.out.println(Countytax);
        System.out.print("Total tax: $");
        System.out.println(sum);
        System.out.print("Total coast: $");
        System.out.println(totalcost);  


I'd just like to know if what i did is correct according to the assigned work.

Mars Rovers in Java

$
0
0
Hi, I am working on an question, which is provided below:

"A squad of robotic rovers are to be landed by NASA on a plateau on Mars. This plateau, which is curiously rectangular, must be navigated by the rovers so that their on-board cameras can get a complete view of the surrounding terrain to send back to Earth.
A rover's position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.
In order to control a rover, NASA sends a simple string of letters. The possible letters are 'L', 'R' and 'M'. 'L' and 'R' makes the rover spin 90 degrees left or right respectively, without moving from its current spot. 'M' means move forward one grid point, and maintain the same heading.
Assume that the square directly North from (x, y) is (x, y+1).

INPUT:
The first line of input is the upper-right coordinates of the plateau, the lower-left coordinates are assumed to be 0,0.
The rest of the input is information pertaining to the rovers that have been deployed. Each rover has two lines of input. The first line gives the rover's position, and the second line is a series of instructions telling the rover how to explore the plateau.
The position is made up of two integers and a letter separated by spaces, corresponding to the x and y co-ordinates and the rover's orientation.
Each rover will be finished sequentially, which means that the second rover won't start to move until the first one has finished moving.

OUTPUT
The output for each rover should be its final co-ordinates and heading.

TEST INPUT:
5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM

EXPECTED OUTPUT:
1 3 N
5 1 E"

My solution to the question is:

package roversonmars;

public class RoversOnMars {
    //Variables
    public int x; // rectangle vertical 
    public int y;// rectangle horizontal
    public char compassPoint; // N,E,W,S
    public static int xCoor, yCoor; // to set grids max points
    //Constructors
    public RoversOnMars(){
        x = 0;
        y = 0;
        compassPoint = 'N';
    }       
    public RoversOnMars(int x, int y, char compassPoint){
        setX(x);
        setY(y);
        this.compassPoint = compassPoint;
    }
    //Accessor methods
    public int getX(){
        return x;
    }
    public int getY(){
        return y;
    }
    public char getCompassPoint(){
        return compassPoint;
    }
    //Mututator methods
    public void setX(int x){
        this.x = x;
    }
    public void setY(int y){
        this.y = y;
    }
    public void setCompassPoint(int number){
        
        switch(number){
            case 1:
                compassPoint = 'N';
            case 2:
                compassPoint = 'S';
            case 3:
                compassPoint = 'W';
            case 4:
                compassPoint = 'E';
        }
    }
    public void CommandLetters(String command){
        for(int i=0; i<command.length(); i++){
            while(command.charAt(i) == 'L'){
               x= x-1;
               break;
            }
            while(command.charAt(i) == 'R'){
            
               x = x+1;
               break;
            }
            while(command.charAt(i) == 'M'){
                if(compassPoint == 'N'){
                    y = y+1;
                }
                else if(compassPoint == 'E'){
                    x = x -1;
                }
                else if(compassPoint == 'W'){
                    x = x+1;
                }
                else if(compassPoint == 'S'){
                    y = y-1;
                }
                break;
            }
        }
    }
    public void setPlateauCoordinate(int a, int B)/>{
        xCoor = a;
        yCoor = b;
    }
    
    public static void main(String[] args) {
       RoversOnMars rover = new RoversOnMars(1,2,'N');
       rover.setPlateauCoordinate(5, 5);
       System.out.println("Coordinates of the plateau: " + xCoor + " " + yCoor);
       System.out.println("Rover's position: " + rover.getX() + " " + rover.getY() + " " + rover.getCompassPoint());
        
       rover.CommandLetters("LMLMLMLMM");
       System.out.println(rover.getX() + " " + rover.getY() + " " + rover.getCompassPoint());
    }
}




It gives me the wrong output, I am about to freak out. :gun_bandana: :gun_bandana:
I cannot find the point that I did wrong.
I need to solve this question as early as possible.
Thanks for any help.

DLL in order program, but won't let me use head?

$
0
0
The program is supposed to allow you to insert elements into a DLL and have the list remain in order:
#include <iostream>
#include <list>
using namespace std;

template<typename T>
class DLLNode {
public:
    T info;
    DLLNode<T> *next, *prev;
    DLLNode() {
        next = prev = 0;
    }
    DLLNode(T t, DLLNode<T> *n = 0, DLLNode<T> *p = 0) {						// do not use a default value for t
        info = t;
        next = n;
        prev = p;
    }
};

template<typename T>
class DLL {
protected:
    DLLNode<T> *head, *tail;
public:
    DLL() {
        head = tail = 0;
    }
    void insertAtHead(T t) {
        head = new DLLNode<T>(t);
        if (tail == 0)
            tail = head;
        else head->next->prev = head;
    }
    T deleteFromTail() {
        //		if(head == 0)															// if the list is empty
        //			return 0;
        T t = tail->info;
        if(tail == head) {														// if there is only one node in the list
            delete tail;
            head = tail = 0;
        }
        else {
            tail = tail->prev;
            delete tail->next;
            tail->next = 0;
        }
        return t;
    }
    
    friend ostream& operator<<(ostream& out, DLL<T> dll);
};

template<typename T>
ostream& operator<<(ostream& out, DLL<T> dll) {
    for (DLLNode<T> *p = dll.head; p != 0; p = p->next)
        out << p->info << ' ';
    out << endl;
    return out;
}



here's where the problem is:
template<class T>
class MyDLL : public DLL<T> {
public:
    void addInOrder(const T&){
        DLLNode<T> newNode = new DLLNode<T>;
        DLLNode<T> *currNode = new DLLNode<T>;
        if(head = NULL) {
            head = newNode;
        }
        else {
            currNode = head;
            while(currNode->next!=NULL) {
                if(newNode == currNode) {
                    currNode->next->prev = newNode;
                    currNode->next = newNode;
                }
                if(newNode > currNode) {
                    currNode->next->prev = newNode;
                    currNode->next = newNode;
                }
                else
                    currNode = currNode->next;
             }
        }
    }
};


First of all, I don't think my method even works, secondly, it gives me the error "undeclared identifier head". Can anyone help?

C# counter

$
0
0
I am using c# , i have form register member and form dependents, on the registered member form i have combobox were i should write number of dependent, for example if i write 5 dependent when i go to form dependent i should be able to save only five dependent, i should not exceded that number. Previously i was using vb to code it hies like: count +=1 if counter > comboboxdependent.text then the MsgBox(" you are done adding your dependent") save.enabled=false end if.
I am learning c# .

What will be the code on c#. You help is highly appreciated.

Drawing Flags

$
0
0
So I have a project that is supposed to draw 3 different flags using .ppm imaging. I'm supposed to use an if/else statement to call one of three separate void functions to draw each of those flags. However, I'm receiving two errors when I compile with gcc -Wall -g. The two errors are in lines 119 and 149 respectively. In 119, "main is normally a non-static function" and in 149 "expected declaration or statement at end of input".



#include <stdio.h>

void make_pixel (int r, int g, int B)/>/>;
void make_ppm_header (int width, int height);
void ukraine_flag (int width);
void russia_flag (int width);
void ireland_flag (int width);

void make_pixel 
(
	int r, // Red intensity
	int g, // Green intensity
	int b //  Blue intensity
)
{
	fprintf (stdout, "%c%c%c", r, g, B)/>/>;
} 

void make_ppm_header (int width, int height)
{
	fprintf (stdout, "P6\n");
	fprintf	(stdout, "%d %d %d\n", width, height, 255);
}

void ukraine_flag (int width)
{
	int height = (width * 3) / 2;
	int current_Row = 1;
	int current_Col = 1;
	
	make_ppm_header (width, height);
	
	if (current_Col <= width)
	{
		if (current_Row <= (height / 2))
		{
			make_pixel (0, 91, 187);
			current_Row += 1;
		}
		if (current_Row > (height / 2))
		{
			make_pixel (255, 213, 0);
			current_Row += 1;
		}

		current_Col += 1;
	}
}

void russia_flag (int width)
{
	int height = ((width * 3) / 2);
	int current_Row = 1;
	int current_Col = 1;
	
	make_ppm_header (width, height);
	
	if (current_Col <= width)
	{
		if (current_Row  <= (height / 3))
		{
			make_pixel (255, 255, 255);
			current_Row += 1;
		}
		if (current_Row > (height / 3))  && (current_Row <= ((height * 2 ) / 3)
		{
			make_pixel (0, 57, 166);
			current_Row += 1;
		}
		if (current_Row > ((height * 2 ) / 3))  &&  (current_Row <= height)
		{
			make_pixel (213, 43, 30);
			current_Row += 1;
		}
		
		current_Col += 1;
	}
}

void ireland_flag (int width)
{
	int height = (width / 2);
	int current_Row = 1;
	int current_Col = 1;
	
	make_ppm_header (width, height);
	
	if (current_Row <= height)
	{
		if (current_Col <= (width / 3))
		{
			make_pixel (0, 155, 72);
			current_Col += 1;
		}
		if (current_Col > (width / 3))  &&  (current_Col <= ((width * 2) / 3))
		{
		
			make_pixel (255, 255, 255);
			current_Col += 1;
		}
		if (current_Col > ((width * 2) / 3))  && (current_Col <= width)
		{
			make_pixel (255, 121, 0);
			current_Col += 1; 
		}
	
		current_Row += 1;
	}
}

int main(void)
{

	int width;
	int country_code;
	
	// This block prompts the user to select which flag to draw and a width for the flag
	fprintf (stdout, "This program will draw the flag of either Ukraine, Russia, or Ireland.\n");
	fprintf	(stdout, "Please enter the number corresponding to the country whose flag you would like to draw: \n");
	fprintf	(stdout, " 0 - Ukraine\n 1 - Russia\n 2 - Ireland\n");
	fscanf	(stdin, "%i", &country_code);
	fprintf	(stdout, "You've selected to draw the flag of %i. How wide would you like your flag to be?\n", country_code);
	fscanf	(stdin, "%i", &width);

	// Creating the code to select a void function corresponding to the flag choice

	if ( country_code == 0 )
	{
		ukraine_flag (width);
	}
	if ( country_code == 1 )
	{
		russia_flag (width);
	}
	if ( country_code == 2)
	{
		ireland_flag (width);
	}

	return 0;
}		



Thanks guys!

What is wrong with my code? Will not compile output.

$
0
0
Hello everyone. I need some help, just to tweek my code if needed. At home, I have eclipse luna I believe and at school just eclipse. My program runs perfectly at home. At school does not run right. At home I get my primes and palindrome primes listed, followed by asking for input. When I input values at school, however, it does not list my primes or palindromes, just skips toato asking for input. Teacher said it is my line 9. But it runs good at home. What could it be?
import java.util.Scanner;
public class p1c {

    public static void main(String[] args) {
        final int NUMBER_OF_PRIMES_PER_LINE = 10;
        
        Scanner input = new Scanner(System.in);
        
        System.out.printf("Please enter two integer numbers: ");
        int x = input.nextInt();
        int y = input.nextInt();

        while(x <= y) {
                String primeString = "Prime: \n";
            int counter = 0;
            
            for (int i = x; i <= y; i++) {
                if(isPrime(i)) {
                    primeString = primeString + String.format("%6d", i);
                    counter++;
                    
                    if(counter % NUMBER_OF_PRIMES_PER_LINE == 0) {
                        primeString += "\n";
                        counter = 0;
                    }
                }
            }
            
            String palindromeString = "Palindromic Prime: \n";
            int pCounter = 0;
            
            for (int i = x; i <= y; i++) {
                //isPrime() function calls to check for both palindrome and if it is prime.  
                if(isPalindrome(i) && isPrime(i)) {
                    palindromeString = palindromeString + primeString+ String.format("%6d", i);
                    pCounter++;
                
                    if(pCounter % NUMBER_OF_PRIMES_PER_LINE == 0) {
                        palindromeString += "\n";
                        pCounter = 0;
                    }
                }
            }
            
            System.out.print("\n\nPlease enter two integer numbers: ");
            x = input.nextInt();
            y = input.nextInt();
        }
        
        System.out.println("\n***Done***");
      
        input.close();
    }
  
    public static boolean isPrime(int n) {
        if(n <= 1) {
            return false;
        }
        
        for (int i = 2; i <= n/2; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
  
    public static boolean isPalindrome(int n) {
        int palindrome = n;
        int reverse = 0;

        while (palindrome != 0) {
            int remainder = palindrome % 10;
            reverse = reverse * 10 + remainder;
            palindrome = palindrome / 10;
        }    
        
        if (n == reverse) {
            return true;
        }
        return false;
    }
}

Problems with Collision Detection

$
0
0
I am wanting to make an RPG game with simple collison detection.
Currently it will detect a collision has occurred but I don't know how to make it so you can move the
character again.

Any help is appreciated.

I also changed some previous code in the section to comments, because it failed to work.



 
Public Class frmName


    Private Sub frmMain_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        Dim collision As Boolean = False
        
        If picPlayer.Bounds.IntersectsWith(picMoney.Bounds) Then
            collision = True
        End If



        Dim Loc As Point
        Select Case e.KeyCode
            Case Keys.Left
                If collision = False And Not picPlayer.Location.X - 5 < 0 Then
                    Loc = New Point(picPlayer.Location.X - 5, picPlayer.Location.Y)
                    picPlayer.Location = Loc
                Else
                    If collision = True Then

                        Exit Sub
                        'Do Until collision = False
                        'Loc = New Point(picPlayer.Location.X + 5, picPlayer.Location.Y)
                        'picPlayer.Location = Loc
                        'collision = False
                        'Loop
                        'MessageBox.Show("Collison Detected!")
                    End If
                End If
            Case Keys.Right
                If collision = False And Not picPlayer.Location.X + 5 > Me.Width - picPlayer.Width - 5 Then
                    Loc = New Point(picPlayer.Location.X + 5, picPlayer.Location.Y)
                    picPlayer.Location = Loc
                Else
                    If collision = True Then
                        Exit Sub
                        'Do Until collision = False
                        'Loc = New Point(picPlayer.Location.X - 5, picPlayer.Location.Y)
                        'picPlayer.Location = Loc
                        'collision = False
                        'Loop
                        'MessageBox.Show("Collsion Detected!")
                    End If
                End If
            Case Keys.Up
                If collision = False And Not picPlayer.Location.Y - 5 < 0 Then
                    Loc = New Point(picPlayer.Location.X, picPlayer.Location.Y - 5)
                    picPlayer.Location = Loc
                Else
                    If collision = True Then
                        Exit Sub
                        'Do Until collision = False
                        'Loc = New Point(picPlayer.Location.X, picPlayer.Location.Y + 5)
                        'picPlayer.Location = Loc
                        'collision = False
                        'Loop
                        'MessageBox.Show("Collision Detected!")
                    End If
                End If
            Case Keys.Down
                If collision = False And Not picPlayer.Location.Y - 5 > Me.Height - picPlayer.Height * 1.5 Then
                    Loc = New Point(picPlayer.Location.X, picPlayer.Location.Y + 5)
                    picPlayer.Location = Loc
                Else
                    If collision = True Then
                        Exit Sub
                        'Do Until collision = False
                        'Loc = New Point(picPlayer.Location.X, picPlayer.Location.Y - 5)
                        'picPlayer.Location = Loc
                        'collision = False
                        'Loop
                        'MessageBox.Show("Collision Detected!")
                    End If
                End If



        End Select
    End Sub
End Class


Need help with 2-Dimensional array problem

$
0
0
Here is the original question:

Write a method with a void return value that sets to 0 all the elements of the even-numbered rows and sets to 1 all the elements of odd-numbered rows of a two dimensional array of ints. Include code to test your method.

I believe I have written the code write to convert this I just can't seem to get it to print now. When I run the program below I get this:

The new array with 0 at even and 1 at odd rows would be: [[I@15db9742

Seems like I'm just forgetting something simple but thanks for any help ahead of time.

public class EvenAndOdd
{
  public static void main(String[] args)
  {
  
  //Array
   int [][] array = {{3,1,13,15},{18,23,55,77}};
   
   changeArray(array);
 }
  
  //Method changes even row to 0's and odd rows to 1's
  public static void changeArray(int[][] temp)
  {
  for(int i=0; i<temp.length; i++)
  {
   for(int j=0; j<temp[i].length; j++)
   {
   if (i%2==1)
   {
    temp[i][j]=1;
   }
   else 
   {
    temp[i][j]=0;
   
   }
  }
 }
  System.out.println("The new array with 0 at even rows and 1 at odd rows would be: " + temp);
 }
}

TestTriangle Program Wont Work

$
0
0

//my triangle class

public class Triangle extends GeometricObject {

	private double side1 = 1.0;
	private double side2 = 1.0;
	private double side3 = 1.0;
	private double s = (side1 + side2 + side3) / 2;
	private String color;
	
	public Triangle() {
		
	}
	
	public Triangle(double side1, double side2, double side3) {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
	}
	
	public double getSide1() {
	    return side1;
	    }

	public double getSide2() {
	    return side2;
	    }

	public double getSide3() {
	    return side3;
	    }

	public void setSide1(double side1) {
	    this.side1 = side1;
	    }

	public void setSide2(double side2) {
	    this.side2 = side2;
	    }

	public void setSide3(double side3) {
		this.side3 = side2;
	    }
	
	public void setColor(){
		this.color = "Blue";
		}

	public String getColor(){
		setColor();
		return color;
		}
	public boolean setFilled(){
		boolean filled = true;
		return filled;
		}

	public boolean getFilled(){
		return isFilled();
		}

	@Override
	public double getArea() {
		return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
	}

	@Override
	public double getPerimeter() {
		return side1 + side2 + side3;
	}

	@Override
	public String toString() {
		return "Triangle side1=" + side1 + ", side2=" + side2 + ", side3=" + side3;
	}
	
	

}

//my test triangle class

import java.util.Scanner;

public class TestTriangle  {
    private double side1 = 1.0;
    private double side2 = 1.0;
    private double side3 = 1.0;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter three sides of the Triangle");
        double side1 = input.nextDouble();
        double side2 = input.nextDouble();
        double side3 = input.nextDouble();

        System.out.println("Enter the color of the Triangle");
        String color = input.next();

        System.out.println("Is the Triangle filled? Reply with 'True' or 'False' ");

        String filled = input.next(); 
    }
    {
    	Triangle triangle = new Triangle(side1, side2, side3);
    	

    	System.out.println("The Triangle Sides are \n side 1: " + triangle.getSide1() + "\n Side 2: " + triangle.getSide2() + "\n Side 3: " + triangle.getSide3());
    	System.out.println("The Triangle's Area is " + triangle.getArea());
    	System.out.println("The Triangle's Perimeter is " + triangle.getPerimeter());
    	System.out.println("The Triangle's Color is " + triangle.getColor());
    	System.out.println("Is the Triangle filled? " + triangle.isFilled());
    	
    }
}




View Postztm004, on 24 February 2015 - 02:11 PM, said:


//my triangle class

public class Triangle extends GeometricObject {

	private double side1 = 1.0;
	private double side2 = 1.0;
	private double side3 = 1.0;
	private double s = (side1 + side2 + side3) / 2;
	private String color;
	
	public Triangle() {
		
	}


	
	public Triangle(double side1, double side2, double side3) {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
	}
	
	public double getSide1() {
	    return side1;
	    }

	public double getSide2() {
	    return side2;
	    }

	public double getSide3() {
	    return side3;
	    }

	public void setSide1(double side1) {
	    this.side1 = side1;
	    }

	public void setSide2(double side2) {
	    this.side2 = side2;
	    }

	public void setSide3(double side3) {
		this.side3 = side2;
	    }
	
	public void setColor(){
		this.color = "Blue";
		}

	public String getColor(){
		setColor();
		return color;
		}
	public boolean setFilled(){
		boolean filled = true;
		return filled;
		}

	public boolean getFilled(){
		return isFilled();
		}

	@Override
	public double getArea() {
		return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
	}

	@Override
	public double getPerimeter() {
		return side1 + side2 + side3;
	}

	@Override
	public String toString() {
		return "Triangle side1=" + side1 + ", side2=" + side2 + ", side3=" + side3;
	}
	
	

}

//my test triangle class

import java.util.Scanner;

public class TestTriangle  {
    private double side1 = 1.0;
    private double side2 = 1.0;
    private double side3 = 1.0;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter three sides of the Triangle");
        double side1 = input.nextDouble();
        double side2 = input.nextDouble();
        double side3 = input.nextDouble();

        System.out.println("Enter the color of the Triangle");
        String color = input.next();

        System.out.println("Is the Triangle filled? Reply with 'True' or 'False' ");

        String filled = input.next(); 
    }
    {
    	Triangle triangle = new Triangle(side1, side2, side3);
    	

    	System.out.println("The Triangle Sides are \n side 1: " + triangle.getSide1() + "\n Side 2: " + triangle.getSide2() + "\n Side 3: " + triangle.getSide3());
    	System.out.println("The Triangle's Area is " + triangle.getArea());
    	System.out.println("The Triangle's Perimeter is " + triangle.getPerimeter());
    	System.out.println("The Triangle's Color is " + triangle.getColor());
    	System.out.println("Is the Triangle filled? " + triangle.isFilled());
    	
    }
}



i cant get my test program to give me the right output it asks the right questions but then when u enter them and press enter it does nothing and says terminated at the top

save a state in a program

$
0
0
Hi, I want to know if you can save state in a java program, like when you run it then stop and run it again it still has the same values stored. For example, first run of code I stored some elements in an array, then program is terminated. Next, I run the code again and the array should still have the elements I had ran previously. Its kinda like a game save. I start a game, move my character to a different spot, save then turn off. Turn on game again and my character is still there chilling, not restarting his position from where I started the game.
Can I do something like that in a java program, like do it in a simple dice game in eclipse, where the winnings I had can be carried on to when I rerun the program again, not starting from 0 everytime?

How would one go about creating an interactive calendar?

$
0
0
I came across this tutorial when I was looking up ideas on the matter, but the tutorial's code makes heavily use of a external library, which is pretty complex. However, I was looking to achieve the same result as in the screenshot, though solely on relying on the AWT and Swing internal libraries.

I was thinking of creating a JTable with a custom renderer class, though I wanted to add in JLabels or JButtons to represent the events on-screen, but I wouldn't know how to do it, since I have never added anything besides text into table cells (not to mention how to span the components through multiple rows).

I didn't know who to ask this question, so I decided to join this forum. I hope someone could help me out with this.

Form Size , off scale on different computers

$
0
0
Hi DIC,

Having a small problem here. I am creating my program in MS visual studios at work, and the screen is pretty darn small, but when I come home, I open the program and everything is stretched and not centered.

Is there a way to keep everything centered is respect to the screen size it is opened on and not the one it is created on?

im suppose to create an application for an insurance option

$
0
0
Write an application that allows the user to choose insurance options in JCheckBoxes. Use a ButtonGroupto allow the user to select only one of two insurance types – HMO (health maintenance organization) or PPO (preferred provider organization). Use regular (single) JCheckBoxes for dental insurance and vision insurance options; the user can select one option, both options, or neither option. As the user selects each option, display its name and price in a text field; the HMO costs $200 per month, the PPO costs $600 per month, the dental coverage adds $75 per month, and the vision care adds $20 per month. When a user deselects an item, make the text field blank.
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*;

 public class JInsurance extends 
JFrame implements ItemListener 
{ 
int hmoPrice = 200, ppoPrice = 800; 
int[] additPrice ={0,20,75}; int basePrice = 0, totalPrice = 
basePrice; JCheckBox hmoBox = new 
JCheckBox("HMO $" + hmoPrice, 
false); 
JCheckBox ppoBox = new 
JCheckBox("PPO $" + ppoPrice, 
false); JLabel additLabel = new JLabel 
("Additional Coverage: Make a 
selection"); 
String[] additNames = {"None $" 
+ additPrice[0], "Vision $" + 
additPrice[1], "Dental $" + additPrice[2]}; 
JComboBox additBox = new 
JComboBox(additNames); JLabel insOptionsLabel = new 
JLabel("Insurance Options:"); 
JTextField totPrice = new 
JTextField(10); 
JTextField message = new 
JTextField(30); JLabel optionExplainLabel = 
new JLabel("Base price for 
insurance with HMO $" + basePrice 
+ "."); 
JLabel optionExplainLabel2 = 
new JLabel("Optionally, you can choose HMO or PPO only"); public JInsurance() 
{ 
super("Insurance Price 
Estimator"); 
setDefaultCloseOperation 
(JFrame.EXIT_ON_CLOSE); JPanel pane = new JPanel(); 
ButtonGroup insGroup = new 
ButtonGroup(); 
insGroup.add(hmoBox); 
insGroup.add(ppoBox); 
pane.add(hmoBox); pane.add(ppoBox); 
pane.add(additLabel); 
pane.add(additBox); 
pane.add(insOptionsLabel); 
pane.add 
(optionExplainLabel); pane.add 
(optionExplainLabel2); 
pane.add(totPrice); 
pane.add(message); 
totPrice.setText("$" + 
totalPrice); hmoBox.addItemListener 
(this); 
ppoBox.addItemListener 
(this); 
additBox.addItemListener 
(this); setContentPane(pane); 
} 
public static void main(String[] 
args) 
{ 
JFrame aFrame = new JInsurance(); 
aFrame.setSize(400,250); 
aFrame.setVisible(true); 
} 
public void itemStateChanged 
(ItemEvent event) { 
Object source = 
event.getSource(); 
int select = 
event.getStateChange(); if(source == additBox) 
{ 
int addNum = 
additBox.getSelectedIndex(); 
addPrice = additPrice 
[addNum]; message.setText("Action: 
Insurance options changed $" + 
addPrice + " added"); 
} 
else 
message.setText("Action: Insurance type changed"); 
totalPrice = basePrice 
+additPrice; 
if(ppoBox.isSelected()) 
totalPrice += 
ppoPrice; else if 
(fishBox.isSelected()) 
totalPrice += 
fishPrice; } 
}


my problem is i dont know if im doing this correct. it keeps giving me error

How to load the text files in directory to the tsmi.dropdownlist

$
0
0
This is what I have so far:

Private Sub LoadFile(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	        Dim loc As String = "C:\Quiz\"
	        For Each dirs As String In Directory.GetDirectories(loc)
	            Dim dirinfo As New DirectoryInfo(dirs)
	            Quiz1.Items.Add(dirinfo.Name)
	        For Each f In New System.IO.DirectoryInfo("C:\Quiz\").GetFiles
	        Dim menuItem As New ToolStripMenuItem(f.Name)
	        MenuItem.DropDownItems.Add(menuItem)
	            Next
	            Next
	Private Sub QuizToolStripMenuItem1_Click(sender As Object, e As EventArgs, AddHandler menuItem.Click, AddressOf menuItem_Click)
	      Dim ts = DirectCast(sender, ToolStripMenuItem)
	End Sub


I get an error that I Cannot add owner item to the drop-down items collection. Not sure what to do? Suggestions please. Thank you

What is "INEXACT" in this code?

$
0
0
Hello everyone
In this following code I have a trouble in understanding the INEXACT. Is it a parameter or variable? and how it is defined later as INEXACT REAL?
Please help me to understand it, Thanks.

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

#define INEXACT

int start (REAL *pa, REAL *pb, REAL *pc, REAL *pd, REAL *pe)
{
INEXACT REAL axby1, bxcy1, cxdy1, dxey1, exay1;
INEXACT REAL bxay1, cxby1, dxcy1, exdy1, axey1;
INEXACT REAL axcy1, bxdy1, cxey1, dxay1, exby1;
INEXACT REAL cxay1, dxby1, excy1, axdy1, bxey1;
.
.
.

Help With Array

$
0
0
Hey guys. I have to make a program that reads a file and keeps track of how many of each printable character there are. I have it all down except at the end I need to display the total amount of printable characters. I don't know how to add all the array values together to get that:

//********************************************************************
//  Assignment5.java
//
//
//********************************************************************

import java.io.*; // needed for file output
import java.util.*; // needed for file input
import javax.swing.*; // needed for dialog boxes

public class Assignment5
{
   //-----------------------------------------------------------------
   //  Reads a sentence from the user and counts the number of
   //  uppercase and lowercase letters contained in it.
   //-----------------------------------------------------------------
   public static void main(String[] args) throws IOException
   {
      final int NUMCHARS = 95;


      int[] chars = new int[NUMCHARS];

      char current;   // the current character being processed

		// set up file output
		FileWriter fw = new FileWriter("output.txt"); // sets up a file for output
		BufferedWriter bw = new BufferedWriter(fw); // makes the output more efficient. We use the FileWriter (fw) created in previous line
		PrintWriter outFile = new PrintWriter(bw); // adds useful methods such as print and println
		
		// set up file for input using JFileChooser dialog box
		JFileChooser chooser = new JFileChooser(); // creates dialog box
		int status = chooser.showOpenDialog(null); // opens it up, and stores the return value in status when it closes
  
		Scanner scan;
		if(status == JFileChooser.APPROVE_OPTION)
		{
			File file = chooser.getSelectedFile();
			scan = new Scanner (file);			
		}
		else
		{
			JOptionPane.showMessageDialog(null, "No File Choosen", "Program will Halt", JOptionPane.ERROR_MESSAGE);
			outFile.close();
			return;
		}
		
      while(scan.hasNextLine())
      {
      
    	  String line = scan.nextLine();
      
      //  Count the number of each letter occurrence
      for (int ch = 0; ch < line.length(); ch++)
      {
         current = line.charAt(ch);
         chars[current-' ']++;
      }
      //  Print the results
      for (int letter=0; letter < chars.length; letter++)
      {
    	 if(chars[letter] >= 1)
    	 {
    	 outFile.print((char) (letter + ' '));
         outFile.print(": " + chars[letter]);
         outFile.println();
    	 }
      }
           
      }   
      outFile.close();
      scan.close();
   }
}

Viewing all 51036 articles
Browse latest View live




Latest Images