Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Tots
Sep 3, 2007

:frogout:
In sed I am trying to take a string where a single quote occurs inside a set of single quotes, pinpoint the middle quote, and do something with it.

Here is where I am at.
code:
echo "This is 'Tot's' sample string" | sed "s|\(*'*\)\('\)\(*'*\)|\1\2\2\3|"
I would expect the output for this to be,
code:
This is 'Tot''s' sample string
but it's not. So now I'm here for help.

Adbot
ADBOT LOVES YOU

Tots
Sep 3, 2007

:frogout:
I really like Notepad++ for all my coding needs.

One of the selling points for me is the build in console plugin. Great for quick compiling and execution.

Tots
Sep 3, 2007

:frogout:
Who wants to help me complete a basic java assignment that's due tomorrow morning? I don't want you to do it for me, but kind of just walk me through the whats and whys in a collab online editor. If you're successful in helping me finish it I'll get you an upgrade/whatever of your choice.

Tots
Sep 3, 2007

:frogout:

Look Around You posted:

:lol:

e:
Less dickish: what problems are you having with it?

I just don't have a solid grasp on OOP. Reading about it isn't doing much good, so I figure it's tutor time.

E: Feel free to make fun of me/deface my retard program here: http://collabedit.com/k4w9y

Assignment detail here:
https://www.dropbox.com/s/djars6tl1vyghyu/HW6_Methods.pdf


Yes I know I'm retarded and should quit programming etc etc

Tots fucked around with this message at 06:33 on Feb 21, 2012

Tots
Sep 3, 2007

:frogout:
Just wanted to give a big thanks to LookAroundYou and orenj for helping me wrap my head around some pretty important concepts.

I'll rain down the good karma on new beginners in a few months.

Tots
Sep 3, 2007

:frogout:
In Java I have a switch statement depending on a variable declared as int. I collect the value to apply to the switch statement using the scanner class. How can I return an error if the user inputs a string?

IE

code:
Scanner switchScan = new Scanner(System.in);
System.out.println("Pick a number 1-4");
int switchVariable = switchScan.nextInt();


switch (switchVariable){
     case 1:
          System.out.println("It's 1");
          break;
     case 2:
          System.out.println("It's 2");
          break;
     case 3:
          System.out.println("It's 3");
          break;
     case 4:
          System.out.println("It's 4");
          break;
     default:
          System.out.println("Please pick a number 1-4");
          int switchVariable = switchScan.nextInt();
          break;
}
In other words, I want what happens in case default to happen if they enter a character or a string in addition to a number outside of the 1-4 scope.

E: As it is now, the application simply crashes when a string is entered.

Tots
Sep 3, 2007

:frogout:
Oh, awesome. Still new to the game and I didn't think of looking at the documentation, which in hindsight should have been my obvious first resource. Thanks.

Tots fucked around with this message at 01:24 on Feb 22, 2012

Tots
Sep 3, 2007

:frogout:

ToxicFrog posted:

This is not true of all languages or libraries, but the Java documentation is actually quite good if you already know what you're looking for (ie "how do I use class X").

It's less good for answering questions like "what classes do I need to solve problem Y", since for any given task, there's one class in the JRE that's poorly suited for it, and another half dozen that are very unsuited for it but can be made to work with some suffering, and it's a crapshoot which one you find first.

Is there a recommended go to resource around here for explaining Java related things at a very rudimentary level? For instance, I have never used a try-catch block before. Instead of just googling and blindclicking links I'd like a go-to resource that I know is thorough and easy to digest.

E: Actually, the oracle.com tutorials (which was the first google result) looks pretty good. I'm still open to suggestions though.
http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html

Tots fucked around with this message at 01:42 on Feb 22, 2012

Tots
Sep 3, 2007

:frogout:
Holy christ is this frustrating. I don't even actually need to do this for the assignment, but I got curious and now I loving hate that I can't make it work.

Why does this just give me a blank screen instead of prompting for input?

It starts out with tryAgain == true, so then it should run the code inside the try block. Right? RIGHT?! gently caress.

code:
public static void main(String[] args) {
        EmployeePayment empPayment = new EmployeePayment();
        double managerPay = empPayment.setManagerPay(625.00);
        Scanner scan = new Scanner(System.in); 
        boolean tryAgain = true;
        
            while (tryAgain == true);
            {
				try{
					System.out.println("Please enter a paycode or -1 to exit");
					int payCode = scan.nextInt();


						while (payCode != -1)
						{

							switch (payCode){
								case 1:
									System.out.println("Manager Selected.");
									System.out.println("Manager's pay is: $" + 
											empPayment.calcManagerPay());
									System.out.println("Enter paycode (-1 to end):");                           
									payCode = scan.nextInt();
									empPayment.addEmployee(1);
									break;
								case 2:
									Scanner rateScan = new Scanner(System.in);
									Scanner hourScan = new Scanner(System.in);
									System.out.println("Hourly Worker Selected. ");
									System.out.println("What is the worker's hourly rate? ");
									double rate = rateScan.nextDouble();
									System.out.println("How many hours did they work? ");
									double hours = hourScan.nextDouble();
									System.out.println("Hourly worker's pay is: $" + 
											empPayment.calcHourlyWorkerPay(rate, hours));
									System.out.println("Enter paycode (-1 to end):");                           
									payCode = scan.nextInt();
									empPayment.addEmployee(2);
									break;
								case 3:
									Scanner salesScan = new Scanner(System.in);
									System.out.println("Commission Worker Selected. ");
									System.out.println("What was the commission worker's gross "
											+ "sales? ");
									double sales = salesScan.nextDouble();
									System.out.println("Commission worker's pay is: $" + 
											empPayment.calcCommWorkerPay(sales));
									System.out.println("Enter paycode (-1 to end):");                           
									payCode = scan.nextInt();
									empPayment.addEmployee(3);
									break;
								case 4:
									Scanner scanPieces = new Scanner(System.in);
									Scanner scanWage = new Scanner(System.in);
									System.out.println("Piece worker Selected." );
									System.out.println("How many pieces did the worker sell?");
									double pieces = scanPieces.nextDouble();                    
									System.out.println("What is the wage per piece?");
									double wage = scanWage.nextDouble();
									System.out.println("Piece worker's pay is: $" + 
											empPayment.calcPieceWorkerPay(pieces, wage));
									System.out.println("Enter paycode (-1 to end):");                           
									payCode = scan.nextInt();
									empPayment.addEmployee(4);
									break;

								default:
									System.out.println("Please enter a valid paycode or -1 to"
											+ " exit");
									payCode = scan.nextInt();
									break;
							}
						tryAgain = false;
						}
					}
				catch(InputMismatchException e){
					System.out.println("Invalid entry");
					return;
            }
        System.out.println("Number of managers paid: " + empPayment.numManager);
        System.out.println("Number of hourly workers paid: " + empPayment.numHourlyWorker);
        System.out.println("Number of commission workers paid: " + empPayment.numCommWorker);
        System.out.println("Number of piece workers paid: " + empPayment.numPieceWorker);






            }
    }
}

Tots
Sep 3, 2007

:frogout:

csammis posted:

You have a semicolon after the while(). Take it out.

e: a little more explanation: that line is effectively while (tryAgain == true) /* empty statement that is executed forever */ ; /* the rest of your code */

gently caress me.

Okay, so it works, but it looks like after it gets an error it just exits with my error message. What I was going for is to have it continue running from the beginning of while (tryAgain = true) after it catches the error. That was the whole reason I stuck that while statement in there.

E: I put together code for testing purposes for what I want to accomplish. Should be easier to see what's going on and what I want

code:
public class JavaApplication2 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        boolean tryAgain = true;
        int switchVariable;
        
        while (tryAgain == true){
            try{
            
            System.out.println("Enter a number");
            switchVariable = scan.nextInt();

                while (switchVariable != 0){

                    switch (switchVariable)
                    {
                        case 1:
                            System.out.println("Case 1");
                            switchVariable = scan.nextInt();
                                    break;
                        case 2:
                            System.out.println("Case 2");
                            switchVariable = scan.nextInt();
                                    break;
                        default:
                            System.out.println("Not a valid number");
                            switchVariable = scan.nextInt();
                    }
                }
                tryAgain = false;
            }
            catch(InputMismatchException e){
                System.out.println("Not an integer");
                tryAgain = true;
                break;
                //I WANT THIS TO RUN AGAIN FROM while (tryAgain == true) AFTER IT CATCHES THE ERROR.  Is this possible?
            }
            }
        System.out.println("Program Finished");
        }
    }

Tots fucked around with this message at 05:03 on Feb 22, 2012

Tots
Sep 3, 2007

:frogout:

Look Around You posted:

You're gonna have to take the return; out of the catch block then; return leaves the entire function, not just the catch block that you're in.

When I don't put anything in there it repeats the error message ad infinitum.

Tots
Sep 3, 2007

:frogout:

Look Around You posted:

What error message is printing all the time? As an aside, that code is not really structured the best way... you don't really need the inner while loop. Try replacing it with an if statement or just using the switch statement. You almost certainly don't want nested loops here.

Actually I was wrong. The output when a string is entered is this:

code:
Not an integer
Enter a number
Not an integer
Enter a number
Not an integer
Enter a number
Not an integer
Enter a number
..ad infinitum
So it looks like it does continue to the beginning of the loop, then uses the old input to throw an error again before allowing for new input. Gonna try assigning the switchVariable to an arbitrary int at the end of the catch statement and see what happens.

Tots
Sep 3, 2007

:frogout:

ToxicFrog posted:

Back to the documentation we go:


In your exception handler, you need to read and discard the bad token (using, say, nextLine()), or it'll get stuck trying to read the same thing over and over again.


Thanks a lot for your help. Most of my problem at this point is just lack of exposure I think. This is literally my 1st java assignment that isn't just changing very basic code that's already written for me. Even though the docs are extremely helpful, "When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method." doesn't mean very much to me at this point.

E: When I put my brain to breaking it down it begins to make sense, but the concepts aren't really internalized at this point. It didn't register as 'important' to me until someone else explained why it's important.

quote:


Also, breaking your code down into multiple smaller functions - say, break "read an int" into its own function that loops until the user enters a valid int, and does the exception handling in there - would make this a lot more readable. (So would using continue to make the try block a lot smaller, for that matter, if java lets you do that.)

Taking it one step at a time, but I will consider this. Thanks.


Just to reaffirm what I am doing here (I got it to work just by adding in a nextLine() statement at the end of the catch), the exception handler is just going to keep reading that bad input until another method tells it to do something else with it. Is that correct? So the catch statement finishes, then returns to the beginning of the loop using whatever the most recent input was unless I specify that it should skip that input, or otherwise do something with it.

Tots fucked around with this message at 05:33 on Feb 22, 2012

Tots
Sep 3, 2007

:frogout:

ToxicFrog posted:

Maybe I've just been reading Structure and Interpretation too much, but it seems that functional abstraction and how to break down your program into smaller, easy to reason about chunks thereby should be the first step after super-basic things like "what is a program". (This is a bitch about the course, not you.)

I'm going to try to stick input collecting and error reporting in its own method tomorrow after I've gotten some sleep. Expect me back in this thread.

E: How long until I am not retarded at programming?

Tots fucked around with this message at 06:10 on Feb 22, 2012

Tots
Sep 3, 2007

:frogout:
Alright, I'm probably wearing out my welcome, but the cogs are turning.

If I wanted to abstract the input and error handling, would this be the right track?

code:
main{

 Prompt: Enter a Pay Code

 Call a method that takes payCode input and validates it.

 payCode = mainclass.PayCodeHandler();

 Switch statement based on payCode{

	Cases 1-4 for each valid paycode
	Case 99 for any invalid payCode
 }
}

public int PayCodeHandler(){
try
	collect input
	if 1-4 return 1-4
	else return 99
catch
Error?  return 99

Tots fucked around with this message at 06:26 on Feb 22, 2012

Tots
Sep 3, 2007

:frogout:

Look Around You posted:

This looks pretty good. Are you sure you want to return '99' on an InputMismatchException and not display an error, discard the invalid input and get a new input? This is more up to you, but if you return 99 on invalid input (strings etc) then your program will end after you do that. There's more ways to break it up even further too. If you find yourself typing the same thing over and over again (or at least extremely similar things), see if there's a way to make it into it's own function (or method or whatever the hell you want to call them).

Well the plan was to print a generic error message in Case 99. I was under the impression that the method would end resulting in the method returning to main with a value of 99 (or 1-4 if it's valid). Then I would call the method again at the end of each case.

Tots
Sep 3, 2007

:frogout:

Look Around You posted:

Well, why not pull the method out of the switch statement so that you're only using it at one point? Also, if you print a generic error on 99 and return it, when will your program halt? Is there another specific code to terminate?

Was going to put the switch in a while statement and end at -1, as it is in my original program.

If I only use it once, wouldn't I then have to put all the output associated with each case, as well as the incrementer that will keep track of how many time they are used, inside this new method?

Tots
Sep 3, 2007

:frogout:

Look Around You posted:

Oh, it looks like the cases are significantly different. One way to break it apart (and probably the best way for larger applications) would be to take each case and turn it into it's own function. That way you can just do case 1: calcManagerSalary(); break; case 2: calcBlahWages(); break; and move the actual logic for calculating the wages into their own functions. This has the side effect of being a lot easier to debug too. But yes, you would have to figure out a place to store the incrementers and increment it when you calculate that specific type of wage.

I am really tired right now, but I can't make sense of how this would work unless a method could return a string

E: Okay, yah I need to go to bed. They wouldn't need to return anything.

Good night.

Tots
Sep 3, 2007

:frogout:
Since my questions sparked the intro debate I should mention that I am in IST which is slightly different than CS. The introduction course for CS uses C++ as does the introduction course for students that aren't going into technology related major. Before taking this course which uses Java I had to take the generic intro which uses C++. That course just taught concepts like using variables and basic loops.

Tots
Sep 3, 2007

:frogout:
I'm reading through my Java book and one of the end of chapter questions has this example code in which I'm supposed to find the error:

code:
        for (k = .1 ; k != 1.0 ; k += .1)
            System.out.println( k );
Easy enough, k was never initialized... but wait! There appears to be a much more insidious error which I doubt the author intended.

The output of

code:
        for (double k = .1 ; k != 1.0 ; k += .1)
            System.out.println( k );
is:

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.0999999999999999
1.2
1.3
1.4000000000000001
1.5000000000000002
1.6000000000000003
1.7000000000000004
1.8000000000000005
1.9000000000000006
2.0000000000000004
...ad infinitum.

Can anyone tell me what the hell is going on here?

Tots
Sep 3, 2007

:frogout:
I'm trying to figure out a way to return the expected output based on that same for structure, but I can't think of anything that will work and not be absolutely retarded. Any ideas?

Tots
Sep 3, 2007

:frogout:
I get what you're all saying, but I was trying to achieve the exact output of .1 - .9 using that same basic for structure somehow... just because. Anyway, I thought about it for like half an hour then gave up after getting frustrated... My brain is sort of goop at this point from lack of sleep.


Anyway, turns out that the solution in the book doesn't actually say anything about initializing the value, rather it says "Don't use floating point numbers for a counter you fucktard." :downsgun:

code:
    public static void main(String[] args) {

        for (int k = 1 ;  k != 10 ; k += 1)
        {
            System.out.println( (double) k / 10);         
        }
        
    }
E: Just so you get an idea, I was trying to build a separate method that would take a value (say double 0.1) then compare it to a range (.05-.09 in this case) and then return .1 if it did fall within that range, I was also trying to make it to apply to any number that happened to be passed to the method, and somehow have it figure out the appropriate range to compare it to. Then when it returned the .1 (or whatever) again it would somehow have to magically not be hosed up like the double it originally evaluated. I can't wait to look at this gem a year down the road.

Tots fucked around with this message at 07:56 on Feb 26, 2012

Tots
Sep 3, 2007

:frogout:

Look Around You posted:

This would work.

If you're using Java 1.5+ you probably have a printf function:
Try System.out.printf("%.1f\n", k); (where k in here is a double).

That prints
1.0
2.0
etc...

I really need to sit down one night and learn all the printf poo poo. It looks ridiculously useful.

This works :haw:

code:
        for (int k = 1 ;  k != 10 ; k += 1)
        {
            System.out.println("0." + k);       
        }

Tots fucked around with this message at 08:31 on Feb 26, 2012

Tots
Sep 3, 2007

:frogout:

Look Around You posted:

I'm guessing you know that's not what you're looking for though, right?

The printf I had will work, but you need to cast your int into a double and divide by 10 again if you want to get the 0.1 etc... you were just passing it 1, 2, 3, [...] which got cast to doubles when passed to printf which is why it came out as 1.0, 2.0 [...]


e:


Yeah, that's not mathematically correct at all; it won't do what you're looking for... can you see why?

e2: also the initial implementation of the "range" test I put up was kind of flawed, I updated the post for a correct version that was suggested below it.
Well I know that it would just drop anything after the first decimal place with a number other than 0. I guess that could end up with either more or less precision than a predefined range

Tots
Sep 3, 2007

:frogout:

Look Around You posted:

What happens if you pass it a negative number?

Ah, didn't think of that.

Tots
Sep 3, 2007

:frogout:

Look Around You posted:

There's some other major flaws in it too though. Notice anything else?

(I'm not trying to be cryptic I'm just trying to get you thinking about it!)

Haha, no I know there is since it doesn't run. I really need to get to sleep though. I have work in the morning. Going to look at it again tomorrow.

Tots
Sep 3, 2007

:frogout:
Oh, no poo poo. Even if the difference is inconceivably small it will evaluate to true.

E: Really going to bed now. Thanks for the late night coding session once again.

oh loving christ and the fact that it doesn't take into account how many powers it removed

I'm going to chalk this up to being tired since they were both terribly obvious.

Tots fucked around with this message at 08:51 on Feb 26, 2012

Tots
Sep 3, 2007

:frogout:

Master_Odin posted:

For class, we're currently looking at caches, and just looked at profilers (in my case, it was gprof).

One of the questions was asking about this scenario:
code:
void foo()
{
  if(condition)
  {
    // large_code_block 1
  } else {
    // large_code_block 2
  }
}
vs
code:
void foo()
{
  if(condition)
  {
    // large_code_block 1
  } else {
    large_code_block2();
  }
}
The large "code" I'm running for the test cases is just simply
code:
for(int i = 0; i < 10000000000; i++);
After looking at it, the second scenario runs faster, with calling a procedure to run the same large code. It is faster running both statements of the condition (running 2 before 1) than the first example. I do not know or how to explain it and my teacher just said "think about it" instead of providing an answer, even when asked twice on something that isn't being graded or anything.
What's in the large code block? Specifically code block 2, since that seems to run the fastest

Tots
Sep 3, 2007

:frogout:
Where can I get a cheap or free off brand TLD domainname?

E: Nevermind, I just remembered I still own a domain name. Whoops :downs:

Adbot
ADBOT LOVES YOU

Tots
Sep 3, 2007

:frogout:

Gravity Pike posted:

Namecheap.com has some sort of $0.88/yr deal for some of the crappier TLDs right now. It looks like they probably pop up to $8-33/yr after the first year, where .com's are steady at $11.

Thanks, I might still check this out

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply