• 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

This is not a programming question, but I'm assuming one of you has to be able to answer this. For the "Product of Sums" part, why is ~B + ~C not an essential prime implicant? Can't it only be covered by the 2x2? The 0 I am looking at which makes it essential is the top-right in the 2x2 square.

What makes you think its not essential? That and ~b + ~d look essential to me.
 
I need some help with getting this copy paste function to work (FLEX)

I am trying to copy paste from mx:DataGrid to an Excel file. This sample I found on the web works with newer versions of Flex with s:DataGrid in place:

Code:
			private function copyToClipboard(e:Event):void {
			e.preventDefault();
			Clipboard.generalClipboard.clear();
			Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, dataGridSelectionText("\t", "\n"));
			
			}

Code:
            private function dataGridSelectionText(fieldSeparator:String, rowSeparator:String):String
            {
                const columns:IList = dataGrid.columns;
                const dataProvider:IList = dataGrid.dataProvider;
                
                var rowIndex:int = -1;
                var text:String = "";
                
                for each (var cp:CellPosition in dataGrid.selectedCells)
                {
                    if ((rowIndex != -1) && (cp.rowIndex != rowIndex))
                        text += rowSeparator;
                    else if (rowIndex != -1)
                        text += fieldSeparator;
                    rowIndex = cp.rowIndex;
                    
                    var column:GridColumn = columns.getItemAt(cp.columnIndex) as GridColumn;
                    var value:Object = dataProvider.getItemAt(rowIndex)[column.dataField];
                    text += exportText(value, column);
                }
                return text;                
            }


			public function exportText(item:Object, column:DataGridColumn):String
			{
				return String(item);
			}

Which results in

Code:
ID | SOME1 | SOME2 |
1   | HTML   | PHP     |
ID | FLEX    | GAF     |

Here's my version, which pastes the rows correctly and inserts them correctly to rows, but not into fields:

Code:
			private function dataGridSelectionText(fieldSeparator:String, rowSeparator:String):String
			{
				const columns:Array = filtterilista2.columns;
				const valinnat:Object = filtterilista2.selectedItems;
				var cp:Object = filtterilista2.selectedItems;
			
				var rowIndex:int = -1;
				var text:String = "";
				
				for each (cp in valinnat) {
					if ((rowIndex != -1) && (cp.rowIndex != rowIndex))
						text += rowSeparator;
					else if (rowIndex != -1)
						text += fieldSeparator;
					rowIndex = cp.rowIndex;
					
					var column:DataGridColumn = columns.indexOf(cp.columnIndex) as DataGridColumn;
					var value:String = ObjectUtil.toString((cp["itemnumber"]+" "+cp["model"]+" "+cp["desc1"]+" "+cp["desc2"]+" "+cp["material"]));
				
					
					text += exportText(value, column);

				
				}
				return text;                
			}

			public function exportText(item:Object, column:DataGridColumn):String
			{
				return String(item);
			}

Which results in

Code:
ID SOME1 SOME2 |
1  HTML  PHP     |
ID FLEX   GAF     |



Screw that, I take the easy way out and manually insert the fieldSeparators between values.
 

Aeris130

Member
Java gurus:

The following isn't an exact implementation that I need, but I'm curious if it's possible to achieve the same effect without having to resort to if-cases or instanceof.

Basically, I need an abstract class or an interface A declaring a catch-all method myMethod(Object o) making it possible to send anything to the class B (that extends/implements A). B should then contain additional implementations of myMethod with a different parameter type (say, myMethod(String s)). If a string is sent to B, it gets cought in myMethod(String), otherwise the parameter gets routed to mymethod(Object o), which doesn't really do anything.

Overriding isn't an option since I'm dealing with different parameter types.

Overloading doesn't work, because the object is declared as:

A obj = new B();

So obj only knows about myMethod(Object o) from A. Is this even possible? Is there a pattern that works in a similar fashion? Even if I create a parameter interface that every parameter has to implement, making it possible to just use a single method, I'd still have to check just wtf it is that implements it at some point and how to work with it, since it should be possible to send any object to the method.
 
Edit: Herp Derp didn't see bit about no instanceof, did you edit? Short answer as far as I know is no, you need to explicitly check types because the calling class has no way of knowing what variant of the method your subclass provides. Leaving the rest of this here anyway maybe someone will get use out of it.

---------

Java gurus:

The following isn't an exact implementation that I need, but I'm curious if it's possible to achieve the same effect without having to resort to if-cases or instanceof.

Basically, I need an abstract class or an interface A declaring a catch-all method myMethod(Object o) making it possible to send anything to the class B (that extends/implements A). B should then contain additional implementations of myMethod with a different parameter type (say, myMethod(String s)). If a string is sent to B, it gets cought in myMethod(String), otherwise the parameter gets routed to mymethod(Object o), which doesn't really do anything.

Overriding isn't an option since I'm dealing with different parameter types.

Overloading doesn't work, because the object is declared as:

A obj = new B();

So obj only knows about myMethod(Object o) from A. Is this even possible? Is there a pattern that works in a similar fashion?

It's not possible afaik to declare a method with a different signature in a subclass and have it be called from somewhere else. The caller only knows about the method defined in the interface/parent class.

You can get the effect you want though with type checking, something like this:

Code:
public class A 
{
	public void foo(Object o)
	{
		System.out.println("Got an object");
	}
}

public class B extends A
{
	public void foo(Object o)
	{
		if(o instanceof String)
		{
			System.out.println("Got a String");
		}
		else
		{
			super.foo(o); //super calls parent class implementation
		}
	}
}

Doing this then:

Code:
public static void main(String[] args)
{
	A bar = new B();
	bar.foo(2);
	bar.foo("LOL");
}

Prints:

Code:
Got an object
Got a String

You can add instanceof checks for any type you want to handle in the subclass in question.
 

Aeris130

Member
Scott Meyers said:
Anytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself.

Just seeing if I can minimize the number of ifs and elses in my OO code.
 
Just seeing if I can minimize the number of ifs and elses in my OO code.

Kind of a long shot but it might be useful depending on the exact implementation you are going for. You could try to make use of the Strategy Pattern.

You still need to adjust based on type but you would do it before calling the function rather than after and in the context of settings modes:

Code:
public interface Strategy 
{
	public void execute(Object o);
}

public class DefaultStrategy implements Strategy 
{
	public void execute(Object o)
	{
		System.out.println("This is the default behaviour");
	}
}

public class StringStrategy implements Strategy 
{
	public void execute(Object o)
	{
		System.out.println((String) o);
	}
}

public class IntStrategy implements Strategy 
{
	public void execute(Object o)
	{
		System.out.println((Integer) o * 2);
	}
}

public class Context 
{
	private Strategy strategy;
	
	public Context(Strategy strategy)
	{
		this.strategy = strategy;
	}
	
	public void Execute(Object o)
	{
		strategy.execute(o);
	}
}

public class B
{
	private Context context = new Context(new DefaultStrategy());
	
	public void setStrategy(Strategy strategy)
	{
		context = new Context(strategy);
	}
	
	public void foo(Object o)
	{
		context.Execute(o);
	}
}

public static void main(String[] args)
{
	B thingy = new B();
	thingy.foo("LOL");
	thingy.setStrategy(new StringStrategy());
	thingy.foo("LOL");
	thingy.setStrategy(new IntStrategy());
	thingy.foo(2);
}

Prints:


Code:
This is the default behaviour
LOL
4

How useful this approach is depends heavily on what functionality exactly you are implementing and how the existing code is structured. Also, I used String/Int as types in Strategy names for demonstration but you can obviously replace with whatever set of functionality you want. The nicer thing about it is that you can have multiple strategies that expect the same input type this way.
 

Kinitari

Black Canada Mafia
So I just wanted to talk to you guys about this transition I feel as though I am making from amateur to maybe-not-so-amateur programmer. It's not so much a question post as it is a livejournal-share post :p.

Last few pages I've been asking for help with a particularly difficult to deal with database, and I've gotten some pretty good help - as it stand now, the problem I had is almost completely gone, and really all I am doing is refining.

What's important about this however is the sort of change this problem has started to nurture in how I 'learn' more about programming. At one point I wanted to learn more about how to utilize OleDB for the CRUDing of my database, and while I had some theoretical knowledge of how to use it, I didn't have any practical knowledge - and that had scared me enough to mostly just stick with the IDE connection wizard.

Well this connection wizard just wasn't cutting it for me, and I wanted to really get into the nitty gritty, get my software running more efficiently and more accurately. I was nervous, because I had sort of adopted this mindset that I was starting to peak. As in, I was worried that I wouldn't be able to grasp the knowledge that I was seeking, and would be perpetually stuck at the 'amateur' level of a developer. Somehow, I managed to bite back on those fears and just dive in and try to teach myself what it is I wanted to know. I couldn't find a tutorial I liked so I said fuck the tutorial, let's just do it trial and error.

Within 30, maybe 40 minutes, I learned more than I had in probably the last few days combined. It just came so easily to me - or maybe it wasn't that I learned, but more like the stuff I learned in school, combined with my growing experience just made it so easy for me to understand everything I wanted to understand. I sincerely feel like I grew in terms of what I can and can't do as a programmer, and it's a wonderful feeling.

A couple of years ago I made a thread asking GAF what I should do with my life, and a couple of people recommended I try programming, I think that was 2009. I spent a few months just teaching myself the basics, and I had a lot of help from the gaffer Spoo I remember, who gave me some really good advice/lessons online - then I went to school and recently came out with my diploma. Now I am interning at a pretty cool government run community centre and I have had some nibbles for permanent placements in both the public and private sector.

And now I feel like I am really and truly getting good at this stuff, like I am moving in the right direction - and my life is markedly better because of it. I was working a crappy retail job that I really hated before this, and was pretty sure I would end up turning that into my 'career'. Now it looks like that isn't the case, like I have options all around me, and a huge part of that is because of GAF, and fellow GAF programmers.

Guys I really appreciate it, you've changed, and you continue to change my life.

edit: Update on my original problem - final solution.

The database/query I was using as my source to create these new datetime fields had just under 70,000 rows.
In row 6,190 there was some bad data - which I just fixed.
EVERYTHING now works.
Check for bad data people.
 

Anduril

Member
You can more easily figure where you should start by using the error information (which includes a stack trace) to find out exactly where in the code it happened.

...

and the next time you use nextDouble, it's trying to parse "Your" as a double, causing the error.
First of all, thanks so much for the informative reply. As I've said, I'm just beginning and every detail like the number line makes a world of difference. Had to google how to enable line numbers in Eclipse first, though. :)

So if I understand your explanation correctly, the culprit for the error is the aScanner.nextLine();, which moves the beginning of the file read on the 2nd call a line too low? Then removing aScanner.nextLine(); should fix the problem, but it doesnt - I still get the exact same error. :( Not a lot of time for learning today, so I havent really had time to try anything else. I want to just let this go and continue with the book, but next lessons build upon this one and if this doesnt work, nothing else on wont, unfortunately. It seems totally weird that the official downloaded book companion source files return an error, though.

usea: Thanks for the clarification. Every bit of new knowledge helps at this time. :)
 

mltplkxr

Member
Java gurus:

The following isn't an exact implementation that I need, but I'm curious if it's possible to achieve the same effect without having to resort to if-cases or instanceof.

Basically, I need an abstract class or an interface A declaring a catch-all method myMethod(Object o) making it possible to send anything to the class B (that extends/implements A). B should then contain additional implementations of myMethod with a different parameter type (say, myMethod(String s)). If a string is sent to B, it gets cought in myMethod(String), otherwise the parameter gets routed to mymethod(Object o), which doesn't really do anything.

Overriding isn't an option since I'm dealing with different parameter types.

Overloading doesn't work, because the object is declared as:

A obj = new B();

So obj only knows about myMethod(Object o) from A. Is this even possible? Is there a pattern that works in a similar fashion? Even if I create a parameter interface that every parameter has to implement, making it possible to just use a single method, I'd still have to check just wtf it is that implements it at some point and how to work with it, since it should be possible to send any object to the method.

The idea is to have A do the work you want to do in B. So you define an interface with a method that does that work. Any class you want to pass to B then implements that interface. You can then call that method from B.

For example (in pseudo code):
interface Worker
public void doWork();

class A implements Worker
public void doWork() {print "I'm an A! Yeah!"}

class A2 implements Worker
public void doWork() {print "I'm an A too! Woohoo!"}

class B
myMethod(Worker toDo) { toDo.doWork()}

B.myMethod(A) = "I'm an A! Yeah!"
B.myMethod(A2) = "I'm an A too! Woohoo!"

Something like that. It's a common pattern and it's used extensively in the core Java API. Look at compare() and equals() for example: you implement the Comparable interface (with the compare() method) on classes you want to sort and then pass a Collection of that to sort(). Collections.sort() then calls compare on your class instead of doing if instanceof that, sort that way, etc.

lorebringer cited Strategy. You can look at Command http://en.wikipedia.org/wiki/Command_pattern as well, which is very simple.

Hope that helps.
 

Zoe

Member
Well, that's good to know so I can keep an eye out for that.

Zoe - you're really good with c# if I remember correct, currently working out my problems with my database, and it's a fun process - but I realize my knowledge in oleDB is lacking. I hate using MSDN as a learning tool, so I was wondering if you know of any good online literature that I could read today, that'd make me more comfortable with it?
I'm afraid I don't really know of specific resources. I usually just Google what I'm trying to do, and that will either take me to MSDN or StackOverflow.
 

usea

Member
Just seeing if I can minimize the number of ifs and elses in my OO code.
I have no idea why you're trying to reduce the number of if-statements. That's a really weird goal, even if you're trying to eliminate jmps for performance. This task could certainly be performed in a different way that is more performant.

BUT, with your stated goals, I have a solution. If you want to skip instanceof, just cast to every target type, each in its own try-catch block. Black hole the exceptions. The one that doesn't throw an exception will work, and you'll call the correct method.

edit: code:
Code:
public interface ICatchAll {
    void myMethod(Object o);
}

public class DoesAll implements ICatchAll {

    @Override
    public void myMethod(Object o) {
        try {
            String s = (String)o;
            myMethod(s);
            return;
        }catch(Exception ex) {}
        
        try {
            float f = (float)o;
            myMethod(f);
            return;
        }catch(Exception ex) {}
    }
    
    private void myMethod(String s) {
        System.out.println("string: " + s);
    }
    
    private void myMethod(float f) {
        System.out.println("float: " + f);
    }
}

public class JavaApplication2 {
    public static void main(String[] args) {
        ICatchAll d = new DoesAll();
        String s = "yes";
        d.myMethod(s);
        float f = 10.5f;
        d.myMethod(f);
    }
}

output:
string: yes
float: 10.5

No if, switch, or instanceof. Dumb requirements. :)

edit2: changed the variable in main to ICatchAll to better demonstrate the point.
 

Aeris130

Member
The idea is to have A do the work you want to do in B. So you define an interface with a method that does that work. Any class you want to pass to B then implements that interface. You can then call that method from B.

For example (in pseudo code):
interface Worker
public void doWork();

class A implements Worker
public void doWork() {print "I'm an A! Yeah!"}

class A2 implements Worker
public void doWork() {print "I'm an A too! Woohoo!"}

class B
myMethod(Worker toDo) { toDo.doWork()}

B.myMethod(A) = "I'm an A! Yeah!"
B.myMethod(A2) = "I'm an A too! Woohoo!"

The problem is that B is the only class that knows what should happen when myMethod is called. This only pushes the problem up one layer: Now it's A/A2 that needs to be able to take every object as indata, but only work with a few specific object types when doWork is called.

If I make separate A objects for each object type that can be worked on, it shifts one layer up again. Now I need to find out what type of object I have, so I can instantiate the correct A object with it. Maybe I'm misunderstanding something.


Yeah, this is another method. The reason I wanted to avoid ifs isn't due to performance, but because adding new classes forces me to keep track of typechecks outside the class itself, that now needs to be updated with new casts/whatever. Basically another "oh and remember to add this class to the typecheck in object xxx, otherwise the program won't be able to work with it". Which forces me to document every place in the code that needs updating, which adds more documentation that needs to be maintained if I change the system.
 

usea

Member
Yeah, this is another method. The reason I wanted to avoid ifs isn't due to performance, but because adding new classes forces me to keep track of typechecks outside the class itself, that now needs to be updated with new casts/whatever. Will make it a pain to maintain once the number gets bigger (which it will).
Ah, I see. Well, you could put all those classes in a particular namespace (package?) and use reflection to iterate over them, for one that implements some interface like Implementor<string> for example. Pretty sure you could do that in Java, right? I haven't used it for quite a while, and I never used reflection.
 

Toma

Let me show you through these halls, my friend, where treasures of indie gaming await...
I need some serious help in C#. Might be a general programming problem too, I have no fucking clue.

In the last few days I worked on a program to analyze data that I saved in a txt file. All users used the same txt file which is the ONLY place my program gets its data from.

The text in my save file itself is structured like this:

Super Mario Galaxy$%&http://www.gamerankings.com/wii/915692-super-mario-galaxy/articles.html$%&WII$%&http://image.gamespotcdn.net/gamespot/images/box/6/9/2/915692_68186_thumb.jpg$%&Nintendo$%&2007$%&97.64%$%&77%&$gamrReview%$&02/01/09%$&9.6 out of 10%$&96.00%%§&Nintendo Life%$&11/12/07%$&10 out of 10%$&100.00%%§&Gamer Limit%$&07/28/09%$&9.6 out of 10%$&96.00%%§&RealGamer%$&01/01/08%$&8.6 out of 10%$&86.00%

Basically: GameName-Filler-website-Filler-Platform-Filler-picture-Filler-review1 name-Filler-Review1Date-Filler-Score-Filler-Score/100-Filler

and then divide it accordingly.

Problem now is this. My PC:
X6gij.png

People I send my program to:

See the average score? Shows up fine for me. I would somehow understand if NONE of the data from the txt file would show up for some missing framework or whatever, but ONLY the calculated number? I mean everything else is shown correctly. Why, how, when... I have no clue what I am supposed to do about that.

Cant troubleshoot either :/
 

usea

Member
It's missing the semicolon after PC in the list box, too. What generates that? If it's not happening on their end, that gives you a clue as to what else isn't happening.

Is this a .net app? If it just doesn't work, but also doesn't crash, does that mean you're catching exceptions and just ignoring them? Add some logging statements (like, to an error.txt file) in catch blocks. Find out what errors are happening on their computer that might cause this.

Why the weird file format? There are tons of standard things out there like json, xml or csv. Just wonderin.
 

Toma

Let me show you through these halls, my friend, where treasures of indie gaming await...
What sort of code are you using to parse it? It's always better to have some code to look at.

Code:
string[] RawData1 = Regex.Split(RawData, "µµµ");

            foreach (string elem in RawData1)
            {

                List<string> Element = new List<string>();
                List<string> ElementReviews = new List<string>();


                string bla = elem.Replace("$%&", "µµµ");
                bla = bla.Replace("%&$", "µµµ");
                string[] elempart = Regex.Split(bla, "µµµ");

                    Element.Add(elempart[0]);
                    Element.Add(elempart[1]);
                    Element.Add(elempart[2]);
                    Element.Add(elempart[3]);
                    Element.Add(elempart[4]);
                    Element.Add(elempart[5]);
                    Element.Add(elempart[6]);
                    Element.Add(elempart[7]);

                    elempart[8] = elempart[8].Replace("%$&", "µµµ");
                    elempart[8] = elempart[8].Replace("%%§&", "µµµ");

                    string[] ReviewsDivider = Regex.Split(elempart[8], "µµµ");

                    foreach (string elem2 in ReviewsDivider)
                    {
                        ElementReviews.Add(elem2);
                    }
                    
                    //loading data into the lists that I want to use throughout my program after they have been divided into game (element) and corresponding reviews.
                    Variables.Data.Add(Element);
                    Variables.Data.Add(ElementReviews);
              }

Maybe the way you transferred the database file caused it to change slightly, like because of line endings or encoding? Or maybe their regional settings are causing numbers to be recognized differently, like if they're in europe and they use commas instead of periods for decimals, and your number parsing isn't specifying the method so it freaks out when it sees the wrong format.

It's missing the semicolon after PC in the list box, too. What generates that? If it's not happening on their end, that gives you a clue as to what else isn't happening.

Is this a .net app? If it just doesn't work, but also doesn't crash, does that mean you're catching exceptions and just ignoring them? Add some logging statements (like, to an error.txt file) in catch blocks. Find out what errors are happening on their computer that might cause this.

Why the weird file format? There are tons of standard things out there like json, xml or csv. Just wonderin.

Yeeeeah...probably everything about my code looks like eye cancer to others >_> I am super messy and usually go with the first idea that comes to mind. Actually I already improved quite a lot over the past 2-3 years, but its still rather... crude.

The try/catch thing might indeed be a problem as I have a few in my code, I'll try to create an error log.
 

usea

Member
out-of-the-blue guesses:

Maybe the way you transferred the database file caused it to change slightly, like because of line endings or encoding?

Or maybe their regional settings are causing numbers to be recognized differently, like if they're in europe and they use commas instead of periods for decimals, and your number parsing isn't specifying the method so it freaks out when it sees the wrong format.
 

Osiris

I permanently banned my 6 year old daughter from using the PS4 for mistakenly sending grief reports as it's too hard to watch or talk to her
Yeeeeah...probably everything about my code looks like eye cancer to others >_> I am super messy and usually go with the first idea that comes to mind. Actually I already improved quite a lot over the past 2-3 years, but its still rather... crude.

Those variable names are straight out BRAIN cancer, the first thing I'd work on if I was you was adopt good, meaningful variable names and use camel case! It'll make debugging a million times easier, for you and others.
 

Toma

Let me show you through these halls, my friend, where treasures of indie gaming await...
out-of-the-blue guesses:

Maybe the way you transferred the database file caused it to change slightly, like because of line endings or encoding?

Or maybe their regional settings are causing numbers to be recognized differently, like if they're in europe and they use commas instead of periods for decimals, and your number parsing isn't specifying the method so it freaks out when it sees the wrong format.

They are Americans, I am European, so our PCs definitely use different formats. Isnt programming something in c# universal? Why is that being affected? They dont enter any decimals.. how could I even adjust that?

Edit:
Looking up specifying the number format.

Those variable names are straight out BRAIN cancer, the first thing I'd work on if I was you was adopt good, meaningful variable names and use camel case! It'll make debugging a million times easier, for you and others.

Yeah, I know. I never have in mind that I need to show my code to someone, usually it tends to work... somehow.
 

mltplkxr

Member
The problem is that B is the only class that knows what should happen when myMethod is called. This only pushes the problem up one layer: Now it's A/A2 that needs to be able to take every object as indata, but only work with a few specific object types when doWork is called.

If I make separate A objects for each object type that can be worked on, it shifts one layer up again. Now I need to find out what type of object I have, so I can instantiate the correct A object with it. Maybe I'm misunderstanding something.
A/A2 don't need to take any object as data, they are the data (and B is your algo that works on that data). It relegates part of the problem to what each class should know, keeping in line with the principles of encapsulation.

In any case, I think I'm the one who misunderstood something! Re-reading it now, what I get from your example is that you want to develop a method that can be implemented by any class ("B implements A") and to which you can pass anything ("a catch-all") but that gets redirected to a default method in case the type is not recognized ("gets routed to myMethod(Object o)")? I'm not sure about this part: "B should then contain additional implementations of myMethod", because on one hand there needs to be 1 method but on the other hand there needs to be several.

lorebringer pointed to the Strategy pattern and that sounds like what you want to do. But also, it sounds like the concerns are not fully separated. But I guess that' s a side effect of using As and Bs in an example with no context :).

Take a look at the Strategy pattern and the java.lang.Comparable interface in relation to its use in Collections.sort().

I hesitate to suggest generics, althought it might be the solution you need, because it can make code somewhat complex, like this: http://www.javaspecialists.co.za/archive/newsletter.do?issue=123
(related discussion: http://www.theserverside.com/news/thread.tss?thread_id=39454)
 

Osiris

I permanently banned my 6 year old daughter from using the PS4 for mistakenly sending grief reports as it's too hard to watch or talk to her
Yeah, I know. I never have in mind that I need to show my code to someone, usually it tends to work... somehow.

Good variable names are not only about readability when sharing code, but also makes debugging issues yourself a lot more straightforward, good variable naming conventions help to significantly close the gap between pseudocode and code implemented in a specific language. Adopt these kind of practices and you'll find your coding improves significantly.
 

usea

Member
They are Americans, I am European, so our PCs definitely use different formats. Isnt programming something in c# universal? Why is that being affected? They dont enter any decimals.. how could I even adjust that?
Are you using like, double.Parse() somewhere to parse the numbers from strings? There's an overload which allows you to specify an invariant culture, otherwise it uses the culture of the PC running the code.

e.g.:
Code:
double d = double.Parse("50.55", NumberFormatInfo.InvariantInfo);

Here's some examples of specific cultures and their output:
Code:
var ci = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
double d = double.Parse("50,55", ci.NumberFormat);
//output: 50.55

var ci = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
double d = double.Parse("50,55", ci.NumberFormat);
//output: 5055

edit: I see your example database uses a . separator for decimals, so I doubt the person running the code on a US-locale computer would have issues parsing that.
 
They are Americans, I am European, so our PCs definitely use different formats. Isnt programming something in c# universal? Why is that being affected? They dont enter any decimals.. how could I even adjust that?
Hmm... alright, just to eliminate any weirdness:

1. Make sure to eliminate any weirdness with delimiters - use one consistent delimiter, like I dunno, '#', or a comma.

2. Make sure to know what format the text file is in - if you're using a StreamReader, for example, and your textfile is Unicode, you'll need to specify that when opening. Or if the textfile is in some other specific European encoding, then change it to Unicode, and proceed.

edit: The above also applies too, if an error is being thrown when parsing.
 

Osiris

I permanently banned my 6 year old daughter from using the PS4 for mistakenly sending grief reports as it's too hard to watch or talk to her
Hmm... alright, just to eliminate any weirdness:

1. Make sure to eliminate any weirdness with delimiters - use one consistent delimiter, like I dunno, '#', or a comma.

2. Make sure to know what format the text file is in - if you're using a StreamReader, for example, and your textfile is Unicode, you'll need to specify that when opening. Or if the textfile is in some other specific European encoding, then change it to Unicode, and proceed.

I'd agree if it was for an embedded system with low resources, but for a modern PC app a better option would be straight-up XML, forget delimiters altogether, when dealing with a lot of textual strings as data the chances of a rogue "content as delimiter" issue occurring increases quite dramatically, think of the fun he'll have when "#Hack" is released as a game title when he's used # as a delimiter for instance. :p

Even worse is using $ as a delimiter as he currently is, when "$$$ Cash Money Poker" gets released :D
 

Toma

Let me show you through these halls, my friend, where treasures of indie gaming await...
Hmm... alright, just to eliminate any weirdness:

1. Make sure to eliminate any weirdness with delimiters - use one consistent delimiter, like I dunno, '#', or a comma.

2. Make sure to know what format the text file is in - if you're using a StreamReader, for example, and your textfile is Unicode, you'll need to specify that when opening. Or if the textfile is in some other specific European encoding, then change it to Unicode, and proceed.

edit: The above also applies too, if an error is being thrown when parsing.

Hm, when applying the Encoding.Unicode to all my StreamReaders:
StreamReader ReadSave = new StreamReader("User Reviews.txt", Encoding.Unicode);

I am not getting any data at at all anymore.

I tried coming up with many different delimiters since I have 20mb in that textfile and I wanted to make sure those delimiter sequences wouldnt pop up anywhere else..

I'll look into the XML tag thing tomorrow though (as Osiris is suggesting) if I dont get it to work with a txt file, since that might be an issue.

I'd agree if it was for an embedded system with low resources, but for a modern PC app a better option would be straight-up XML, forget delimiters altogether, when dealing with a lot of textual strings as data the chances of a rogue "content as delimiter" issue occurring increases quite dramatically, think of the fun he'll have when "#Hack" is released as a game title when he's used # as a delimiter for instance. :p

Even worse is using $ as a delimiter as he currently is, when "$$$ Cash Money Poker" gets released :D

Thats why I am always using 3 different signs as delimiters, like $§# or whatever.
 
I'd agree if it was for an embedded system with low resources, but for a modern PC app a better option would be straight-up XML, forget delimiters altogether.
Eh, a neat CSV would be good enough if this is just a small app he threw together to show off some neat functionality.

Best to figure out what the problem is right now and make it work - there's always time for format changes later.
 

mltplkxr

Member
I'd agree if it was for an embedded system with low resources, but for a modern PC app a better option would be straight-up XML, forget delimiters altogether, when dealing with a lot of textual strings as data the chances of a rogue "content as delimiter" issue occurring increases quite dramatically, think of the fun he'll have when "#Hack" is released as a game title when he's used # as a delimiter for instance. :p

Yep, but the useful thing about standard delimiters of old is that the file can be imported in Excel and parsed/debuged/manipulated easilly. Toma can easilly find any corrupted input by importing the file and telling Excel what the separator is.

Personnaly, with the plethora of lightweitgh databases available now, I find it's a no brainer to go SQL.
 

Toma

Let me show you through these halls, my friend, where treasures of indie gaming await...
Yep, but the useful thing about standard delimiters of old is that the file can be imported in Excel and parsed/debuged/manipulated easilly. Toma can easilly find any corrupted input by importing the file and telling Excel what the separator is.

Personnaly, with the plethora of lightweitgh databases available now, I find it's a no brainer to go SQL.

I tried learning Databases/SQL once, but started doing other stuff and somehow never picked up on it again. I know I should get my stuff together and learn that at one point though.

Are you using like, double.Parse() somewhere to parse the numbers from strings? There's an overload which allows you to specify an invariant culture, otherwise it uses the culture of the PC running the code.

And yeah, no double parse and its already "." in the txt file. However, everything is properly divided from the txt file for them as well. The only thing that isnt working are the numbers.
 

Toma

Let me show you through these halls, my friend, where treasures of indie gaming await...
HM, thanks to your suggestion I just changed my PC setting to EN(USA) and I got the same error with the numbers.

So that IS definitely the issue.

Putting Encoding.Unicode after the StreamReader didnt help though, anything else I could try in that case?

I am not using the parse function either. Only Regex.Split and string.Split.
 
Well, how about this - upload the text file you're using somewhere, and it'll be clear to spot whether it's an encoding issue, or something else entirely.

edit2: hmm, lemme stare at the example line for a bit
 

Toma

Let me show you through these halls, my friend, where treasures of indie gaming await...

Chris R

Member
database.txt makes me cry a little inside :( SQL Lite/Mysql/Sql Server Express/ect! All your data looks like it should parse fine though, at least from what I saw in the text file.
 
This is a smaller example file, gives the same error though:
https://www.dropbox.com/s/hf72863t1tktvic/Database%20-%2020.rar
I'll check this in the meantime, kk.

But do you use "µµµ" anywhere in the file? Because I don't seem to see it. I ask because of your first line:
Code:
string[] RawData1 = Regex.Split(RawData, "µµµ");
and I guess I should also ask if the file is supposed to be all on a single line, no line breaks.
 

Toma

Let me show you through these halls, my friend, where treasures of indie gaming await...
Well, how about this - upload the text file you're using somewhere, and it'll be clear to spot whether it's an encoding issue, or something else entirely.

edit2: hmm, lemme stare at the example line for a bit

Found it! :)

But can anyone explain me why this even was a problem?

This line is the culprit:
Code:
richTextBox5.Text = Convert.ToString(Math.Round(Convert.ToDouble(elem[6].Replace("%",""))/100)));
elem[6] contains "77.77%" for example.
It worked when I replace it with:
Code:
                    string test1 = elem[6].Replace("%", "");
                        double test2 = Convert.ToDouble(test1);
                        double test3 = Math.Round(test2);
                        string test4 = Convert.ToString(test3);

Why? And why are the regional settings affecting that? I mean what makes the long line work in German settings, but not in US ones?

I'll check this in the meantime, kk.

But do you use "µµµ" anywhere in the file? Because I don't seem to see it. I ask because of your first line:
Code:
string[] RawData1 = Regex.Split(RawData, "µµµ");
and I guess I should also ask if the file is supposed to be all on a single line, no line breaks.

I replaced part of the delimiters with "µµµ" when using Regex.Split. Somehow the delimiters wouldnt work when used in Regex.Split in certain combinations. Like Regex.Split(string, "%$&") simply did not work. Then I replaced it earlier with "µµµ" and it worked. Apparently thats not the problem though :)

Thanks for everyone chiming in! And yes, I promise to look at SQL once I am done with this program. Guess I avoided it for long enough.
 
Well, not sure what would be wrong with the short line. That is, as long as you always expect elem[6] to contain a percent, formatted in that specific way.

Although, just wondering, what's the first split you use, before the example code you gave?
 

Toma

Let me show you through these halls, my friend, where treasures of indie gaming await...
Well, not sure what would be wrong with the short line. That is, as long as you always expect elem[6] to contain a percent, formatted in that specific way.

Although, just wondering, what's the first split you use, before the example code you gave?

The one in the example was actually the first one upon loading up (It has the aforementioned replace function though because Regex.Split(string, "§?§") didnt work):

RawData = RawData.Replace("§?§", "µµµ");
string[] RawData1 = Regex.Split(RawData, "µµµ");

RawData before is everything unaltered from the save file.

elem[6] should also be always the same, yeah. But just in case it werent, why would that lead to an error in a US regional format setting but not in the German one? This is just so weird... There is another error that is probably due to the same reason (me not seeing it, but the Americans do), will hunt that down tomorrow. If you guys wouldnt have mentioned the regional format setting I'd have never found that out.

Thanks again :)
 
Actually, something I just looked over completely, since I thought you mistyped it:
Code:
Convert.ToString(Math.Round(Convert.ToDouble(elem[6].Replace("%",""))/100));
Did you mistype it, because according to this, you're taking the percentage (77.77%, for example), dividing the number by 100, then rounding it - that results in 1, since you're rounding a decimal that is gonna probably be between .5 and 1 almost all the time.
 

Toma

Let me show you through these halls, my friend, where treasures of indie gaming await...
Actually, something I just looked over completely, since I thought you mistyped it:
Code:
Convert.ToString(Math.Round(Convert.ToDouble(elem[6].Replace("%",""))/100)));
Did you mistype it, because according to this, you're taking the percentage (77.77%, for example), dividing the number by 100, then rounding it - that results in 1, since you're rounding a decimal that is gonna probably be between .5 and 1 almost all the time.

I always got either 0 or 1 after rounding, so that is probably the issue. I am doing exactly what you just said. The...

Oh. Wow. Thanks for pointing that out.
Now I got it. One should never, ever ignore a problem that somehow works otherwise but still hasnt been solved.

elem[6] is actually 77.77% in the txt file, but for some reason, and I didnt figure out why until now,Math.Round(77.77) would always give me 7777, so I added the /100 to get back to the proper number. However the US formatting would already see this as 77.77/100=0.77.. which is why it worked when I left out the /100 in the 4 line code for the US formatting. Now that I changed it back to EU formatting, its scrambled in the opposite direction.

Now the opposite happens though. How can use Math.Round in a specific format? Either I need /100 for EU or I dont for US. Should I use If clauses that check for pc formatting settings or is there an easier way?

Cant test anymore, but would the things that usea suggested maybe work for Math.Round too?
double d = double.Parse("50.55", NumberFormatInfo.InvariantInfo);
 
I always got either 0 or 1 after rounding, so that is probably the issue. I am doing exactly what you just said. The...

Oh. Wow. Thanks for pointing that out.
Now I got it. One should never, ever ignore a problem that somehow works otherwise but still hasnt been solved.

elem[6] is actually 77.77% in the txt file, but for some reason, and I didnt figure out why ,Math.Round(77.77) would always give me 7777, so I added the /100 to get back to the proper number. However the US formatting would already see this as 77.77/100=0.77.. which is why it worked when I left out the /100 in the 4 line code.

Now the opposite happens though. How can use Math.Round in a specific format? Either I need /100 for EU or I dont for US. Should I use If clauses that check for pc formatting settings or there an easier way?
Well, if all the numbers are formatted in a specific format in the read file, then you should pass in the culture when doing the double.Parse, like so:
Code:
// Will parse as 77 and 77/100, using (German - Germany) culture info.
var deEnc = double.Parse("77,77", CultureInfo.GetCulture("de-DE"));

// Will parse as the same thing, using the (English - United States) culture.
var usEnc = double.Parse("77.77", CultureInfo.GetCulture("en-US"));

Basically, once you know what format your numbers are gonna be in, use a specific culture through the above method to parse the number you get. Make sure to use the System.Globalization namespace to gain access to the CultureInfo class, though.
 

Toma

Let me show you through these halls, my friend, where treasures of indie gaming await...
Well, if all the numbers are formatted in a specific format in the read file, then you should pass in the culture when doing the double.Parse, like so:
Code:
// Will parse as 77 and 77/100, using (German - Germany) culture info.
var deEnc = double.Parse("77,77", CultureInfo.GetCulture("de-DE"));

// Will parse as the same thing, using the (English - United States) culture.
var usEnc = double.Parse("77.77", CultureInfo.GetCulture("en-US"));

Basically, once you know what format your numbers are gonna be in, use a specific culture through the above method to parse the number you get.

Got it. Thanks a lot! :) I am pretty sure I wouldnt have found that out without GAF. I didnt even know where to start looking for the mistake. This thread and its inhabitants are mighty awesome :)
 
The problem is that B is the only class that knows what should happen when myMethod is called. This only pushes the problem up one layer: Now it's A/A2 that needs to be able to take every object as indata, but only work with a few specific object types when doWork is called.

If I make separate A objects for each object type that can be worked on, it shifts one layer up again. Now I need to find out what type of object I have, so I can instantiate the correct A object with it. Maybe I'm misunderstanding something.

I think what you're looking for is Double-Dispatch.
 

Tomat

Wanna hear a good joke? Waste your time helping me! LOL!
I need help picking a data structure for one my projects for school if you guys and gals don't mind offering some advice.

My first problem is I need to create an adjacency list that is provided by a text file at the start of the main function. The input looks like this:

a:bcd
b:ad
c:a
d:ab

and so on. The character before the : is the vertex, and the points listed after it at the adjacent vertices. Originally I was thinking of creating a class that stored a character (the vertex) and a vector of the adjacent vertices. My problem with this is I have no idea how many vertices the user will need to enter. I was trying to avoid the use of pointers, but the more I think about it, the more I'm uncertain as to whether that'll be possible. Would it be wise to user pointers in this problem so I can create new pointers to Nodes as the user needs them and store the information according? (That seems like a big Yes to me after typing this all out :I)
 
Assuming the following unix command

Code:
touch file; cat - >> file

it's correct in saying that it's creating the file 'file', and then appending (concatenating) whatever I type in the terminal to the file until I decide to ctrl-d out, right? I.E it's an empty file, then when cat >> file is called, it's taking input from the keyboard and redirecting to the file.

Prof gave it to us as a tester, and a possible test question, and I just want to make sure I can properly explain it.
 
Top Bottom