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

Simple Console Calculator

$
0
0
Hello everyone,
I'm trying to make a simple calculator that doesn't care about priority and only do operation linearly.
Example: 4 + 5 * 2 = 18

Here's my code so far:


static void Main(string[] args)
        {
            int i = 0;
            float res;
            int p;
            int num2 = 0;
            int num1 = 0;

            if (int.TryParse(args[1], out p))
            {res = p;} // sets the res as the first number of the operation

            while (i < args.Length) // Doing the whole length of what we enterd
            {
                switch (args[i])
                    {
                        case "+" : // If it detects a +

                        if (int.TryParse(args[i+1], out p)) // Take the next argument
                        {
                            num2 = Int32.Parse(args[i+1]); // Make it an int
                            res += num2; // Add it to res (which is the 1st argument and the total of before)
                        }
                        break;

                        case "-":

                            if (int.TryParse(args[i + 1], out p))
                            {
                                num2 = Int32.Parse(args[i + 1]);
                                res -= num2;
                            }
                            break;

                        case "*":

                            if (int.TryParse(args[i + 1], out p))
                            {
                                num2 = Int32.Parse(args[i + 1]);
                                res *= num2;
                            }
                            break;
                            
                    } i++;
            }
            Console.WriteLine(res.ToString()); // Says unassigned res
            Console.ReadLine();
        }




However when I try it with a cmd, it crashes... Any ideas ?

Thanks in advance

printing unexpected output

$
0
0
i am just learning about a++, ++a, a=a+1 .....so i write a code to understand it.
but it is printing unexpected output.

i think output should be 1 2 2 but i am getting 3 3 1.

what does it mean ?

#include<stdio.h>
#include<conio.h>
main()
{
      int i=1;
      printf("%d %d %d",i,++i,i++);
      getch();
      }



output : 3 3 1

Efficient removal of duplicates in unsorted linked list

$
0
0
I've written a method that accepts as a parameter an unsorted linked list and removes any duplicates found. The following is my code:

    public static<T> void remove(java.util.LinkedList<T> list)
    {       
        for(int i = 0; i < list.size(); i++)
        {
            for(int j = i + 1; j < list.size(); j++)
            {
                if(list.get(i).equals(list.get(j)))
                {
                    list.remove(j);
                }
            }
        }        
    }



Now, I'm wondering what is the more efficient way of doing this. If I'm not mistaken, this is O(n^2).

Thanks in advance!

trouble with If statements

$
0
0
Well I've always had some problems with this, but I can't seem to find any answers.
I'm asking for you to look at the second section of code, when I run this code and reply to "so your name is (name)?" with "yes", it runs the else instead of the if.
import java.util.Scanner;
class Learn1 {
	
	public static void main(String[] args) {
		
		double chicken = 4.14159625;
		int beef = 1;
		double pie;
		pie = chicken - beef;
		System.out.print("Hello ");
		System.out.print(pie);
		System.out.println(" Worlds!");
		
		
		System.out.println("name please!");
		Scanner name = new Scanner(System.in);
		System.out.println("so your name is " + name.nextLine() + "?");
		Scanner yesno1 = new Scanner(System.in);
		if (yesno1.nextLine() == "yes"){
		System.out.println("OK!");
		}else{
		System.out.println("ah...");
		}
	}
}


Dynamically allocate an array and find the mode.

$
0
0
This is the Question?
In statistics, the mode of a set of values is the value that occurs most often or with the greatest frequency. Write a function that accepts two arguments:
• An array of integers
• An integer that contains the size of the array
This function will determine the mode of the array. That is, it should determine which value in the array occurs most often. The mode is the value of the function should return. If the array has no mode (none of the values occur more than once), the function should return -1. (Assume the array will always contain nonnegative integers).
Demonstrate your function using a driver program that will accept from the user the number an integer containing the number of items, dynamicaly allocate an array of integers the size the user specified, prompt the user for each item in the array, calculate the mode() and then display the mode to the user.


I am able to arraing the array but don't know how to get started with finding the mode.

This is mu code so far.

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int * getIntegers(int *);
void displayIntegers(int *,int);
void sortIntegers(int *integers, int size);
int modeIntegers(int *integers, int size);
int main()
{
	int i;
	int *testIntegers = NULL;
	int numberIntegers = 0;
	testIntegers = getIntegers(&numberIntegers);
	sortIntegers(testIntegers, numberIntegers);
	displayIntegers(testIntegers,numberIntegers);	
	free (testIntegers);
	system("pause");
	return 0;
}
int *getIntegers(int *sizep)
{
	int i;
	int *myArray;
	int *iptr;
	printf("How many Integers do you want? ");
	fflush(stdout);
	scanf(" %d",sizep);
	myArray = calloc(*sizep , sizeof(int));
	/* using array notation*/
	for (i = 0; i < *sizep; i++)
	{
		printf("\tIntegers %d: ",i+1);
		fflush(stdout);
		scanf(" %d",&myArray[i]);
	}
	return myArray;
}
void displayIntegers(int *integers, int size)
{
	/* array */
	int i;
	for (i = 0; i < size; i++)
		printf("%d\n",integers[i]);
		fflush(stdout);
	}
void sortIntegers(int *integers, int size)
{
	/* Selection sort as an array */
	int inner, outer, hold;
	for (outer = 0; outer < size -1; outer++)
		for (inner = outer + 1; inner < size; inner++)
		{
			if (integers[outer] > integers[inner])
			{ // swap them
				hold = integers[outer];
				integers[outer] = integers[inner];
				integers[inner] = hold;
			}
		}
}

Dynamically allocate an array and find the mode.

$
0
0
This is the Question?
In statistics, the mode of a set of values is the value that occurs most often or with the greatest frequency. Write a function that accepts two arguments:
• An array of integers
• An integer that contains the size of the array
This function will determine the mode of the array. That is, it should determine which value in the array occurs most often. The mode is the value of the function should return. If the array has no mode (none of the values occur more than once), the function should return -1. (Assume the array will always contain nonnegative integers).
Demonstrate your function using a driver program that will accept from the user the number an integer containing the number of items, dynamicaly allocate an array of integers the size the user specified, prompt the user for each item in the array, calculate the mode() and then display the mode to the user.


I am able to arraing the array but don't know how to get started with finding the mode.

This is my code so far.


#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int * getIntegers(int *);
void displayIntegers(int *,int);
void sortIntegers(int *integers, int size);
int modeIntegers(int *integers, int size);
int main()
{
int i;
int *testIntegers = NULL;
int numberIntegers = 0;
testIntegers = getIntegers(&numberIntegers);
sortIntegers(testIntegers, numberIntegers);
displayIntegers(testIntegers,numberIntegers);
free (testIntegers);
system("pause");
return 0;
}
int *getIntegers(int *sizep)
{
int i;
int *myArray;
int *iptr;
printf("How many Integers do you want? ");
fflush(stdout);
scanf(" %d",sizep);
myArray = calloc(*sizep , sizeof(int));
/* using array notation*/
for (i = 0; i < *sizep; i++)
{
printf("\tIntegers %d: ",i+1);
fflush(stdout);
scanf(" %d",&myArray[i]);
}
return myArray;
}
void displayIntegers(int *integers, int size)
{
/* array */
int i;
for (i = 0; i < size; i++)
printf("%d\n",integers[i]);
fflush(stdout);
}
void sortIntegers(int *integers, int size)
{
/* Selection sort as an array */
int inner, outer, hold;
for (outer = 0; outer < size -1; outer++)
for (inner = outer + 1; inner < size; inner++)
{
if (integers[outer] > integers[inner])
{ // swap them
hold = integers[outer];
integers[outer] = integers[inner];
integers[inner] = hold;
}
}
}

Java Video Game Selector Errors

$
0
0
Hi,

I am currently struggling with this code i am working on and was wondering if someone could help me determine what i am doing wrong or where my mistakes are. If you could please help, I would really appreciate it. The project is a video game selector, it selects a video game out of a library for you to play and all you have to do is enter in a number and it will tell you which game to play. There are some criteria that i have mostly fulfilled, so that is why some things may be different or unnecessary. My problem is that when i ask what game system, an error comes up i cannot determine why it keeps giving me these errors, in addition to that i think my variables i am using for my cases are causing errors with the ones i am using in my scanner.

Please reply with any suggestions and any help is appreciated.

I am also using NetBeans 7.2 if that is relevant.

Here is my code:

package finalproject;
import java.util.Scanner; //import scanner
public class FinalProject {
  public static void main(String[] args) {
           
           int PC;
           PC = 1;
           int Xbox360;
           Xbox360 = 2;
           int Wii;
           Wii = 3;           //Declaring variables
           int N64; 
           N64 = 4;
           int NES;
           NES = 5;
           int SEGA;
           SEGA = 6;
           int game;
           
           
        Scanner input = new Scanner(System.in);// searching for input
        FinalProjectClass nameObject = new FinalProjectClass ();//using method from other class
        
        System.out.println("Enter Your Name Here: ");//asking user for name
        String name = input.nextLine();
        
        nameObject.name(name);//displaying the name using method
        
       Scanner GameDevice = new Scanner(System.in);
       System.out.println("What Game System are you playing? ");//asking what game system the user is playing
       System.out.println("Enter the Number corresponding to your system, Use this list to help you: "
               +"PC= 1 "
               +"Xbox360= 2 "
               +"Wii= 3 "
               +"N64= 4 "
               +"NES= 5 "
               +"SEGA= 6 ");
       
       switch (GameSystem){                    // Using switch to allow system to file through the different variables
           case 1: 
                    System.out.println("Enter a number 1-25 here: "); // asking for a number to decide what game to play
                    game = input.nextLine();
                   
                   
                   switch(game){ // selects game based on number entered and tells the user the name of the game.
                       case 1:
                           System.out.println(" You should Play the Game: Minecraft ");
                           break;
                       case 2:
                           System.out.println(" You should Play the Game: League Of Legends ");
                           break;
                       case 3:
                           System.out.println(" You should Play the Game: The Sims 3 ");
                           break;
                       case 4:
                           System.out.println(" You should Play the Game: CrossFire ");
                           break;
                       case 5:
                           System.out.println(" You should Play the Game: Left 4 Dead 2 ");
                           break;
                       case 6:
                           System.out.println(" You should Play the Game: Borderlands 2 ");
                           break;
                       case 7:
                           System.out.println(" You should Play the Game: Empire Total War ");
                           break;
                       case 9: 
                           System.out.println(" You should Play the Game: EverLong ");
                           break;
                       case 10: 
                           System.out.println(" You should Play the Game: Starcraft II ");
                           break;
                       case 11:
                           System.out.println(" You should Play the Game: Call of Duty: Modern Warfare 2 ");
                           break;
                       case 12:
                           System.out.println(" You should Play the Game: Call of Duty Modern Warfare ");
                           break;
                       case 13:
                           System.out.println(" You should Play the Game: Call of Duty Black Ops 2 ");
                           break;
                       case 14:
                           System.out.println(" You should Play the Game: Guild Wars 2 ");
                           break;
                       case 15:
                           System.out.println(" You should Play the Game: Prototype ");
                           break;
                       case 16:
                           System.out.println(" You should Play the Game: Need For Speed: Most Wanted ");
                           break;
                       case 17:
                           System.out.println(" You should Play the Game: Skyrim ");
                           break;
                       case 18:
                           System.out.println(" You should Play the Game: MoonBase Alpha ");
                           break;
                       case 19:
                           System.out.println(" You should Play the Game: World Of Tanks ");
                           break;
                       case 20:
                           System.out.println(" You should Play the Game: Sim City 3000 ");
                           break;
                       case 21:
                           System.out.println(" You should Play the Game: Bloodline Champions ");
                           break;
                       case 22:
                           System.out.println(" You should Play the Game: Zoo Tycoon ");
                           break;
                       case 23: 
                           System.out.println(" You should Play the Game: Spelunky ");
                           break;
                       case 24:
                           System.out.println(" You should Play the Game: Assasins Creed ");
                           break;
                       case 25:
                           System.out.println(" You should Play the Game: World Of Warcraft ");
                           break;}
              break;
        case 2: 
                    
                    System.out.println("Enter a number 1-21 here: ");
                    game2 = input.nextLine();
                   
                   
                   switch(game2){
                       case 1:
                           System.out.println(" You should Play the Game: Mass Effect ");
                           break;
                       case 2:
                           System.out.println(" You should Play the Game: Call of Duty 2 ");
                           break;
                       case 3:
                           System.out.println(" You should Play the Game: RockBand ");
                           break;
                       case 4:
                           System.out.println(" You should Play the Game: Need for Speed: Hot Pursuit ");
                           break;
                       case 5:
                           System.out.println(" You should Play the Game: Kameo ");
                           break;
                       case 6:
                           System.out.println(" You should Play the Game: Ghost Recon");
                           break;
                       case 7:
                           System.out.println(" You should Play the Game: Crackdown ");
                           break;
                       case 9: 
                           System.out.println(" You should Play the Game: Crackdown 2 ");
                           break;
                       case 10: 
                           System.out.println(" You should Play the Game: Oblivion");
                           break;
                       case 11:
                           System.out.println(" You should Play the Game: Call of Duty: Modern Warfare 2 ");
                           break;
                       case 12:
                           System.out.println(" You should Play the Game: Call of Duty Modern Warfare ");
                           break;
                       case 13:
                           System.out.println(" You should Play the Game: Call of Duty Black Ops 2 ");
                           break;
                       case 14:
                           System.out.println(" You should Play the Game: Halo 3 ");
                           break;
                       case 15:
                           System.out.println(" You should Play the Game: Gears of War ");
                           break;
                       case 16:
                           System.out.println(" You should Play the Game: Need For Speed: Most Wanted ");
                           break;
                       case 17:
                           System.out.println(" You should Play the Game: Skyrim ");
                           break;
                       case 18:
                           System.out.println(" You should Play the Game: Madden NFL '10 ");
                           break;
                       case 19:
                           System.out.println(" You should Play the Game: NCAA Football '08");
                           break;
                       case 20:
                           System.out.println(" You should Play the Game: NBA Live '08 ");
                           break;
                       case 21:
                           System.out.println(" You should Play the Game: BattleField 3 ");
                           break;
                       
                 break;}
        case 3:
                    System.out.println("Enter a number 1-19 here: ");
                    game3 = input.nextLine();
                   
                   
                   switch(game3){
                       case 1:
                           System.out.println(" You should Play the Game: Carnival Games ");
                           break;
                       case 2:
                           System.out.println(" You should Play the Game: Super Smash Bros. Brawl ");
                           break;
                       case 3:
                           System.out.println(" You should Play the Game: Super Swing Golf ");
                           break;
                       case 4:
                           System.out.println(" You should Play the Game: Super Mario Galaxy ");
                           break;
                       case 5:
                           System.out.println(" You should Play the Game: Super Mario Galaxy 2  ");
                           break;
                       case 6:
                           System.out.println(" You should Play the Game: MarioKart Wii");
                           break;
                       case 7:
                           System.out.println(" You should Play the Game: Family Game Night ");
                           break;
                       case 9: 
                           System.out.println(" You should Play the Game: Animal Crossing: City Folk ");
                           break;
                       case 10: 
                           System.out.println(" You should Play the Game: Mario and Sonic at the Olympic Games");
                           break;
                       case 11:
                           System.out.println(" You should Play the Game: Mario and Sonic at the Olympic Winter Games ");
                           break;
                       case 12:
                           System.out.println(" You should Play the Game: NBA Live '09 All-Play ");
                           break;
                       case 13:
                           System.out.println(" You should Play the Game: WiiPlay ");
                           break;
                       case 14:
                           System.out.println(" You should Play the Game: WiiSports");
                           break;
                       case 15:
                           System.out.println(" You should Play the Game: The Legend of Zelda: Twilight Princess ");
                           break;
                       case 16:
                           System.out.println(" You should Play the Game: The Legend of Zelda: Skyward Sword ");
                           break;
                       case 17:
                           System.out.println(" You should Play the Game: Super Mario Bros. Wii ");
                           break;
                       case 18:
                           System.out.println(" You should Play the Game: Donkey Kong Country Returns");
                           break;
                       case 19:
                           System.out.println(" You should Play the Game: Links Crossbow Training");
                           break;
                break;}
      
        case 4: 
                    
                   System.out.println("Enter a number 1-32 here: ");
                    game4 = input.nextLine();
                   
                   
                   switch(game4){
                       case 1:
                           System.out.println(" You should Play the Game: Harvest Moon 64 ");
                           break;
                       case 2:
                           System.out.println(" You should Play the Game: Super Smash Bros.");
                           break;
                       case 3:
                           System.out.println(" You should Play the Game: Mario Party 2 ");
                           break;
                       case 4:
                           System.out.println(" You should Play the Game: Quest 64")              "
                           break;
                       case 5:
                           System.out.println(" You should Play the Game: GoldenEye 007  ");
                           break;
                       case 6:
                           System.out.println(" You should Play the Game: Mariokart 64" );
                           break;
                       case 7:
                           System.out.println(" You should Play the Game: Tonic Trouble ");
                           break;
                       case 9: 
                           System.out.println(" You should Play the Game: The Legend of Zelda: Ocarina Of Time ");
                           break;
                       case 10: 
                           System.out.println(" You should Play the Game: The Legend of Zelda: Majora's Mask ");
                           break;
                       case 11:
                           System.out.println(" You should Play the Game: Mario Tennis ");
                           break;
                       case 12:
                           System.out.println(" You should Play the Game: Goemons Great Adventure ");
                           break;
                       case 13:
                           System.out.println(" You should Play the Game: Rugrats Scavenger Hunt ");
                           break;
                       case 14:
                           System.out.println(" You should Play the Game: Rainbox Six );
                           break;
                       case 15:
                           System.out.println(" You should Play the Game: Tony Hawks Pro Skater ");
                           break;
                       case 16:
                           System.out.println(" You should Play the Game: Pokemon Stadium ");
                           break;
                       case 17:
                           System.out.println(" You should Play the Game: Pokemon Stadium 2 ");
                           break;
                       case 18:
                           System.out.println(" You should Play the Game: Diddy Kong Racing");
                           break;
                       case 19:
                           System.out.println(" You should Play the Game: A Bugs Life ");
                           break;
                       case 20:
                           System.out.println(" You should Play the Game: Mega Man 64 );
                           break;
                       case 21:
                           System.out.println(" You should Play the Game: Yoshi's Story");
                           break;
                       case 22:
                           System.out.println(" You should Play the Game: Glover ");
                           break;
                       case 23:
                           System.out.println(" You should Play the Game: Ready 2 Rumble Boxing ");
                           break;
                       case 24:
                           System.out.println(" You should Play the Game: Wipeout 64");
                           break;
                       case 25:
                           System.out.println(" You should Play the Game: Extreme XG2 ");
                           break;
                       case 27:
                           System.out.println(" You should Play the Game: Banjo-Kazooie );
                           break;
                       case 28:
                           System.out.println(" You should Play the Game: Super Mario 64");
                           break;
                       case 29:
                           System.out.println(" You should Play the Game: Starfox 64 ");
                           break;
                       case 30:
                           System.out.println(" You should Play the Game: Kirby 64 The Crystal Shards ");
                           break;
                       case 31:
                           System.out.println(" You should Play the Game: Pokemon Puzzle League 64");
                           break;
                       case 32:
                           System.out.println(" You should Play the Game: Dr. Mario 64 ");
                           break;
                 break;}
        case 5:
            
                    System.out.println("Enter a number 1-10 here: ");
                    game5 = input.nextLine();
                   
                   
                   switch(game5){
                       case 1:
                           System.out.println(" You should Play the Game: Troy Aikman Football ");
                           break;
                       case 2:
                           System.out.println(" You should Play the Game: Sonic The Hedgehog ");
                           break;
                       case 3:
                           System.out.println(" You should Play the Game: College Slam ");
                           break;
                       case 4:
                           System.out.println(" You should Play the Game: Double Dribble ");
                           break;
                       case 5:
                           System.out.println(" You should Play the Game: Techmo Super Hockey ");
                           break;
                       case 6:
                           System.out.println(" You should Play the Game: Batman Forever ");
                           break;
                       case 7:
                           System.out.println(" You should Play the Game: Spider-Man ");
                           break;
                       case 9: 
                           System.out.println(" You should Play the Game: Triple Play ");
                           break;
                       case 10: 
                           System.out.println(" You should Play the Game: Zoop ");
                           break;
                       
                       break;}
           
        case 6:

                    System.out.println("Enter a number 1-10 here: ");
                    game6 = input.nextLine();
                   
                   
                   switch(game6){
                       case 1:
                           System.out.println(" You should Play the Game: StarTropics ");
                           break;
                       case 2:
                           System.out.println(" You should Play the Game: ExciteBike ");
                           break;
                       case 3:
                           System.out.println(" You should Play the Game: Prince of Persia ");
                           break;
                       case 4:
                           System.out.println(" You should Play the Game: Super Mario Bros. 2" );
                           break;
                       case 5:
                           System.out.println(" You should Play the Game: Golf ");
                           break;
                       case 6:
                           System.out.println(" You should Play the Game: Jordan v.s Bird oneon one ");
                           break;
                       case 7:
                           System.out.println(" You should Play the Game:  Super Mario Bros./ Duck Hunt");
                           break;
                       case 9: 
                           System.out.println(" You should Play the Game: Rad Racer ");
                           break;
                       case 10: 
                           System.out.println(" You should Play the Game: Teenage Mutant Ninja Turtles II: The Arcade Game ");
                           break;
             break;}
                
       }}}


This is tha class that i am using the method in

package finalproject;
class FinalProjectClass {
    public void name(String name){
        System.out.println("Hello"+  name);
}
}

vhost not working

$
0
0
hi
i am unable to define vhost on local machine.
please check below


enabled

Include conf/extra/httpd-vhosts.conf


httpd-vhosts.conf


<VirtualHost *:80>
    ServerAdmin ramesh@thegeekstuff.com
    DocumentRoot C:\wamp\www\cms
    ServerName top5freeware
	
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin ramesh@thegeekstufdf.com
    DocumentRoot C:\wamp\www
    ServerName localhost		
</VirtualHost>






hosts
127.0.0.1 localhost
127.0.0.1 top5freeware



dont no why it is not working at all i restated the appachi did evything that i know

Write data into text file

$
0
0
Hi. I have to write simple program in assembly (using tasm for compiling) which will add to numbers and save their sum into text file. I have managed to do first part, but when trying to save sum into file it won't work (operand doesn't match). Dunno what i'm doing wrong. Can someone help me or rewrite code to show me, how it should be done?
.model small
.stack 200H
.data
   msg1 DB 10,13,'Enter the first no: $'
   msg2 DB 10,13,'Enter the second no: $'
   msg3 DB 10,13,'sum = $'
   newline DB 10,13, ' $'
   file DB "C:\tasm\results.txt",00
.code
   print MACRO msg ;macro definition
   PUSH AX
   PUSH DX
   MOV AH,09H
   MOV DX,offset msg
   INT 21H
   POP DX
   POP AX
   ENDM
.startup
   print msg1
   CALL readnumtoAX
   MOV CX,AX
   print newline
   print msg2
   CALL readnumtoAX
   print newline
   print msg3
   ADD ax,cX
   CALL displayAX
   CALL saveAX
.exit
readnumtoAX PROC NEAR
   PUSH BX
   PUSH CX
   MOV CX,10
   MOV BX,00
back:
   MOV AH,01H
   INT 21H
   CMP AL,'0'
   JB skip
   CMP AL,'9'
   JA skip
   SUB AL,'0'
   PUSH AX
   MOV AX,BX
   MUL CX
   MOV BX,AX
   POP AX
   MOV AH,00
   ADD BX,AX
   JMP back
skip:
   MOV AX,BX
   POP CX
   POP BX
   RET
readnumtoAX ENDP
displayAX PROC NEAR
   PUSH DX
   PUSH CX
   PUSH BX
   PUSH AX
   MOV CX,0
   MOV BX,10
back1:
   MOV DX,0
   DIV BX
   PUSH DX
   INC CX
   OR AX,AX
   JNZ back1
back2:
   POP DX
   ADD DL,30H
   MOV AH,02H
   INT 21H
   LOOP back2
   POP AX
   POP BX
   POP CX
   POP DX
   RET
  displayAX ENDP
  saveAX PROC
	MOV AH,3D
	MOV AL,20
	MOV DX,file
	INT 21h
	MOV BX,AX
	MOV AX,4000
	MOV DX,cX
	MOV CX,0D
	INT 21H
	MOV AX,4c00
	INT 21H
	saveAX ENDP
end

from c to c++

$
0
0
please how can convert this code from C to C++



#include <stdio.h>

int main() {
    int N;
    for(;scanf("%d",&N) && N!=0;printf("%d => %d\n",N,N*N-N+1));
    return 0;
}




Basics of Page Replacement

$
0
0
Hey there,

I'm fairly certain I understand how page replacement works (and I did very well on all of this class' exams). I'm onto the programming project now and I am stuck at a bit I cannot figure out in order to start coding.

I have the following:

Page sizes: 512, 1024, and 2048 (words)
Number of frames: 4, 8, 12
List of virtual memory addresses (there is an entire .DAT file, but here are just the first few): 12 ,5635, 1933, 8087, 5850, 4798

I can't seem to figure out how many pages there are for each of the page sizes. Are there simply 16, 32, and 64 pages respectively for each page size? I've been able to figure out the number of pages, frames, and number of virtual address spaces with many other problems and variables (both for homework and tests) but for some reason my mind has put up a block against this one. I feel it has something to do with how the information has been presented to me (as it's different than it has been before).

So yea, if anyone could help me figure out the number of pages I can get this thing started on paper and hopefully have it coded before the evening is over.

I know this stuff is ridiculously easy. This brain fart just won't go away and the harder I think about it the more confused I seem to be getting. It may very well be attributed to the fact that I quit smoke a few days ago. My head is so fuzzy!

2^(32-9)=2^23 ..which is the number of entries for a page size of 512.



This is the assignment; however, I don't yet need help on anything but this as I've just started:

Quote

Problem 2: Virtual Memory management problem
Compare the performance of the following page replacement algorithms: FIFO, LRU (Least recently used), MRU (most recently used), and optimal. You will be provided with a file containing the virtual addresses that are being referenced by a single program (a process). Run your program with the following parameters:
Page size: 512, 1024, 2048 (words)
Number of frames allocated to the process: 4, 8, 12
(So you will have 9 runs, with each page size and number of frames combination. Each run contains statistics for each of the four page replacement algorithms.
You must collect and print the following statistics
Page Size #of pages Page replacement ALG Page fault percentage
Your report must show a summary of runs and your conclusions.

Im having issues coding css

$
0
0
HI all, so first of all the following code works, it pulls out cars from a database and displays it on a table on my website. The problem I am having
is formatting the table with css code I want to be able to change the table background. change the font size and color of Car Size and Image and other minor things.
any help is appreciated

/*note i am linking successfully to my external css sheet */

<?php

mysql_connect("localhost","user","blah") or die(mysql_error());// connect to the database
  mysql_select_db("blah") or die(mysql_error()); // select database
$query = mysql_query("SELECT * FROM cars where carType = 'ford' AND active = 1")  or die(mysql_error());

echo "<div id = 'tabledbs'>";
echo"<table border cellpadding = 3>";

if(mysql_num_rows($query) > 0){
echo"<tr><th>Car Name</th>                                                                                                     
<th>Image</th</tr>";
   while($row = mysql_fetch_array($query)){

/* Displays contents from database */
echo"<tr><td>" .$row['name'] . "</td>                                                                                              
<td><img src='".$row['imagePath'] ."'width='160' height='130'/></td></tr>";
echo "</div>";
   }
}else{

   echo "There are no cars to be displayed in the website;

}

?>



this is my attempt on my external css file

#tabledbs{background_color:black}
//would also like to change font size,colors,etc


Unable to properly Implement KeyListener class

$
0
0
Hello everyone,

I am new to the site, and also to programming. I have been watching some tutorials and trying to research best i can on the java language for about a week, and believed i was getting the hang out of it. While making a 2d platformer I somehow got stuck on player movement, something i thought i understood well. I apologize for taking up time as i understand this is something that is very basic, and i assure you I have tried everything I can think of, and would be really appreciative if anyone would be able to tell me what I am doing wrong.

I am using 3 seperate classes total to create player's movement.

the main class "Component"

package me.Mac.Advent_Ture;


import java.applet.Applet;
import java.awt.*;
import javax.swing.JFrame;






public class Component extends Applet implements Runnable 
{
    public static boolean isMoving = false;

    private final long serialVersionUID = 1L; //compilation things
    private  static int pixelSize = 1; //has to be above the pixel dimension line
    
    
    public static double dir = 0;
    


    public static Dimension size = new Dimension(800,600); // game size
    public static Dimension pixel = new Dimension(size.width/pixelSize,size.height/pixelSize); //size of each pixel
    public static String name = "Advent Ture!";   //game title
    public static boolean isRunning = false;  //when true game will run
    public static Level level; // creates level
    public static double sX= 0,sY=0;
    public static Character character;
    
    
    
    
    
    //images
    
        private Image screen;
    
    //ints
    
  
        
        
    //Strings
    
    //booleans
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    public Component()
    {
        
        setPreferredSize(size);
        
        addKeyListener(new Listening());
        
        
        
        //allows keys to be read and used(calls Listening class)
    }
    
    public void start()
    {
       
        //Define objects
        new Tile(); //loading images
        level = new Level(); //calls Level Method
        character = new Character(Tile.tileSize,Tile.tileSize * 3); // size width and height of char
        
        
        //GameStart
        isRunning = true; // starts game loop
        new Thread(this).start();
    }
    
    public void stop()
    {
        isRunning = false;  // stops game
    }
    
    public static void main(String args[])
            
    {
        
        Component component = new Component();
        
        JFrame frame = new JFrame();
        frame.add(component); //adding component to frame
        frame.pack(); //setting the same size as the components on the frame
        frame.setResizable(true);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setTitle(name);
        frame.setFocusable(true);
        frame.requestFocus();
        
        
        
        
        component.start();
        
    }
    
    
    public void tick()     //moves enimeies and player
    {
        
      level.tick();
      character.tick();
      
    }
    
    public void render()   //draw on screen
    {
     Graphics g = screen.getGraphics();
     
     // draw shit
     g.setColor(Color.blue); //cane make your own with g.setColor(new Color.r,g,B)/>;
     g.fillRect(0, 0, pixel.width, pixel.height);
     
     //rendering
     level.render(g);
     character.render(g);
     
     g = getGraphics();
     
     g.drawImage(screen,0,0,size.width,size.height,0,0,pixel.width,pixel.height,null);
     
     g.dispose(); // disposes object after use
    }
    
    
    
    
    
    public void run()
    {
        screen = createVolatileImage(pixel.width,pixel.height); //loaded onto Graphics card ie less lag
        
        while(isRunning)
        {
            tick(); //tick before render
            render();
            
            
            try
            {
               Thread.sleep(5); 
            }catch(Exception e){}
        }
    }

    
    
}



the character class

package me.Mac.Advent_Ture;

import java.awt.*;



public class Character extends DoubleRectangle
{
    public double movementSpeed = 1.0;
    public double fallingSpeed = 1.3;
    
    
    
    
    
    
    
    
    
    public Character(int width, int height)
    
            
    {
        setBounds((Component.pixel.width/2)-(width/2),(Component.pixel.height/2)-(height/2),width,height);
        
    }
    
    public void tick()
            
   {
      
       
       
        if(!isCollidingWithBlock(new Point ((int)x,(int)(y + height)),new Point((int) (x+width), (int) (y + height))))
                {
                    
                y += fallingSpeed;
        Component.sY += fallingSpeed;
                }
        
        if(Component.isMoving)
        {
            x +=Component.dir;
            Component.sX += Component.dir;
            
        }
    }
    
    
    
    public boolean isCollidingWithBlock(Point pt1,Point pt2)
    {
        
        for(int x=(int) (this.x/Tile.tileSize);x<(int)(this.x/Tile.tileSize) + 3;x++) //hotbox width
        {
            for(int y=(int) (this.y/Tile.tileSize);y<(int)(this.y/Tile.tileSize) + 4;y++) //hitbox height
            {
                if(x >=0 && y >= 0 && x<Component.level.block.length && y< Component.level.block[0].length) {
                    if(Component.level.block[x][y].id != Tile.air)
                    {
                    if(Component.level.block[x][y].contains(pt1) || Component.level.block[x][y].contains(pt2))  //collision detection
                    {
                    return true;
               
                    }
                }
                }
            }
           
        }
        return false;
        
    }     
       

    public void render(Graphics g)                                                          //place in the arry(tileset) that the character is in
    {
        g.drawImage(Tile.tileset_char,(int)x-(int)Component.sX,(int)y-(int)Component.sY,(int)(x + width)-(int)Component.sX,(int)(y + height)-(int)Component.sY, Tile.character[0] * Tile.tileSize, Tile.character[1] * Tile.tileSize,Tile.character[0] * Tile.tileSize + (int)width, Tile.character[1] * Tile.tileSize + (int)height, null);
        
    }
 


}



and the Listening class, which has the keyListener in it

package me.Mac.Advent_Ture;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Listening implements KeyListener {
    
    public static int key;
    
    
    

    @Override
    public void keyTyped(KeyEvent ke) {
        
    }

    @Override
    public void keyPressed(KeyEvent ke) {
       key = ke.getKeyCode();
        
        switch(key)
        {
            case KeyEvent.VK_RIGHT:
                Component.isMoving = true;
                Component.dir = Component.character.movementSpeed;
                System.out.println("Right");
                 break;
                
            case KeyEvent.VK_LEFT:
                Component.isMoving = true;
                Component.dir = -Component.character.movementSpeed;
                System.out.println("Left");
                 break;
        }
    }

    @Override
    public void keyReleased(KeyEvent ke) {
        key = ke.getKeyCode();
        
        switch(key)
        {
            case KeyEvent.VK_RIGHT:
                if(Component.dir == Component.character.movementSpeed)
                {
                Component.isMoving = false;
                
                }
        break;
             case KeyEvent.VK_LEFT:
                if(Component.dir == -Component.character.movementSpeed)
                {
                Component.isMoving = false;
                }
                 break;
        }
    }
    
}




I apologize if the code is messy, as I previously said I am very new to this, also I have been trying a bunch of things for the past to days to try to solve it myself. I was able to get the player to move if I changed the if(Component.isMoving) to if(!Component.Moving) which is making me believe that the KeyListener is not working at all. I am using NetBeans and going off of a tutorial on youtube. I have paused that tutorial countless times to check my code vs theirs and everything seems the same except for things I have changed but know why.

I have also tried eliminating the Listening class and implementing the KeyListener in the Character and Component classes, but with no success. I understand it is probably something simple and stupid I am missing, but i have looked around and played with this code to the best of my abilities, and also to my wits end.

If anything else is needed from me to solve this please let me know, and thank you very much in advance.

MikeMac

Problem Calling Function Twice At The Same Time

$
0
0
Hello There,

I am currently making a game using Qt and C++. In the game I have a small function called MoveTo and this function moves an NPC to a specified location. This works perfectly fine. However, If two NPC's try and use the MoveTo function at one time, one will wait for the other to finish the function which can be very annoying when game making.

Is there another way around calling the same function multiple times at the same time?
I have already tried Threading but the performance takes too big of a hit especially on my crappy dev pc.

Thanks in Advanced Guys,
Matt

Having trouble with comparison of MergeSort and BubbleSort

$
0
0
Hey everyone! First time here!

As the title suggests, I'm having trouble making a comparison between a slow sort, specifically MergeSort, and a faster sort, specifically BubbleSort. According to the professor, the output is supposed to be:

The seed to use is: 39

Bubble sort had 25349145 swaps

The first 10 values: 0 0 0 3 3 6 6 7 7 9

The last 10 values: 9991 9991 9991 9992 9992 9994 9997 9997 9998 9998



Merge sort had 133616 moves

The first 10 values: 0 0 0 3 3 6 6 7 7 9

The last 10 values: 9991 9991 9991 9992 9992 9994 9997 9997 9998 9998

But that's not exactly what I'm getting. Here's my code:

#include <stdlib.h>
#include <random>
#include <iostream>
using namespace std;
typedef int DataType;

void bubbleSort(DataType[], int);
void swap(DataType&, DataType&);
void mergeSort(DataType[], int, int);
void merge(DataType[], int, int, int);
void radix(DataType[], int, int, int);

const int SIZE = 10000;
int count = 0;

int main()
{
int seed = 39;
int theArray[SIZE];
srand(seed);
    for(int i = 0; i < SIZE; i++)
    {
    theArray[i] = rand() % SIZE;
    }

bubbleSort(theArray,SIZE);

cout << "The seed value is: " << seed << endl;
cout << "Bubble Sort had " << count << " swaps." << endl;
cout << "The first 10 values are: ";
for (int i = 0; i < 10; i++)
{

cout << theArray[i] << " ";
}
cout << "\nThe last 10 values are: ";
for (int i = SIZE-10; i < (SIZE); i++)
{
    cout << theArray[i] << " ";
}
cout << "\n" << endl;

mergeSort(theArray,0,SIZE-1);

cout << "Merge Sort had " << count << " swaps." << endl;
cout << "The first 10 values are: ";
for (int i = 0; i < 10; i++)
{
    cout << theArray[i] << " ";
}

cout << "\nThe last 10 values are: ";
for (int i = SIZE-10; i < (SIZE); i++)
{
    cout << theArray[i] << " ";
}

cout << "\n" << endl;

system("PAUSE");
return 0;
}

void bubbleSort(DataType theArray[], int n)
{
bool sorted = false;
for(int pass = 1; (pass < n) && !sorted; ++pass)
{
    sorted = true;
    for (int index = 0; index < n-pass; ++index)
    {
        int nextIndex = index+1;
        if(theArray[index] > theArray[nextIndex])
        {
            swap(theArray[index],theArray[nextIndex]);
            count++;
            sorted = false;
        }
    }
}
}

void swap(DataType& x, DataType& y){
DataType temp = x;
x = y;
y = temp;
}

void mergeSort(DataType theArray[], int first, int last)
{
    if(first < last)
    {
        int mid=((first+last)/2);
        mergeSort(theArray, first, mid);
        mergeSort(theArray, mid+1, last);
        merge(theArray, first, mid, last);
    }
}

void merge(DataType theArray[], int first, int mid, int last){
DataType tempArray[SIZE];
int first1 = first;
int last1 = mid;
int first2 = mid+1;
int last2 = last;
int index = first1;

for(; (first1<=last1) && (first2<=last2); ++index){
if(theArray[first1] < theArray[first2]){
tempArray[index] = theArray[first1];
++first1;
}
else{
tempArray[index] = theArray[first2];
++first2;
}
}
for(; first1 <= last1; ++first1, ++index){
tempArray[index] = theArray[first];
}
for(; first2 <= last2; ++first2, ++index){
tempArray[index] = theArray[first2];
}
for(index = first; index <= last; ++index){
theArray[index] = tempArray[index];
}
}



Any input would be greatly appreciated! :)/>

Linked List with PNode

$
0
0
I am trying to implement a linked list that defines a PNode class. The data field of PNode points to a Person object, and the link field points to the next PNode in the list. The user enters in a name and age, and said information is added to the end of the list. Finally, ug the pointer start I want to print out the name and age of the oldest person. Here is what I have, minus the final print statement. Any idea where I have gone wrong with this?

public class Person {

		  private String name;
		  private int age;

		  public Person(String name) {
			setName(name);
		  }

		  public int getAge() {
			return age;
		  }

		  public String getName() {
			return name;
		  }

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

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

}





import java.util.Scanner;


public class PNode {
	private Person object;
	private PNode next;
	

	public PNode(Person person, Object object) {
		
	}

	public static void main(String[] args) {
		  
		  System.out.println("Please enter a person's name and age");
		  Scanner scanner = new Scanner(System.in);
		  
		  PNode start, tail, next;
		  start = null;
		  
		  String name = scanner.next();
		  
		  if (!name.equalsIgnoreCase("DONE")) {
			  start = new PNode(new Person(name), null);
			  tail = start;
			  
			  while (true) {
				  name = scanner.next();
				  if (name.equalsIgnoreCase("DONE")) break;
				  next = new PNode(new Person(name), null);
				  tail.setNext(next);
				  tail = next;
			  }
		  }
	  }

	private void setNext(PNode next) {
		this.next = next;
		
	}
	class LinkedList {
		  public LinkedList() {
		    header = new ListNode(null);
		  }

		  public boolean isEmpty() {
		    return header.next == null;
		  }

		  public void makeEmpty() {
		    header.next = null;
		  }

		  public LinkedListIterator zeroth() {
		    return new LinkedListIterator(header);
		  }

		  public LinkedListIterator first() {
		    return new LinkedListIterator(header.next);
		  }

		  public void insert(Object x, LinkedListIterator p) {
		    if (p != null && p.current != null)
		      p.current.next = new ListNode(x, p.current.next);
		  }

		  public LinkedListIterator find(Object x) {
		    ListNode itr = header.next;

		    while (itr != null && !itr.element.equals(x))
		      itr = itr.next;

		    return new LinkedListIterator(itr);
		  }

		  public LinkedListIterator findPrevious(Object x) {
		    ListNode itr = header;

		    while (itr.next != null && !itr.next.element.equals(x))
		      itr = itr.next;

		    return new LinkedListIterator(itr);
		  }

		  public void remove(Object x) {
		    LinkedListIterator p = findPrevious(x);

		    if (p.current.next != null)
		      p.current.next = p.current.next.next; 
		  }

		  private ListNode header;

		}

		class LinkedListIterator {
		  LinkedListIterator(ListNode theNode) {
		    current = theNode;
		  }

		  public boolean isValid() {
		    return current != null;
		  }

		  public Object retrieve() {
		    return isValid() ? current.element : null;
		  }

		  public void advance() {
		    if (isValid())
		      current = current.next;
		  }

		  ListNode current;
		}

		class ListNode {
		  public ListNode(Object theElement) {
		    this(theElement, null);
		  }

		  public ListNode(Object theElement, ListNode n) {
		    element = theElement;
		    next = n;
		  }

		  public Object element;

		  public ListNode next;
		}

}




Sorry, the variable start points to the first node.

Error Messages

$
0
0
I don't understand what i am doing wrong.

I am getting the following error messages:
invalid conversion from `const char*' to `char'
missing template arguments before '.' token

I am making a inventory program for computers, Using Computer name, model number and serial number.

#include <iostream>
#include <string>
#include <vector>

using namespace std;
string name;
string model;
string serialNumber;
string inventory;
string vectorOne;
string vectorTwo;
bool flag = 0;

int main()
{
  vector < string > vectorOne;
  inventory.push_back("Asus");
  inventory.push_back("324689");
  inventory.push_back("25F36T88C45Y");
  cout << "\n\n";

  vectorTwo < string > vectorTwo;
  inventory.push_back("Asus");
  inventory.push_back("354791");
  inventory.push_back("4GR25BK6854K");
  cout << "\n\n";

  cout << "Inventory is:" << endl;
  for (long index = 0; index < (long)vectorOne.size(); ++index)
    cout << vectorOne.at(index) << " ";

  vectorTwo.erase(vector.begin() + 0);
  vectorTwo.insert(vector.begin(), Asus);
  vectorTwo.erase(vector.begin() + 1);
  vectorTwo.insert(vector.begin(), 568712);
  vectorTwo.erase(vector.begin() + 2);
  vectorTwo.insert(vector.begin(), 58H5RV897J12);

  cout << "Inventory is:" << endl;
  for (long index = 0; index < (long)vectorTwo.size(); ++index)
    cout << vectorTwo.at(index) << " ";

  int temp;
  cin >> temp;
}

how can convert this code from C to C++ because i don't have any i

$
0
0
mmm no i'm not IT person i wanna just make a small comparison between two codes and i spend a lot of time to study this is code i know its very easy but i need it please


#include <stdio.h>

int main() {
    int N;
    for(;scanf("%d",&N) && N!=0;printf("%d => %d\n",N,N*N-N+1));
    return 0;
}


"Navigation to the webpage was canceled" webbrowser error

$
0
0
Okay, so i fixed my error that i posted about in another thread, but now i'm having a new error.
Whenever i try to make the webbrowser redirect, i keep getting the error of "Navigation to the webpage was canceled" showing up in the browser. I don't even have Webbrowser.Navigating event in my code so i don't know what could be causing this error. I read around and saw that disabling your firewall can fix this error, so i tried that. However, it didn't fix the error. I also tried using "ipconfig /flushdns" in the shell, but that also didn't work.

Can anybody help?

Here's what happens to shorten up the first part:
- The browser it told to navigate to a url
- The browser returns a navigation canceled error
- When it tries to redirect to another locationon the same server, it can't so it just says "This program cannot display the webpage"

Notes:
- I know the links are valid because i tested them in chrome with no issues
- I know the webbrowser can still navigate because i made a debug button that when pressed just has it navigate to google.
- I've disabled firewall and flushed my dns with no luck.

[C] Dynamic array of structs or pointers?

$
0
0
Hi DIC, I just have a quick question, and I might follow it up with a more involved problem with code later.
Note: I'm referring to character arrays as strings here, for simplicity.

I want to make a dynamic array of structs, but currently when I use realloc (and especially when realloc moves the code block), the data inside my structs (fixed length strings that only get modified with strcpy, to add to the confusion)gets pretty mangled, looking very similar to strings that have overwritten their null terminator.

Can this be avoided if I make the dynamic array point to strings instead?

Can I malloc the strings inside the structs, as well as the array? This sounds like a nightmare, but would be incredibly helpful.

Alternatively, what is the best way to make a dynamic array of structs, specifically those including strings?
Viewing all 51036 articles
Browse latest View live




Latest Images