• 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

cyborg009

Banned
I need some help with this block of code in java for this getter:

The workday is divided into two shifts: day and night. the day shift is shift 1 and the night shift is shift 2. I'll post the full code is this doesn't help.

Code:
public int getShift() {
		
		
		if (shift == 1){
			return "Day";
		} else if (shift == 2){
			return "Night";
		}
		
		
			
	
	}

Second attempt
Code:
public String getShift() {
		
		String day = "Day";
		String night = "Night";
		if (shift == 1){
			return day;
		} else if (shift == 2){
			return night;
		}
		
		
			
	
	}
 

Haly

One day I realized that sadness is just another word for not enough coffee.
If I'm feeling lazy, I divide by 255. If I really care, I create my own color class with a utility function:

Code:
public class Color
{
     public int r, g, b, a;

     public Color(int red, int green, int blue, int alpha)
     {
          r = red;
          g = green;
          b = blue;
          a  = alpha;
     }

     Vector4 ToVector4()
     {
          return Vector4(r/255.0f, g/255.0f, b/255.0f, a/255.0f);
     }
}

Of course, you could always train yourself to think of colors in terms of percentages of each color channel but that's kind of silly.
 

Halvie

Banned
I need some help with this block of code in java for this getter:

The workday is divided into two shifts: day and night. the day shift is shift 1 and the night shift is shift 2. I'll post the full code is this doesn't help.

Code:
public int getShift() {
		
		if (shift == 1){
			return "Day";
		} else if (shift == 2){
			return "Night";
		}
		
	}

Second attempt
Code:
public String getShift() {
		
		String day = "Day";
		String night = "Night";
		if (shift == 1){
			return day;
		} else if (shift == 2){
			return night;
		}
	}



couldn't you do:

Code:
if(shift ==1)
return "Day";
else
return "Night";
 
If I'm feeling lazy, I divide by 255. If I really care, I create my own color class and with a utility function:

Code:
public class Color
{
     public int r, g, b, a;

     public Color(int red, int green, int blue, int alpha)
     {
          r = red;
          g = green;
          b = blue;
          a  = alpha;
     }

     Vector4 ToVector4()
     {
          return Vector4(r/255.0f, g/255.0f, b/255.0f, a/255.0f);
     }
}

Of course, you could always train yourself to think of colors in terms of percentages of each color channel but that's kind of silly.

For some reason it never really occurred to me to divide by 255.... But that makes total sense now and I'm upset I didn't realise it sooner.
 

squidyj

Member
If I'm feeling lazy, I divide by 255. If I really care, I create my own color class and with a utility function:

Code:
public class Color
{
     public int r, g, b, a;

     public Color(int red, int green, int blue, int alpha)
     {
          r = red;
          g = green;
          b = blue;
          a  = alpha;
     }

     Vector4 ToVector4()
     {
          return Vector4(r/255.0f, g/255.0f, b/255.0f, a/255.0f);
     }
}

Of course, you could always train yourself to think of colors in terms of percentages of each color channel but that's kind of silly.

Silly? it's the only way that makes sense, especially when rendering.
 
I need some help with this block of code in java for this getter:

The workday is divided into two shifts: day and night. the day shift is shift 1 and the night shift is shift 2. I'll post the full code is this doesn't help.

Generally speaking, you should mention the issue you are having. It might not be immediately obvious to folks that can help.

Although in this case, you have if/else if. Now, you might know enough about your program to know that all possible scenarios are covered, but the compiler doesn't. Your compiler doesn't know that the method will always return. All it knows is it will return under two possible conditions. For all the compiler knows, shift could equal 0, 3, or any other legal integer value. In that scenario, the method does not have code to return a value, so your compiler is going to give you an error saying something to effect of not all paths result in a return value. Alter the code, perhaps as suggested above by Halvie, so that all paths will.

Make sense?
 

caffeware

Banned

Aren't the numbers from 0 to 1 infinite too?
That's the basic of Zeno's paradoxes, I believe.

Suppose Homer wants to catch a stationary bus. Before he can get there, he must get halfway there. Before he can get halfway there, he must get a quarter of the way there. Before traveling a quarter, he must travel one-eighth; before an eighth, one-sixteenth; and so on.

This description requires one to complete an infinite number of tasks, which Zeno maintains is an impossibility.
 

cyborg009

Banned
Generally speaking, you should mention the issue you are having. It might not be immediately obvious to folks that can help.

Although in this case, you have if/else if. Now, you might know enough about your program to know that all possible scenarios are covered, but the compiler doesn't. Your compiler doesn't know that the method will always return. All it knows is it will return under two possible conditions. For all the compiler knows, shift could equal 0, 3, or any other legal integer value. In that scenario, the method does not have code to return a value, so your compiler is going to give you an error saying something to effect of not all paths result in a return value. Alter the code, perhaps as suggested above by Halvie, so that all paths will.

Make sense?

Yep and it works but it doesn't seem to output the shift times but that might be the toString which I should be able to fix. And I was planning add a while loop in the same block of code for inputs greater than 3 but I ran into a error about adding a return.

got it thanks

Code:
public class Employee {
	
	private String name;
	private String number;
	private String hireDate;
	public Employee() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Employee(String name, String number, String hireDate) {
		super();
		this.name = name;
		this.number = number;
		this.hireDate = hireDate;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	public String getHireDate() {
		return hireDate;
	}
	public void setHireDate(String hireDate) {
		this.hireDate = hireDate;
	}
	@Override
	public String toString() {
		return "Employee [name=" + name + ", number=" + number + ", hireDate="
				+ hireDate + ", toString()=" + super.toString() + "]";
	}

	

}

Code:
public class ProductionWorker extends Employee {

	private int shift;
	private double hourlyRate;
	
	public ProductionWorker(){
		
	}

	public ProductionWorker(int shift, double hourlyRate) {
		super();
		this.shift = shift;
		this.hourlyRate = hourlyRate;
	}

	public String getShift() {
		
		
		
		if (shift == 1){
			return "day";
		} else if (shift == 2){
			return "night";
		}else{
			return "incorrect number";
		}
		
		
		
		
	}

	public void setShift(int shift) {
		this.shift = shift;
		
	}

	public double getHourlyRate() {
		return hourlyRate;
	}

	public void setHourlyRate(double hourlyRate) {
		this.hourlyRate = hourlyRate;
	}

	@Override
	public String toString() {
		return "ProductionWorker [shift=" + shift + ", hourlyRate="
				+ hourlyRate + ", toString()=" + super.toString() + "]";
	}


	
}

Demo
Code:
import java.util.Scanner;


public class Employee_product_Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		ProductionWorker p = new ProductionWorker();
		Scanner input = new Scanner(System.in);
		System.out.println("Please enter your name");
		p.setName(input.nextLine());
		System.out.println("Please enter your ID number");
		p.setNumber(input.nextLine());
		System.out.println("Please enter date of hire");
		p.setHireDate(input.nextLine());
		System.out.println("Please enter your shift digit");
		p.setShift(input.nextInt());
		System.out.println("Please enter hourly rate");
		p.setHourlyRate(input.nextDouble());
		
		System.out.println(p);

}
}
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Silly? it's the only way that makes sense, especially when rendering.

"Silly" was a poor word choice there. I meant to say "really difficult and not worth it unless you really need to be able to do it".
 

caffeware

Banned
Thanks so much! Really helped me understand what I was doing much better.

The thing I don't understand now is that when I run to cursor, it shows the phoneNumber as the same value while formatNumber holds the formatted number, despite the fact that it says "return phoneNumber" at the end.

Code:
//*
string processNumber(string phoneNumber) //2nd copy made
{
    //Function's logic: [B]Local[/B] "phoneNumber" processed here!
    return phoneNumber; //3rd copy made *
}

int main()
{
    string phoneNumber = "12345678"; //1rst copy made (original)
    string formatNumber = processNumber(phoneNumber);//3rd copy made
    
     /* Now "formatNumber" holds a copy of the processed 2nd string, 
    the second copy got destroyed when the function ended; while the original "phoneNumber" is
   still untouched. */
    
    return 0;
}

Each copy is a different string even if they have the same name! This is possible because they are in different scopes.

For example:
Code:
int main()
{
    string phoneNumber = "12345678"; //1rst copy made (original)
    string phoneNumber = "12345678"; //not valid; same name in same scope!
    string phoneNumber = "85695354"; //still not valid!
    return 0;
}
 

Slavik81

Member
Oh I agree. Why use someone else's wheel when you can invent your own, better one?

I decided I'd do both to show you why.

The first solution:
Code:
#include <iostream>
#include <string>

bool isDigit(char character)
{
  return character >= '0' && character <= '9';
}

bool isValidPhoneNumber(const std::string& number)
{
  if(number.size() != 7)
  {
    return false;
  }

  for(size_t i=0; i<number.size(); ++i)
  {
    if(!isDigit(number[i]))
    {
      return false;
    }
  }

  return true;
}

int main()
{
  std::cout << "Input a phone number." << std::endl;
  std::string number;
  std::cin >> number;
  std::cout << "Number was " << (isValidPhoneNumber(number) ? "valid." : "invalid.") << std::endl;
  return 0;
}

This program took ~7 minutes to create.

I then created a new project, copy/pasted this one into it, and set about using boost::regex.
Code:
#include <iostream>
#include <string>
#include <boost/regex.hpp>

bool isValidPhoneNumber(const std::string& number)
{
  const boost::regex expression("\\d{7}");
  return regex_match(number, expression);
}

int main()
{
  std::cout << "Input a phone number." << std::endl;
  std::string number;
  std::cin >> number;
  std::cout << "Number was " << (isValidPhoneNumber(number) ? "valid." : "invalid.") << std::endl;
  return 0;
}

This program took 21 minutes to write, including downloading and and building boost::regex (a library with >10,000 dependencies). And no, it's not header-only.

Development was slower, the build is slower, the resulting executable is larger, and the code's not any easier to understand.

By what metric would boost::regex be an improvement?
 

Chris R

Member
Regex does have uses, but if you are only looking for 7 digits I wouldn't use it. When you need to account for other possible phone number formats and/or input by third parties is when it really shines (if it is something you can use within your program/language parameters).
 
Stuff that owns: Regex.


Any good simple tutorials for graphics (as in simple "canvas" like stuff) in c#. Triangles and squares and whatnot. Jumping from Flash/Flex/AS3 to a C# personal project for a while.
 

moka

Member
Regex does have uses, but if you are only looking for 7 digits I wouldn't use it. When you need to account for other possible phone number formats and/or input by third parties is when it really shines (if it is something you can use within your program/language parameters).

I wrote some Regex that can match all UK phone numbers quite accurately a while ago. Let me see if I can find it.

Edit: Found it! It was written for Java so you'll probably have to remove the extra escape slashes.

Code:
01\\d{4} \\d{5}|01\\d{3} \\d{6}|01\\d{1}1 \\d{3} \\d{4}011\\d \\d{3} 
\\d{4}|02\\d \\d{4} \\d{4}|03\\d{2} \\d{3} \\d{4}|055 \\d{4} \\d{4}|056 \\d{4} 
\\d{4}|070 \\d{4} \\d{4}|07624 \\d{6}|076 \\d{4} \\d{4}|07\\d{3} \\d{6}|0800 
\\d{3} \\d{4}|08\\d{2} \\d{3} \\d{4}|09\\d{2} \\d{3} \\d{4}

I think there might be a few things wrong with it, I'm pretty sure there's a pipe missing somewhere.
 

iapetus

Scary Euro Man
Stuff that owns: Regex.

perl_problems.png

To generate #1 albums, 'jay --help' recommends the -z flag.

For balance:

regular_expressions.png

Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee.
 

moka

Member
perl_problems.png

To generate #1 albums, 'jay --help' recommends the -z flag.

For balance:

regular_expressions.png

Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee.

Regular expressions can be beautiful, if you know how to use them properly. I, don't but I still like it.
 

-COOLIO-

The Everyman
anyone know if a html5 decibel detector?

edit: im using x-webkit-speech currently but it has a short listening time limit and it listens for actual words instead of random loudness.
 

squidyj

Member
I used regular expressions to parse a text and it worked quite well.

Anyways I'm having trouble with Haskell, primarily with functions as first class objects

Code:
--a truth assignment maps integer values to truth values
type TruthAssignment = Integer -> Bool

--defining a recursive data type of well formed formula
data Formula = 	FSym Integer |
				FNot Formula |
				FAnd Formula Formula |
				FOr Formula Formula

--needs to return a function that can be passed a truth assignment function
--the result of that function would be the extension of the given formula
--under that truth assignment
compileFormula :: Formula -> (Integer -> Bool -> Bool)
compileFormula (FSym x) g = g x
compileFormula (FNot x) _ = not (compileFormula x)
compileFormula (FOr x y) _ = (compileFormula x) || (compileFormula y)
compileFormula (FAnd x y) _ = (compileFormula x) && (compileFormula y)

in compileFormula not and the other logical operators are expecting booleans and will then produce booleans which is not what it needs to do.

The error i'm getting is "could not match expected type bool with actual type TruthAssignment -> bool" on the not statement, which I understand why it's giving me that, I just don't understand how I can generate this return function properly.
 

TheFatOne

Member
So GAF I really want to work on improving my java skills, but I'm not sure what to code. I'm looking for harder projects that will take several months. Right now the only thing I can think of is making a game. Can anyone give me some ideas?
 

moka

Member
So GAF I really want to work on improving my java skills, but I'm not sure what to code. I'm looking for harder projects that will take several months. Right now the only thing I can think of is making a game. Can anyone give me some ideas?

Build a web crawler, make an index using the information you collect, put it into a database and come up with algorithms that can help sort and organise the information in meaningful ways. Then create a GUI using AWT and Swing so you can search this database to find results for your query.

Basically a Google but on a much smaller scale.
 

KorrZ

Member
So GAF I really want to work on improving my java skills, but I'm not sure what to code. I'm looking for harder projects that will take several months. Right now the only thing I can think of is making a game. Can anyone give me some ideas?

My advice (while pretty general) would be to make something you'd actually use yourself. For example, I work in IT for a small managed services company and we need to keep track of time spent on projects/support cases for billing. While there are plenty of great apps/programs out there already for this purpose, I've built my own and have been constantly improving on it/refining it to suit my own specific needs.

It's a good learning experience and having something that you'll actually use on a daily basis is a great way to get ideas for how to improve on it; as well as keeping you motivated to make it better.
 
Dam just jumped back into c++ for minor project.
And well traps,traps as far as your eyes can see.

But yeah still love how it keeps you challenged and depressed when you don't see the bug immediately(the latter is the same for almost all languages :p ).
 

jon bones

hot hot hanuman-on-man action
This may seem like an odd request, but I'm currently revising my resume and I'm a little curious to see how software developers style / write up their resumes. If you don't mind PM'ing me a copy of yours, I'd love to see take a look at it for inspiration. Thanks!
 
This may seem like an odd request, but I'm currently revising my resume and I'm a little curious to see how software developers style / write up their resumes. If you don't mind PM'ing me a copy of yours, I'd love to see take a look at it for inspiration. Thanks!
I just use the moderncv template/package in LaTeX.
 

nan0

Member
I just use the moderncv template/package in LaTeX.

Yep, using it for both my CV and skill sheet. A section each for Programming/Script/Markup-languages, dev tools, operating systems, personal projects, professional interests, (spoken) languages and relevant university courses (if you recently graduated)
 

jon bones

hot hot hanuman-on-man action
I just use the moderncv template/package in LaTeX.

Yeah, this seems to be the coolest thing to be doing nowadays.

Yep, using it for both my CV and skill sheet. A section each for Programming/Script/Markup-languages, dev tools, operating systems, personal projects, professional interests, (spoken) languages and relevant university courses (if you recently graduated)

thanks bros, i'll take a look
 

Kinitari

Black Canada Mafia
So I finally got a programming job! But it looks like I'll probably have to learn PHP - I'm thinking about signing up for Lynda, cause I hear their PHP lessons are baller - what does GAF think, good idea? I start on goddamn, Monday (my interview was last friday) so I don't exactly have a huge amount of time to prep.

My roommate is also finally biting the bullet and going back to school this September for development, and I told him I'd help him as much as I could. I directed him to a bunch of web-tutorial sites, and he's taken to them - but now I am thinking about really giving him some good experience (and myself for that matter) and just forking a repo on github and working together on it with him. It'll give me some practical experience with ruby (I know the syntax, but I haven't really used it a lot) and also give both of us an opportunity to get more acclimated with GIT.

Does anyone here know of any good 'beginner' repos, maybe of like a really simple game in php or ruby that would make a good fork?
 

Kinitari

Black Canada Mafia
I am making a nav bar and the text inside these nav bars are a specific color. When i make the text inside the nav bars clickable for links they are blue instead of the color that i originally chose.

How did you originally choose this colour? Are you using just HTML + CSS? Any scripts? Is this in a CMS? Can we see the code that 'chose' the colour? Any code at all?

edit: Reading this post again, it sounds like the problem you are having is that your hyperlinks aren't the colour you want them to be.

By default, links are styled blue and underlined - you need to either overwrite this styling or remove it, usually in CSS.

Code:
a:link {text-decoration:none;}
a:visited {text-decoration:none;}
a:hover {text-decoration:underline;}
a:active {text-decoration:underline;}

removes all styling from links.
 

usea

Member
I am making a nav bar and the text inside these nav bars are a specific color. When i make the text inside the nav bars clickable for links they are blue instead of the color that i originally chose.
A lot more context would help. What are you even talking about? Is this a webpage? Your posts do absolutely nothing to explain what problem you're having.

I'm going to take a shot in the dark. Are you talking about css? If you're defining a color property on text in the body, that won't apply to links in the body. Those are different.

Here's an introductory page on css. Scroll to the part that is called "Setting Colors."

http://www.w3.org/MarkUp/Guide/Style
 

Ambitious

Member
I used regular expressions to parse a text and it worked quite well.

Anyways I'm having trouble with Haskell, primarily with functions as first class objects



in compileFormula not and the other logical operators are expecting booleans and will then produce booleans which is not what it needs to do.

The error i'm getting is "could not match expected type bool with actual type TruthAssignment -> bool" on the not statement, which I understand why it's giving me that, I just don't understand how I can generate this return function properly.


First off, fix the function signature:

Code:
compileFormula :: Formula -> TruthAssignment -> Bool

which is the same as:

Code:
compileFormula :: Formula -> (Integer -> Bool) -> Bool

Notice the difference to your signature.

Now, think about the types involved in the not statement: The not function expects a Bool, but "compileFormula x" does not return one. It returns an anonymous function taking a TruthAssignment and returning a Bool.

For some reason, you're discarding the TruthAssignment argument by using the underscore. But it's needed when a FSym is encountered.

So, just put the TruthAssignment function in there:

Code:
compileFormula (FNot x) g = not (compileFormula x g)

Of course you have to do the same for then Or and And calls.
 

jon bones

hot hot hanuman-on-man action
now I am thinking about really giving him some good experience (and myself for that matter) and just forking a repo on github and working together on it with him. It'll give me some practical experience with ruby (I know the syntax, but I haven't really used it a lot) and also give both of us an opportunity to get more acclimated with GIT.

Does anyone here know of any good 'beginner' repos, maybe of like a really simple game in php or ruby that would make a good fork?

I'm really interested in getting used to Git and doing something practical - mind explaining some of the language you're using here (fork, repo, etc)

congrats, btw!
 

Kinitari

Black Canada Mafia
I'm really interested in getting used to Git and doing something practical - mind explaining some of the language you're using here (fork, repo, etc)

congrats, btw!

Thanks :).I'll do my best at explaining, I'm still new at this.


Repo is short for repository, which on github you can think of as the container of all the project files/code.github is public, so you can see everyone's projects (or repos).You can also suggest changes/bugfixes. Forking is taking someone's project, copying it, and making your own version (your own fork).So for example, you see a game project, like the foundation but you want to take it in another direction, so you fork it.
Github keeps track of all of this.
 

jon bones

hot hot hanuman-on-man action
Thanks :).I'll do my best at explaining, I'm still new at this.


Repo is short for repository, which on github you can think of as the container of all the project files/code.github is public, so you can see everyone's projects (or repos).You can also suggest changes/bugfixes. Forking is taking someone's project, copying it, and making your own version (your own fork).So for example, you see a game project, like the foundation but you want to take it in another direction, so you fork it.
Github keeps track of all of this.

thanks bro, i think i'm gonna try my hand at finding a good project to work on. i feel like i really need a portfolio of stuff to stand out.
 

Zoe

Member
Thanks :).I'll do my best at explaining, I'm still new at this.


Repo is short for repository, which on github you can think of as the container of all the project files/code.github is public, so you can see everyone's projects (or repos).You can also suggest changes/bugfixes. Forking is taking someone's project, copying it, and making your own version (your own fork).So for example, you see a game project, like the foundation but you want to take it in another direction, so you fork it.
Github keeps track of all of this.

Just don't tell anybody you're gonna fork their repo!!!
 

squidyj

Member
First off, fix the function signature:

Code:
compileFormula :: Formula -> TruthAssignment -> Bool

which is the same as:

Code:
compileFormula :: Formula -> (Integer -> Bool) -> Bool

Notice the difference to your signature.

Now, think about the types involved in the not statement: The not function expects a Bool, but "compileFormula x" does not return one. It returns an anonymous function taking a TruthAssignment and returning a Bool.

For some reason, you're discarding the TruthAssignment argument by using the underscore. But it's needed when a FSym is encountered.

So, just put the TruthAssignment function in there:

Code:
compileFormula (FNot x) g = not (compileFormula x g)

Of course you have to do the same for then Or and And calls.

It all seems so obvious now and I feel pretty silly for letting it trip me up like that.
 

Exuro

Member
Can someone explain to me what the -Wall and -Werror flags for c++ compiling do? I'm compiling some code without it and it compiles, but when I use the flags I'm getting an undefined reference error.

edit: I found what my issue was but the question still stands.
 

Mangotron

Member
So if I have a text file that my program is reading that looks like

Code:
name   1   1
name   2   2
name   3   3

What's the easiest way (C++) to add those number columns top to bottom and calculate how many numbers are in each column?
 
Can someone explain to me what the -Wall and -Werror flags for c++ compiling do? I'm compiling some code without it and it compiles, but when I use the flags I'm getting an undefined reference error.

edit: I found what my issue was but the question still stands.

Wall is "warn all" ie turn all warnings on. Werror turns those warnings into actual errors.

So:

-Wall will still compile (wilst showing warnings for certain things)
-Werror will stop compiling until you resolve whatever the warning is about.
 
Top Bottom