• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

It seems every language has a bunch of poor design decisions. I'm not even sure what is considered the closest to a perfect language. Though java is nice to ease into OOP. I know we have enough language already, but I would like to see a new master race program come along that is developed by a whole bunch of universities and companies.

Part of the issue is that there are so many different philosophies and idioms that are represented by different languages that quite often it's impossible to objectively decide that one approach is better than another.

A lot of Lisp hackers would tell you that we already created the perfect programming language and we did it in 1958. Others would say that that many parentheses can't be the right way to do anything. Some people insist that C is all you need and all this other cruft is just jank on top of that pure imperative paradigm. Most of the rest of us recognise that sometimes you need more abstraction and god damn it nobody wants to implement their own stack every time they need one. A lot of programmers now only know OOP in the Java/C# vein, and all they recognise are classes and inheritance, which drastically limits how you can think and program at all. Still others swear by higher levels of abstraction again and you get your Python or Ruby fans claiming the one true way to do anything, but dynamic typing and flexible interpreters can have all kinds of downsides in terms of correctness and scale with larger projects. Then you get to the more functional paradigms (although yeah Lisp fits that as well ofc) and you get Haskell or ML or Erlang or whatever and everything is persistant data structures, referential transparency, lambda calculus out the whazoo. That model is so fundamentally different from the Turing machine approach that even implementing a stack in Haskell can actually a painful excercise, but expressing infinitely recursing lists of elaborate function mappings is a one liner.

Sorry bit of a rant there but I guess the point is that there's never going to be something like you described because people can't even agree on which model of computation to go with most of the time (I didn't even mention logic programming above), never mind specific language features. I just think it's really important for everyone to get as much exposure to as many languages as possible so that they can recognise when their language/approach of choice is suitable and when it isn't, so many people are straitjacketed by what they know well that they end up picking the wrong tool for the job over and over.

Spoiler, Lisp wins, you can define your own paradigm :p

I actually prefer Python most of the time.
 

injurai

Banned
Part of the issue is that there are so many different philosophies and idioms that are represented by different languages that quite often it's impossible to objectively decide that one approach is better than another.

A lot of Lisp hackers would tell you that we already created the perfect programming language and we did it in 1958. Others would say that that many parentheses can't be the right way to do anything. Some people insist that C is all you need and all this other cruft is just jank on top of that pure imperative paradigm. Most of the rest of us recognise that sometimes you need more abstraction and god damn it nobody wants to implement their own stack every time they need one. A lot of programmers now only know OOP in the Java/C# vein, and all they recognise are classes and inheritance, which drastically limits how you can think and program at all. Still others swear by higher levels of abstraction again and you get your Python or Ruby fans claiming the one true way to do anything, but dynamic typing and flexible interpreters can have all kinds of downsides in terms of correctness and scale with larger projects. Then you get to the more functional paradigms (although yeah Lisp fits that as well ofc) and you get Haskell or ML or Erlang or whatever and everything is persistant data structures, referential transparency, lambda calculus out the whazoo. That model is so fundamentally different from the Turing machine approach that even implementing a stack in Haskell can actually a painful excercise, but expressing infinitely recursing lists of elaborate function mappings is a one liner.

Sorry bit of a rant there but I guess the point is that there's never going to be something like you described because people can't even agree on which model of computation to go with most of the time (I didn't even mention logic programming above), never mind specific language features. I just think it's really important for everyone to get as much exposure to as many languages as possible so that they can recognise when their language/approach of choice is suitable and when it isn't, so many people are straitjacketed by what they know well that they end up picking the wrong tool for the job over and over.

Spoiler, Lisp wins, you can define your own paradigm :p

I actually prefer Python most of the time.

Haha so true. What I personally thing we need is a language that takes the top languages of different paradigms. Creates a uniform syntax that they all seemingly conform to, the basically have a whole bunch of redundant functions. Now normally you wouldn't want redundancy but here me out. Similiar to how OOP you are working with classes, or objects or interface. All similiar but unique. It would basically be like declaring a paradigm type. This would then allow you to break out into a new paradigm to write whatever the component that you need is.

I know often times languages will be used in conjuncture, with maybe python making calls to them. But I feel eventually we need to have a single compiled API that works within different paradigms.

Sort of how you decouple dependencies and get dynamic types in OOP languages, it would be decoupling paradigms.
 
FLEX QUESTION but I guess the principle would be same for any language...
I don't think I'll get an answer but I have this dataGrid I have to sort by user input. I also have this tree structure that sorts out the same grid.

For example, the treestructure is as follow example (sorry I am really bad at analogies but I can't really paste the code either :( ):

CASE 1 (sorting with the tree structure)

Code:
level 1: PIZZA KEBAB HAMBURGER

you select PIZZA it opens the next level:

level 2: PINEAPPLE HAM CHEESE

you select cheese and you get level 3

LEVEL 3: CHEDDAR EDAM EMMENTAL

And on the grid you see all the Pizzas that contain Cheese.
CASE 2 (sorting with the text):
Code:
Use types "CHEESE" and it will show all the Pizzas, Kebabs and Hamburgers that contain Cheese. 

Of course you can now pick "PIZZA" and it will show you only the Pizzas that contain cheese which results in same products as in Case 1.


Now here's my problem: I can't sort out the items UNLESS I have some LEVEL 1 thing selected. I just doesn't do anything. For example:

I type out CHEESE. Nothing happens. I click Pizza and now it correctly shows all the Pizzas that contain cheese.


The list of products is in an ArrayCollection and if I do trace(pizzakebabburgerArrayCollection.toString()) at any point it correctly lists all of the visible items in the said grid.




Sure the sorting with text and the tree is quite confusing IMO, but that is how the customer wants it.
 
Learning to write fucking horrible code?

Yeah, sounds like most CompSci 1 classes, to be honest. When I taught Java, we taught it properly. :p

Let's just say it's a pretty horrible fucking class... Way too hard for newbies and way to easy for the people in the same course who has programmed before.
 

iapetus

Scary Euro Man
That's exactly what I needed! Thank you so much. Is the (3000) in Thread.sleep the time in milliseconds or something like that?

Yes.

You know when I said "Fucking horrible code"? That's exactly what I meant. :)

Firstly it won't do what you want it to (won't shut down after 20 seconds, for reasons that should be obvious - you should be able to fix that, though). Secondly:

Code:
  try {
    Thread.sleep(3000)
  } catch (Exception ex) {}

is an abomination. This should be something more like:

Code:
try {
    Thread.sleep(3000);
} catch (InterruptedException ie) {
    ie.printStackTrace();
}

Never catch exceptions that are overly general. It's horrible, horrible practice. And never simply ignore an exception. Even if you are going to ignore an exception, at the very least have a comment in the code to explain why you are committing this crime against nature.
 
Yes.

You know when I said "Fucking horrible code"? That's exactly what I meant. :)

Firstly it won't do what you want it to (won't shut down after 20 seconds, for reasons that should be obvious - you should be able to fix that, though). Secondly:

Code:
  try {
    Thread.sleep(3000)
  } catch (Exception ex) {}

is an abomination. This should be something more like:

Code:
try {
    Thread.sleep(3000);
} catch (InterruptedException ie) {
    ie.printStackTrace();
}

Never catch exceptions that are overly general. It's horrible, horrible practice. And never simply ignore an exception. Even if you are going to ignore an exception, at the very least have a comment in the code to explain why you are committing this crime against nature.

We ended upp with this:

Code:
public class Uppgift1_76
{
	public static void main(String [] args) throws InterruptedException
	{
		int time = 0; //int får värdet 0
		while (time < 20)
    {
      if (time == 18) 
      {
        Thread.sleep(2000);
      }
      
      else
      {
        Thread.sleep(3000);
      }
      System.out.println(3);
			

			time += 3;
	}

}
 
Code:
import java.io.*;
import java.util.Scanner;

public class Uppgift1_62 {

    public static void main(String args[]) throws Exception {

    	Scanner scanner = new Scanner(System.in);
    	FileOutputStream FOS = new FileOutputStream("textfil.txt");
    	OutputStream outputStream = new FileOutputStream("textfil.txt");
    	Writer writer= new OutputStreamWriter(outputStream);
    	System.out.println("Skriv vad du vill! Huehuehuehue.");
    	char a = scanner.next().charAt(0);
    	outputStream.write(a);

        FileInputStream input1 = new FileInputStream("textfil.txt");
    	Reader reader = new InputStreamReader(input1);	
    	int data = reader.read();
    	System.out.println((char) data);
    	FOS.close();
    	writer.close();
    	reader.close();
    	scanner.close();
    	
    		
    		
    }
  

}

In this code I want the program to make a file which contains the input from the user. The problem is that "char a = scanner.next().charAt(0);" only saves the first letter in that is written. Is there another line I can use to make this shit work?
 

Minamu

Member
I'm still having problems with multithreading :( My tutor realized that because I had found an already optimized code that shift around elements in an array instead of making new arrays, converting it to threads is very difficult. This is my current code and if you run it with the same main as in my previous post, you'll see that the threads never wait for each other and even continue to post their Console.WriteLines after the program has run its course:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadedSort
{
	public class QuickSort
	{
		public int[] MyArray = new int[10];
		public int tempElements;
		private int numThreads = 0;
		private int maxThreads = 4;
		private Object lockObject = new Object();

		public void QuickSorter()
		{
			sort(0, tempElements - 1);
		}

		public void sort(int left, int right)
		{
			int pivot;
			int leftSide;
			int rightSide;

			leftSide = left;
			rightSide = right;
			pivot = MyArray[left];

			//The first loop through all this place number 1 and 2 in element 0 and 1.
			while (left < right)
			{
				while ((MyArray[right] >= pivot) && (left < right))
				{
					right--;
				}

				if (left != right)
				{
					MyArray[left] = MyArray[right];
					left++;
				}

				while ((MyArray[left] <= pivot) && (left < right))
				{
					left++;
				}

				if (left != right)
				{
					MyArray[right] = MyArray[left];
					right--;
				}
			}

			MyArray[left] = pivot;
			pivot = left;
			left = leftSide;
			right = rightSide;

			if (left < pivot)
			{
				if(numThreads < maxThreads)
				{
					lock (lockObject)
					{
						numThreads++;
						//A new thread is started and is given startSort so it knows of the remaining elements to sort, iirc.
						Thread myThread = new Thread(new ParameterizedThreadStart(startSort));
						myThread.Start(new SortParameters(this, left, pivot - 1));
						/*test1 is printed twice before the sorted list is even printed on the screen, I don't know why. Sometimes even in the middle of the sorted list!*/
						Console.WriteLine("test1");
					}
				}

				//else
				//{
				//    sort(left, pivot - 1);
				//    Console.WriteLine("test2");
				//}
			}

			/*For some reason, test3 below is printed four times after all the code in main() is finished O_o*/
			if (right > pivot)
			{
				sort(pivot + 1, right);
				Console.WriteLine("test3");
				//Thread.Sleep(100);
			}
		}

		static void startSort(Object obj)
		{
			SortParameters sortParam = (SortParameters)obj;
			sortParam.instance.sort(sortParam.left, sortParam.right);
		}

		public class SortParameters
		{
			public QuickSort instance;
			public int left;
			public int right;

			public SortParameters(QuickSort instance, int left, int right)
			{
				this.instance = instance;
				this.left = left;
				this.right = right;
			}
		}
	}
}
So it seems that some part of the code isn't waiting around for the other which is screwing up the array so it never becomes correctly sorted (for some reason I get two 8's even though the unsorted list only has one and the 3 disappears). I'm aware that the code is recursive and very hard to grasp, I have no idea what's going on either xD It can probably be done a lot smoother.

Edit: I seem to be getting one of three results: The correct sorted list, two 8's with one acting as a 3, or 8 and 3 are in the wrong places. It's always these numbers that make a fuss. With Thread.Sleep(1000); everything seems to go away but my tutor wouldn't allow that.
 

mike23

Member
I haven't looked too closely, but it could be that you need to wait for the threads to finish. The fact that the extra sleep makes it work could be because it allows all the threads to finish before looking at the results. Take a look at Thread.Join()

Also, this is mostly just a preference thing, but if you're using .NET 4.0, take a look at the Task class.
 

Minamu

Member
I think so too. I couldn't figure out how to add it, or where. My tutor suggested that was the problem too (all the sortedparameters code etc is his). I think I use 4.0 yeah, I'll look into it!
 

Gaaraz

Member
Hi guys, just after an opinion if that's okay, I'm currently working as a PHP developer, but due to a huge restructure of the organisation the role my colleague and I do is being 'deleted'.

There's only one more 'suitable' role there we can go to, doing mostly C# .NET and Sharepoint. I have very little experience of either, working on just one project of each in the past, I really enjoyed C#, but found Sharepoint to be a bit of a nightmare though it was an odd project to work on, anyhow I'd be grateful for any advice regarding my options...

1) Take voluntary redundancy (£8k) and carry on in my job (can go until 31st March) in the hope I find a new job elsewhere, doing PHP

2) Hold out for the job doing the Windows stuff, cross my fingers and hope I get the job

3) Make life easier for everyone involved and go for a slightly lower paid job, doing more content type things and front end HTML/CSS rather than back end development

I'm much more worried about having a job I'll enjoy and find rewarding than I am money, so don't want to just grab the £8k redundancy and leave them. Would really, really appreciate any guidance :) Thanks GAF!
 

usea

Member
Hi guys, just after an opinion if that's okay, I'm currently working as a PHP developer, but due to a huge restructure of the organisation the role my colleague and I do is being 'deleted'.

There's only one more 'suitable' role there we can go to, doing mostly C# .NET and Sharepoint. I have very little experience of either, working on just one project of each in the past, I really enjoyed C#, but found Sharepoint to be a bit of a nightmare though it was an odd project to work on, anyhow I'd be grateful for any advice regarding my options...

1) Take voluntary redundancy (£8k) and carry on in my job (can go until 31st March) in the hope I find a new job elsewhere, doing PHP

2) Hold out for the job doing the Windows stuff, cross my fingers and hope I get the job

3) Make life easier for everyone involved and go for a slightly lower paid job, doing more content type things and front end HTML/CSS rather than back end development

I'm much more worried about having a job I'll enjoy and find rewarding than I am money, so don't want to just grab the £8k redundancy and leave them. Would really, really appreciate any guidance :) Thanks GAF!
I do C# and I love it. I think the libraries are great and the syntax is excellent. I have luckily managed to avoid doing anything relating to sharepoint, though; can't speak to it.

Your worst option is to take a lower paying job doing front end stuff, unless you want to give up programming. Good programmers are in demand, you don't need to take a lower paying job.

You should try to get more information before you make a decision. Try to find a new job and also try to get the C# job internally. If you get both, then choose. If you only get one, your decision is made for you. I'm guessing you won't have much trouble finding another position outside of your company though.
 

Roquentin

Member
Hi guys, just after an opinion if that's okay, I'm currently working as a PHP developer, but due to a huge restructure of the organisation the role my colleague and I do is being 'deleted'.

There's only one more 'suitable' role there we can go to, doing mostly C# .NET and Sharepoint. I have very little experience of either, working on just one project of each in the past, I really enjoyed C#, but found Sharepoint to be a bit of a nightmare though it was an odd project to work on, anyhow I'd be grateful for any advice regarding my options...

1) Take voluntary redundancy (£8k) and carry on in my job (can go until 31st March) in the hope I find a new job elsewhere, doing PHP

2) Hold out for the job doing the Windows stuff, cross my fingers and hope I get the job

3) Make life easier for everyone involved and go for a slightly lower paid job, doing more content type things and front end HTML/CSS rather than back end development

I'm much more worried about having a job I'll enjoy and find rewarding than I am money, so don't want to just grab the £8k redundancy and leave them. Would really, really appreciate any guidance :) Thanks GAF!
If you can, go for C#. I don't know anything about SharePoint, but it's a great opportunity to get some C# experience and you should use it. If SharePoint is indeed bad, down the road and with some experience you could look for another job in C#.

I made a huge mistake in my career and moved from C# to PHP. I regret it every time I think about it.
 
Learning to write fucking horrible code?

Yeah, sounds like most CompSci 1 classes, to be honest. When I taught Java, we taught it properly. :p

Fair enough, when I learned about the java wait method I was pretty upset because no one ever wanted to teach us that.

Code:
import java.io.*;
import java.util.Scanner;

public class Uppgift1_62 {

    public static void main(String args[]) throws Exception {

    	Scanner scanner = new Scanner(System.in);
    	FileOutputStream FOS = new FileOutputStream("textfil.txt");
    	OutputStream outputStream = new FileOutputStream("textfil.txt");
    	Writer writer= new OutputStreamWriter(outputStream);
    	System.out.println("Skriv vad du vill! Huehuehuehue.");
    	char a = scanner.next().charAt(0);
    	outputStream.write(a);

        FileInputStream input1 = new FileInputStream("textfil.txt");
    	Reader reader = new InputStreamReader(input1);	
    	int data = reader.read();
    	System.out.println((char) data);
    	FOS.close();
    	writer.close();
    	reader.close();
    	scanner.close();
    	
    		
    		
    }
  

}

In this code I want the program to make a file which contains the input from the user. The problem is that "char a = scanner.next().charAt(0);" only saves the first letter in that is written. Is there another line I can use to make this shit work?

Well charAt() takes the index and since you are passing 0 of course its only going to take the first letter. I'm fairly certain that something like String a = "hello world!" out.write(a); will do it, no need to try and loop through a string and write each char.
 

Ya no

Member
Hey GAF I'm trying to write a basic shell script using sed to search a file for a word then find the next occurrence of a another word and print that line.

Example:

ABANDONER

random text random text
random text random text

defn: Someone who abandons.



What I'm looking for is to have it find the word ABANDONER, then look for the next line that begins with defn: and print it. Would that be possible using sed? I read an article that had a similar example and tried:

sed '/ABANDONER/,/defn:/' dict.txt

The article said this:

"Minimalist. In address ranges with /regex/ as <address2>, the range "/foo/,/bar/" will stop at the first "bar" it finds, provided that "bar" occurs on a line below "foo". If the word "bar" occurs on several lines below the word "foo", the range will match all the lines from the first "foo" up to the first "bar". It will not continue hopping ahead to find more "bar"s. In other words, address ranges are not "greedy," like regular expressions."

The file I have is a huge dictionary file and right now I'm just looking for a way to search it in the way I described so I can work from there. Any help/suggestions greatly appreciated. If what I'm looking for isn't possible with sed I can try to use awk. (I'm in a intro to shell scripting class)
 
Hi. Just started programming (learning C#). Doing my first Forms application. I want the application to populate the array using information from text boxes (using a different form each time) but I think the application is trying to take information from all forms at once and gives me a "NullReferenceException was unhandled" error.

This is probably really easy to rectify and I'm just being dumb. Can anyone help?

Code:
//Add a new passenger to the dataGridView
        private void buttonAddPassenger_Click(object sender, EventArgs e)
        {
            int seatNum = Int32.Parse(this.textSeatNo.Text);
            if (seatNum >= numberOfSeats) //validate the seatNo
            {
                MessageBox.Show("The seat number must be in the range of 1 to " + numberOfSeats);
            }
            else
            {
                int RowIndex=0;
                //search for the array index of the seat with seatNo = seatNum
                for (int i = 0; i < numberOfSeats; i++)
                {
                    if (SeatArray[i].SeatNo == seatNum)
                    {
                        RowIndex = i;
                        break;
                    }
                }
                
                SeatArray[RowIndex].SeatAssign = this.checkBoxFirstClass.Checked;
                
                frm2.EconPass1.Text = frm2.EconPass1.Text;
                SeatArray[RowIndex].PassName = frm2.EconPass1.Text;
              

                //If I add the following and try to get information from more than one form, I get the NullReferenceException was unhandled error
               
                frm3.EconPass2.Text = frm3.EconPass2.Text;
                SeatArray[RowIndex].PassName = frm3.EconPass2.Text;
                frm3.EconPass3.Text = frm3.EconPass3.Text;
                SeatArray[RowIndex + 1].PassName = frm3.EconPass3.Text;


                frm4.EconPass4.Text = frm4.EconPass4.Text;
                SeatArray[RowIndex].PassName = frm4.EconPass4.Text;
                frm4.EconPass5.Text = frm4.EconPass5.Text;
                SeatArray[RowIndex + 1].PassName = frm4.EconPass5.Text;
                frm4.EconPass6.Text = frm4.EconPass6.Text;
                SeatArray[RowIndex + 2].PassName = frm4.EconPass6.Text;
                

                dataGridView1.Refresh();
            }
 
I made a huge mistake in my career and moved from C# to PHP. I regret it every time I think about it.

This is confusing me. Do you mean that you now literally can't get anyone to consider you for an alternate job that involves a different language? How does working in PHP now impair you from working in whatever other language you would prefer or at least applying for positions that will let you?
 
So thanks to your feedback and some other help we finally solved the cases! Although now I am on a totally new case and I don't even know where to start.

They want us to create a program that uses the method min (no idea what this is) to recieve two integers and return the smaller of those two. Then they want us to make another method that takes the other method's place and recieves two floats and return the smaller of them. Then they want us to make the method main take two integers and decide which one of them is the smaller by calling the method min. Then they want us to repeat the same thing with two floats and show all the results.

Do you even know what I am saying because I sure as hell don't. :/
 
So thanks to your feedback and some other help we finally solved the cases! Although now I am on a totally new case and I don't even know where to start.

They want us to create a program that uses the method min (no idea what this is) to recieve two integers and return the smaller of those two. Then they want us to make another method that takes the other method's place and recieves two floats and return the smaller of them. Then they want us to make the method main take two integers and decide which one of them is the smaller by calling the method min. Then they want us to repeat the same thing with two floats and show all the results.

Do you even know what I am saying because I sure as hell don't. :/

Java documentation is your friend. The math objects min methods will make this easy. Just throw in a scanner to collect the integers and floats in the main call the min methods on them and output it.
 

Gaaraz

Member
Thank you both so so much for the responses guys - I think you're right with regards to the lower paid front end/content job - it'd be a real dead end. It's a shame because there are a lot of positives, mostly it's super convenient to get to (I purposely bought a house less than 5 minutes from my current job) and I'd be working with people I got on really well with there, but it'd be a real bad move career wise. Like I said, not in it for the money, but I don't think it'd be a particularly challenging/rewarding job.

I made a huge mistake in my career and moved from C# to PHP. I regret it every time I think about it.
This in particular stood out for me - what makes you say this Roquentin? Sorry to hear that btw.
 

mike23

Member
Hi. Just started programming (learning C#). Doing my first Forms application. I want the application to populate the array using information from text boxes (using a different form each time) but I think the application is trying to take information from all forms at once and gives me a "NullReferenceException was unhandled" error.

This is probably really easy to rectify and I'm just being dumb. Can anyone help?

Code:
//Add a new passenger to the dataGridView
        private void buttonAddPassenger_Click(object sender, EventArgs e)
        {
            int seatNum = Int32.Parse(this.textSeatNo.Text);
            if (seatNum >= numberOfSeats) //validate the seatNo
            {
                MessageBox.Show("The seat number must be in the range of 1 to " + numberOfSeats);
            }
            else
            {
                int RowIndex=0;
                //search for the array index of the seat with seatNo = seatNum
                for (int i = 0; i < numberOfSeats; i++)
                {
                    if (SeatArray[i].SeatNo == seatNum)
                    {
                        RowIndex = i;
                        break;
                    }
                }
                
                SeatArray[RowIndex].SeatAssign = this.checkBoxFirstClass.Checked;
                
                frm2.EconPass1.Text = frm2.EconPass1.Text;
                SeatArray[RowIndex].PassName = frm2.EconPass1.Text;
              

                //If I add the following and try to get information from more than one form, I get the NullReferenceException was unhandled error
               
                frm3.EconPass2.Text = frm3.EconPass2.Text;
                SeatArray[RowIndex].PassName = frm3.EconPass2.Text;
                frm3.EconPass3.Text = frm3.EconPass3.Text;
                SeatArray[RowIndex + 1].PassName = frm3.EconPass3.Text;


                frm4.EconPass4.Text = frm4.EconPass4.Text;
                SeatArray[RowIndex].PassName = frm4.EconPass4.Text;
                frm4.EconPass5.Text = frm4.EconPass5.Text;
                SeatArray[RowIndex + 1].PassName = frm4.EconPass5.Text;
                frm4.EconPass6.Text = frm4.EconPass6.Text;
                SeatArray[RowIndex + 2].PassName = frm4.EconPass6.Text;
                

                dataGridView1.Refresh();
            }

Where do you initialize the values in SeatArray?

You should have SeatArray[x] = new Seat(); somewhere in your code.

If you just have Seat[] SeatArray = new Seat[100]; it just fills the array with null values which might be causing your NullReferenceException

If you're using Visual Studio, use the debugger to step through the method and see exactly when the exception occurs and which value is unexpectedly null.

Put a break point at the first line (int seatNum = Int32.Parse(this.textSeatNo.Text);)
then run the program and click the button. It should bring you back into visual studio. Then hit F10 to go line by line until something bad happens.
 

usea

Member
The exception stack trace will say which line it occurs on, fwiw.

But it's probably this line:
Code:
SeatArray[RowIndex + 1].PassName = frm3.EconPass3.Text;

Like mike23 said, SeatArray probably isn't filled with actual objects for some reason. Even if you fix the error though, something tells me the code won't be doing what you're trying to make it do. What did you mean by "I want the application to populate the array using information from text boxes (using a different form each time)"? What does 'each time' mean? Do you want the button to do something different each time you click it? Or do you want it to do multiple things on a single click? The latter is the way you have it coded right now.
 

Roquentin

Member
This is confusing me. Do you mean that you now literally can't get anyone to consider you for an alternate job that involves a different language? How does working in PHP now impair you from working in whatever other language you would prefer or at least applying for positions that will let you?
I don't have a lot of commercial experience in C# and the last one was almost 6 years ago. But the biggest problem is that I just haven't used C# and .Net in a long time, because PHP was more suitable for my personal projects. Getting back to C# would take a while, I might do it at some point, but currently I'm trying to get back to C++.

This in particular stood out for me - what makes you say this Roquentin? Sorry to hear that btw.
C# is a better designed technology and you can make much more money in it than in PHP.
 
The exception stack trace will say which line it occurs on, fwiw.

But it's probably this line:
Code:
SeatArray[RowIndex + 1].PassName = frm3.EconPass3.Text;

Like mike23 said, SeatArray probably isn't filled with actual objects for some reason. Even if you fix the error though, something tells me the code won't be doing what you're trying to make it do. What did you mean by "I want the application to populate the array using information from text boxes (using a different form each time)"? What does 'each time' mean? Do you want the button to do something different each time you click it? Or do you want it to do multiple things on a single click? The latter is the way you have it coded right now.

Thanks for the replies guys.

I have separate forms with separate text boxes, but each time I press the 'Add Passenger' button, I want it to fill the array of 200 seats with the passenger names from the particular form I filled out.

Basically, if I want to add 2 passengers, the program will show the form with two separate name fields (text boxes). I will then fill in the text boxes and click the 'Add Passenger' button. This works when the program only has code to take textbox data from one form, like so:

Code:
frm2.EconPass1.Text = frm2.EconPass1.Text;
SeatArray[RowIndex].PassName = frm2.EconPass1.Text;

But as soon as I add the code (I'm sure this is where I'm going wrong) to take textbox data from the other forms, it gives me the "NullReferenceException was unhandled" error and points to one of the newly added lines of code, like you mentioned usea.

Code:
                frm2.EconPass1.Text = frm2.EconPass1.Text;
                SeatArray[RowIndex].PassName = frm2.EconPass1.Text;
              

                //If I add the following, I get the NullReferenceException was unhandled error
                frm3.EconPass2.Text = frm3.EconPass2.Text;
                SeatArray[RowIndex].PassName = frm3.EconPass2.Text;
                frm3.EconPass3.Text = frm3.EconPass3.Text;
                SeatArray[RowIndex + 1].PassName = frm3.EconPass3.Text;


                frm4.EconPass4.Text = frm4.EconPass4.Text;
                SeatArray[RowIndex].PassName = frm4.EconPass4.Text;
                frm4.EconPass5.Text = frm4.EconPass5.Text;
                SeatArray[RowIndex + 1].PassName = frm4.EconPass5.Text;
                frm4.EconPass6.Text = frm4.EconPass6.Text;
                SeatArray[RowIndex + 2].PassName = frm4.EconPass6.Text;


This is how I initialize values in SeatArray

Code:
namespace SeatApp1
{
    public partial class Form1 : Form
    {
        //array to store all the Seat objects
        static int numberOfSeats = 200;
        Seat[] SeatArray = new Seat[numberOfSeats];

        //algorithm to bind datagrid to an array
        private CurrencyManager currencyManager = null;



        public Form1()
        {
            InitializeComponent();
        }

       
        

        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < numberOfSeats; i++)
            {
                //initialize the array with numberOfSeats Seat object
                SeatArray[i] = new Seat(i + 1);
            }

            //binding the datagrid to the array
            currencyManager = (CurrencyManager)dataGridView1.BindingContext[SeatArray];
            dataGridView1.DataSource = SeatArray;
        }

Thanks for your help guys. I'm seeing my tutor tomorrow, so if I can't find a solution by then, I'll let you know.


mike23 said:
You should have SeatArray[x] = new Seat(); somewhere in your code.

Do I not have that in the for loop above?
 

CrankyJay

Banned
I don't have a lot of commercial experience in C# and the last one was almost 6 years ago. But the biggest problem is that I just haven't used C# and .Net in a long time, because PHP was more suitable for my personal projects. Getting back to C# would take a while, I might do it at some point, but currently I'm trying to get back to C++.


C# is a better designed technology and you can make much more money in it than in PHP.

It shouldn't take you that long to get back on your feet with C#...once you have the fundamentals down of any programming you should be able to jump from one language to another fairly easily.
 

Gaaraz

Member
Yeah, having delved into different languages lately I'm amazed at how much easier they are to pick up now I have a decent knowledge of PHP, though the MVC stuff lets me down occasionally :(

My situation has changed a little now, 3 options still:

1) Ride it out at work, and go for the .NET/C#/Sharepoint job, the one guy who has experience in that has been told he 100% has a job, which makes sense, so it's 2 people into 1 job, I'd say I have almost exactly a 50/50 chance of it.

2) Go for another job available somewhere else as a PHP developer, slightly more money than the job above, and working for the same company as my best friend

3) Go for the really easy content job that still pays well, is working with really nice people but suddenly now doesn't seem very tempting at all when compared with the two above... ^_^

(option #2 would have the added benefit of around £8k redundancy if I decided before Monday! but to be honest, I'm much more worried about the job than the money)
 
So thanks to your feedback and some other help we finally solved the cases! Although now I am on a totally new case and I don't even know where to start.

They want us to create a program that uses the method min (no idea what this is) to recieve two integers and return the smaller of those two. Then they want us to make another method that takes the other method's place and recieves two floats and return the smaller of them. Then they want us to make the method main take two integers and decide which one of them is the smaller by calling the method min. Then they want us to repeat the same thing with two floats and show all the results.

Do you even know what I am saying because I sure as hell don't. :/

are you supposed to use an existing method or make your own? it reads to me like make your own eg:

Code:
public int min(int a, int b)
{
...stuff...
    return smallest;
}

then for part two you overload it by creating a new method with the same name but different signature:

Code:
public float min(float a, float b)
{
..stuff..
   return smallest;
}

call both of them by min(a, b); the program will determine at runtime which method to use depending on the types of a and b.

eg:

Code:
public static void main()
{
      ... get some int a and int b from the user
      int smallestInt = min(a, b);

      ... get some float a and float b from the user
     float smallestFloat = min(a,b);

     ... print out smallestInt and smallestFloat
}

i'm assuming this because if it's an intro to comp. sci using java they'll be wanting to teach you overloading.
 

Slavik81

Member
Just checking in to say that I've been down in Santa Clara for the Qt Developer Days. Man, is this place cool. Walking by offices labeled 'Cisco', 'Broadcom', 'McAfee', 'Intel', 'Netflix'. Back home, all the big buildings belong to oil companies.

The Qt conference itself has been pretty exciting too. Qt5 will definitely a big improvement. Especially the C++ and QML tools it provides for the development of OpenGL-rendered user interfaces.

Now to figure out what to do for the next couple days. I couldn't get a flight back until Sunday afternoon, so I'm going to be scoping out the city. After breakfast, I think I'm going to check out the Intel museum.
 
Writing unit tests on a Saturday is heaven on earth, am I right or am I right?

Coffee in hand... Michael Jackson/Madonna blend playlist playing (worlds collide)... good times.
 
Programming gaf do you have some cool x86 Assembly resources links you guys want to share. Xmas vacation is coming soon that means 2 weeks of freedom and no internship so i am looking for something to do.
 

SolKane

Member
Anyone familiar with Tkinter in Python? I have a simple issue which I'm having a problem with:

Code:
from tkinter import *
import p2
recordList = [...]

root = Tk()
subroot = Toplevel(root)
x = p2.MainInterface(subroot)
for listItem in recordList:
    x.addRecord(listItem)
root.mainloop()

So I have a class I defined which has a basic UI for entering records into a database. I'm writing a script that will just create an instance of it, call a member function and add records. That works fine, but I want to kill that window immediately after execution of the for loop. I've tried using destroy() to no effect. I just want the following: create a Toplevel widget and then kill that Toplevel so only the main Tk window is left running.
 

leroidys

Member
Does anyone have a good source for learning Java for someone who already knows java syntax (via C) and other programming languages? I'm thinking specifically stuff like methods, object oriented programming, how to write "good" java programs, specific pitfalls, etc.
 
I'm personally just glad I don't work weekends.

This was voluntary and I was working from home. Just getting caught up on correcting some poor design and writing some (lots of) tests to cover it.

Does anyone have a good source for learning Java for someone who already knows java syntax (via C) and other programming languages? I'm thinking specifically stuff like methods, object oriented programming, how to write "good" java programs, specific pitfalls, etc.

Head First Java and then into Effective Java should probably work well for you. If you're not fully confident in your OOP design skills, think about resources that cover OOP, design patterns*, etc. Head First is also good there (they go for a quirky presentation, but the material is actually pretty good), but also Gang of Four, Robert C. Martin, etc. Lots of good resources.

---

*I always feel the need to accompany the mention of "design patterns" with the cautionary note "don't become a slave to them and thinking in terms of what pattern to use instead of what problem to solve." I have found resources on patterns help introduce and sharpen design skills, but actual pattern usage in your code is better when it emerges almost completely on its own. Short version: don't be that guy that's always asking others "what pattern should I use here?" Shorter version: Especially don't be that "Singleton!" guy.
 

MNC

Member
Got a bit of a problem with sqlite in android

http://stackoverflow.com/questions/...-through-a-joined-table-with-multiple-results

Here's my question; a bit easier formatting than posting the text on gaf.

I have 3 tables, `USER`, `ENTRY` (for entered products, not necessary to create a PRODUCT table), and `USER_COLLECTION`, which is a table inbetween `USER` and `ENTRY`, because an entry can have multiple users.

Basically:

User = `USERID | USER_NAME`

Entry = `ENTRYID | ENTRY_NAME | ENTRYPRICE | ENTRY_DATE`

Collection = `COLLECTIONID | ENTRYID | USERID`

I have a table with users that persist throughout the project. They can create entries (which is usually some kind of product with a price) and they can link multiple users to a certain entry (which can be selected from a list, hence the users persist throughout the project).

So for instance, my tables look like this:

User
--------------------------
user_id | user_name
--------------------------
1 | 'FOO'
2 | 'BAR'
3 | 'FOOBAR'


ENTRY
-----------------------------------------------------------------------
entryid | entry_name | entry_price | entry_date
-----------------------------------------------------------------------
0 | 'Banana' | 2.50 | 12/12/2012


COLLECTION
---------------------------------------
collectionid | entryid | userid
----------------------------------------
0 | 1 | 1
1 | 1 | 2
0 | 1 | 3

I have a Banana, with a price of 2.50 and 3 users linked to it, Foo, Bar and Foobar.

Now, I want to use this in my app and get the data; except I don't know where to start. I tried selecting the entry data, using that id to loop through the collection data, but that would mean I have two cursors open and it wouldn't work. Tried creating a join but I couldn't really make a good one, mainly because:


JOIN
---------------------------------------
collectionid | entryname | username
----------------------------------------
0 | Banana | FOO
1 | Banana | BAR
0 | Banana | FOOBAR

I can't iterate through this, because I would create multiple of the same entry objects in my Android code...

Hope I'm being clear on this.
 

gcubed

Member
i just started learning PERL (scripting i guess, not technically programming). Its becoming pretty valuable in my field (network engineering) and coming from a c++ background, good lord is it quick to write.

My nemesis though... regex. Any good documentation to help with regex knowledge or is just basically trudge through it and learn by pain?
 
Got a bit of a problem with sqlite in android

http://stackoverflow.com/questions/...-through-a-joined-table-with-multiple-results

Here's my question; a bit easier formatting than posting the text on gaf.

I know nothing at all about Android development so there could well be an ORM based approach or something you should use instead but the obvious thing to do is fetch the entry_id as well as entry_name for the banana. Then you can use a dicitonary or something to map new objects into to make sure you only create one instance of the object for each instance in the DB.

So you would get:

Code:
---------------------------------------
collectionid | entryid | entryname | username
----------------------------------------
0 | 1 | Banana | FOO
1 | 1 | Banana | BAR
0 | 1 | Banana | FOOBAR

As you go to create new bananas, look up the id in the map to see if it exists. If it does just return that object rather than create a new one.
 

usea

Member
i just started learning PERL (scripting i guess, not technically programming). Its becoming pretty valuable in my field (network engineering) and coming from a c++ background, good lord is it quick to write.

My nemesis though... regex. Any good documentation to help with regex knowledge or is just basically trudge through it and learn by pain?
I learned through trudging, but I'm sure there's good tutorials out there somewhere.

Programming in Perl is definitely programming. Don't let anybody tell you different.
 

iapetus

Scary Euro Man
I know nothing at all about Android development so there could well be an ORM based approach or something you should use instead but the obvious thing to do is fetch the entry_id as well as entry_name for the banana. Then you can use a dicitonary or something to map new objects into to make sure you only create one instance of the object for each instance in the DB.

So you would get:

Code:
---------------------------------------
collectionid | entryid | entryname | username
----------------------------------------
0 | 1 | Banana | FOO
1 | 1 | Banana | BAR
0 | 1 | Banana | FOOBAR

As you go to create new bananas, look up the id in the map to see if it exists. If it does just return that object rather than create a new one.

You don't even have to do that; as long as your returned value is ordered by entryId, you can just iterate through the results, and only create a new item when the entryId changes.
 
Top Bottom