Java begineer problem
Page 1 of 2 Goto page 1, 2  Next
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Sun, 5th Sep 2010 18:11    Post subject: Java begineer problem
So yeah, picked up java 1-2 weeks ago and now i'm stuck on my first problem.

Basically I want to create a program where a window pops up and asks you to write code in the following way. HH:MM:SS. Once you've done that another window should pop up where the info is showed in the following way:

3 hours
4 minutes
22 seconds.

Now the problem i'm having is that the text is shown the following way.

3 hours
:4 minutes
:22 seconds

I've been through the code over and over and i can't see where i went wrong. it seems quite logical to me but there's probably a small detail that is most likely evident for you guys. NOTE: I haven't added the hours, seconds, minutes text yet to the end message.

code:

Code:

   1.
      import javax.swing.*;
   2.
       
   3.
      public class Marathon {
   4.
              public static void main (String[] arg) {
   5.
                      String a;
   6.
                      a = JOptionPane.showInputDialog("Write time in format: TT:MM:SS");
   7.
                      int b = a.indexOf(':');
   8.
                      int c = a.lastIndexOf(':');
   9.
                      String d;
  10.
                      d = a.substring(0, b);
  11.
                      String e;
  12.
                      e = a.substring(b, c);
  13.
                      String f;
  14.
                      f = a.substring(c);
  15.
                      String g;
  16.
                      g = d + "\n" + e + "\n" + f;
  17.
                      JOptionPane.showMessageDialog(null, g);
  18.
                      System.exit(0);
  19.
      }
  20.
      }


Thanks.
Back to top
me7




Posts: 3936

PostPosted: Sun, 5th Sep 2010 18:20    Post subject:
Correction:

12. e = a.substring(b+1, c);
14. f = a.substring(c+1);

Edit: I forgot to explain, b and c are the indexes of the ':' character but you don't want this character included in your output, so you want to begin with the character that comes AFTER the index of ':'. Got it?


Last edited by me7 on Sun, 5th Sep 2010 18:23; edited 1 time in total
Back to top
LeoNatan
Banned



Posts: 73193
Location: Ramat Gan, Israel 🇮🇱
PostPosted: Sun, 5th Sep 2010 18:22    Post subject:
Why not just split the string:

Code:
String[] results = a.split(":");

String output = results[0] + " hours\n" + results[1] + " minutes\n" + results[2] + " seconds";
JOptionPane.showMessageDialog(null, output);

Anyway, in your method, try

Code:
e = a.substring(b + 1, c);
...
f = a.substring(c + 1);

You want to take the string from one place after the index of the ":".

BTW, naming parameters "a" "b" "c" is a really bad habit, one you should avoid very dearly.
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Sun, 5th Sep 2010 18:28    Post subject:
Ah I see, didn't know that you could use +1 in substring.

Thanks for the help guys.

Also iNatan, how should i name the strings then? I'm new so any tips to avoid future bad habits is welcomed.
Back to top
LeoNatan
Banned



Posts: 73193
Location: Ramat Gan, Israel 🇮🇱
PostPosted: Sun, 5th Sep 2010 18:40    Post subject:
You should always give them a meaningful name.

For example:

Code:
String input = JOptionPane.showInputDialog("Write time in format: TT:MM:SS");
int indexHours = input.indexOf(':');
int indexMinutes = input.lastIndexOf(':');
String hours = input.substring(0, indexHours);
String minutes = index.substring(indexHours + 1, indexMinutes);
String seconds = index.substring(indexMinutes + 1);
String output = hours + "\n" + minutes + "\n" + seconds;
JOptionPane.showMessageDialog(null, output);

That way you never have a variable or parameter which you have no clue what it is. With modern IDEs you don't have to worry about typing too much, so don't worry about length (within reason, of course). It is important to be as descriptive as possible so you can remember what each variable is the instant you see it.
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Sun, 5th Sep 2010 18:46    Post subject:
iNatan wrote:
You should always give them a meaningful name.

For example:

Code:
String input = JOptionPane.showInputDialog("Write time in format: TT:MM:SS");
int indexHours = input.indexOf(':');
int indexMinutes = input.lastIndexOf(':');
String hours = input.substring(0, indexHours);
String minutes = index.substring(indexHours + 1, indexMinutes);
String seconds = index.substring(indexMinutes + 1);
String output = hours + "\n" + minutes + "\n" + seconds;
JOptionPane.showMessageDialog(null, output);

That way you never have a variable or parameter which you have no clue what it is. With modern IDEs you don't have to worry about typing too much, so don't worry about length (within reason, of course). It is important to be as descriptive as possible so you can remember what each variable is the instant you see it.



Ah okay that's true, makes more sense.

I'll keep it in mind, thanks for the tip.
Back to top
Werelds
Special Little Man



Posts: 15098
Location: 0100111001001100
PostPosted: Sun, 5th Sep 2010 19:11    Post subject:
Another thing Leo does but doesn't explain there is using camelCase. What that means is that each word within a variable name starts with a capital letter; again, increases readability. Which would you prefer: someverylongunusableandutterlyuselessvariablename or someVeryLongUnusableAndUtterlyUselessVariableName? Bullshit example, but you get the point

Every language has its own guidelines for using capital letters and naming and such, for Java check out this, and specifically this one. Second one is more relevant to you, because that contains stuff you'll be dealing with already Smile

One thing I personally can't stand, and I think Leo is with me on this: some programmers use a prefix for the variable type; i.e. strSomeString and intSomeInteger (or shorthand; s for str and i for int). It's something most programmers are against these days for various reasons, so please don't start doing that Very Happy
Back to top
LeoNatan
Banned



Posts: 73193
Location: Ramat Gan, Israel 🇮🇱
PostPosted: Sun, 5th Sep 2010 19:29    Post subject:
Dear lord, I absolutely can't stand some C++ naming conventions:

Code:
class Shit {
    public:
      int m_nIntegerShit;
      float m_fFloatShit;
      bool m_bBoolShit;
};

Can really drive me to:

 Spoiler:
 


Can't say I'm a fan of Java's naming convention either, but still a lot better. For me, the .NET one is the most comfortable and readable. It really felt natural when I started coding in .NET.
Back to top
Werelds
Special Little Man



Posts: 15098
Location: 0100111001001100
PostPosted: Sun, 5th Sep 2010 21:05    Post subject:
I personally don't mind Java's style, but I'm also used to working in at least 3 different languages for different projects at any given time anyway

The biggest problem for me is that my fellow students all fail at having a proper coding style. Apart from readability, most aren't even consistent in how they name variables/classes/constants/whatever. Some of them start everything with a capital letter for example, and mix English/Dutch names in their code (i.e. they copy/paste the English bits and don't bother to change it). Really annoying.
Back to top
me7




Posts: 3936

PostPosted: Sun, 5th Sep 2010 21:09    Post subject:
Razacka2 wrote:
Ah I see, didn't know that you could use +1 in substring.


This has nothing to do with substring supporting "+1". Substring just requires an integer and the addition operator returns an integer. This isn't limited to substring either, any method that requires an integer can be used that way.
Just be careful with mathematical operations that can return a float or double. "c / 3" for example should return an integer since both "c" and "3" are integers. But "c / 3.0" could be dangerous, what happens in that case depends on the programming language.

Keep it up Wink
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Thu, 16th Sep 2010 20:22    Post subject:
I've run into a new problem that is bugging me and for the love of it i can't figure it out.


Code:

import javax.swing.*;

public class Matteprov {
   public static void main (String[] arg) {
      String Input;
      Input = JOptionPane.showInputDialog("Hur mÃ¥nga poäng fick eleven pÃ¥ provet?");
      double Input2 = Double.parseDouble(Input);
      //String Output;

      if (Input2 < 25) {
         Output = "IG";
         JOptionPane.showMessageDialog(null,"Följande elev fÃ¥r " + Output);
        }
      else if (25 =< Input2 < 35) {
         Output = "G";
         JOptionPane.showMessageDialog(null,"Följande elev fÃ¥r " + Output);
        }
      else if ( 35 =< Input2 < 45 ) {
          Output = "VG";
          JOptionPane.showMessageDialog(null,"Följande elev fÃ¥r " + Output);
      }
      else {
          Output = "MVG";
          JOptionPane.showMessageDialog(null,"Följande elev fÃ¥r " + Output);
      }
      
      
     System.exit(0);

  }
}


The program is supposed to take in a certain value and then determine what grade it is according to the swedish system. The error appears in line 14, saying " illegal start of type". I'm not sure how to fix it, any ideas?
Back to top
me7




Posts: 3936

PostPosted: Thu, 16th Sep 2010 20:34    Post subject:
Try: else if (25 =< Input2 && input2 < 35)

'&&' is the boolean AND operator.
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Thu, 16th Sep 2010 20:42    Post subject:
now it says that "> is expected" on the same line. i don't get where to place it..

why am i not getting this error at line 18 as well? its essentially the same function just different values.
Back to top
PumpAction
[Schmadmin]



Posts: 26759

PostPosted: Thu, 16th Sep 2010 21:28    Post subject:
Code:

public class Matteprov {
   public static void main (String[] arg) {
      double input = Double.parseDouble(JOptionPane.showInputDialog("Hur mÃ¥nga poäng fick eleven pÃ¥ provet?"));
      String output;
     
      if (input<25){
            output = "IG";
      } else {
            if (input <35){
                  output = "G";
            } else {
                   if (input <45){
                        output = "VG";
                  } else {
                        output = "MVG";
                  }
            }
      }
     JOptionPane.showMessageDialog(null,"Följande elev fÃ¥r " + output);
     System.exit(0);

  }
}


There is no need to check if input is bigger than 25 and smaller than 35 because if it's not smaller you are already in the else case thus it must be bigger! and if it's not smaller than 35 then just check if it's smaller then 45 and if it's still not smaller you'll have mvg. pretty easy Smile

And there is no 1<=i<=5 or else if in java as far as i know Smile

Remember to use LOWERCASE variable names! And don't use input or input5 Laughing use grade or something more descriptive...


=> NFOrce GIF plugin <= - Ryzen 3800X, 16GB DDR4-3200, Sapphire 5700XT Pulse
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Thu, 16th Sep 2010 21:56    Post subject:
ah okay, i guess i was thinking in mathematical terms more then logical.

also why should i use lowercase variable names?

thanks for the help.
Back to top
me7




Posts: 3936

PostPosted: Thu, 16th Sep 2010 23:27    Post subject:
Razacka2 wrote:
now it says that "> is expected" on the same line. i don't get where to place it..

why am i not getting this error at line 18 as well? its essentially the same function just different values.


Sorry, Java doesn't know '=<', you need to write '<='.

And you should use lowercase (with camelNotationForMultipleWords) because it's Java convention and other devs expect it when they read your code. Uppercase is "reserved" for classes.
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Mon, 25th Oct 2010 22:12    Post subject:
I'm wondering if you guys have any ideas on begineer problems and projects I could work on, maybe you know a site that offers these kind of exercises? I'm kind of limited by my creativity right now and unsure of what to code and so on. Just started learning about try, catch and so on so i'm still a beginner.

I checked out projecteuler.net but I'd rather avoid mathematical problems as I've got more then enough of them in coursebook. Don't get me wrong, I have nothing against a problem dealing with maths but i'd like there to be a certain idea (eg, construct a program that decides what insurance you should get based by certain values you put in etc.)

Thanks!
Back to top
BearishSun




Posts: 4484

PostPosted: Tue, 26th Oct 2010 00:27    Post subject:
Get a good beginner java book and go through it, and try to implement all of the examples in the book yourself.

Once you have basic knowledge of java go ahead and choose a branch of CS you want to work on specifically (security, artificial intelligence(has plenty of sub-fields like data mining, pattern recognition, natural language recognition), computer graphics, networks, algorithms, operating systems, etc.).

Then I suggest you find a programming book meant specifically for that topic and you'll find plenty of projects to work on.

After you're done with books, you can find many scientific papers with new techniques in the field, but I don't suggest you even look at them until you have a pretty good grasp on the basics, as they generally hide the implementation details.
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Tue, 26th Oct 2010 16:38    Post subject:
BearishSun wrote:
Get a good beginner java book and go through it, and try to implement all of the examples in the book yourself.

Once you have basic knowledge of java go ahead and choose a branch of CS you want to work on specifically (security, artificial intelligence(has plenty of sub-fields like data mining, pattern recognition, natural language recognition), computer graphics, networks, algorithms, operating systems, etc.).

Then I suggest you find a programming book meant specifically for that topic and you'll find plenty of projects to work on.

After you're done with books, you can find many scientific papers with new techniques in the field, but I don't suggest you even look at them until you have a pretty good grasp on the basics, as they generally hide the implementation details.


How do you know when to branch into something specifically? Is there a deadend which you reach where you need to pick some subcategory to learn more about in order to do specific things?

Sorry for the tedious questions, just sounded really interesting when you started talking about different branches and picking one.
Back to top
BearishSun




Posts: 4484

PostPosted: Tue, 26th Oct 2010 16:56    Post subject:
After being a programmer for a few years you'll realize that there isn't much to learn anymore as far as programming itself is concerned. Programming is just a tool used for making something bigger. All languages have the pretty much same underlying concepts and once you truly understand one you understand them all.

And choosing a branch will keep you more productive. If you choose something that sounds cool and interesting to you, you'll want to work on it a lot, and you'll learn a lot of new things. But this is something that will come natural to you in time, and you shouldn't worry about anything than learning the language for now.
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Wed, 8th Dec 2010 20:01    Post subject:
I'm trying to solve this problem but im unsure of what to do, i asked Leo as well but he seems busy so i don't wish to take his time so i thought i'd try my luck here.

the problem :

"A method to simulate exponential decline is to roll 100 dices and remove all sixes. Then you roll the remaining dices and remove all sixes etc.

Write a program that simulates exponential growth according to the model above.
TIP : Use two for loops and an if loop or whatever you call it.
Simulation of a dice can be written as : (int)(6 * Math.random() + 1)

So if we write it down in pseudo code:

1. Roll a certain amount of dices ( 100 in our case)
2. Write out the amount of rolled dices in a text window (JOptionPane.showMessageDialog)
3. Count the amount of sixes that have been rolled.
4.Remove the same amount of dices as the amount of rolled sixes.
5. Do step 1-4 10 times.
6. write out the result.
"

This is how far i've gotten :

Code:

import java.util.StringTokenizer;

import javax.swing.*;
      
public class Proguppgift866 {
   public static void main(String[] arg) {
      Integer dice =(int) (6 * Math.random() + 1);
      String total = "";
      
      for(int i = 1; i <= 100; i++) {
      Integer dice1 =(int) (6 * Math.random() + 1);
      total = total + " " + dice1;
      }
      JOptionPane.showMessageDialog(null,"100 dices have been thrown");
      
      StringTokenizer t = new StringTokenizer(total);
      int n = 6;
      int dices = 100;
      while (t.hasMoreTokens()) {
         if(t.nextToken().equals(6))
            dices = dices -1;
      }

      
      
      }
   }
   


Any ideas?
Back to top
me7




Posts: 3936

PostPosted: Wed, 8th Dec 2010 20:20    Post subject:
First nest all of it in a for loop that loops ten times. Then replace "100 dices have been thrown" with a more dynamic message that uses a variable of your code to print the actual amount.
This should point you in the right direction.
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Wed, 8th Dec 2010 20:52    Post subject:
me7 wrote:
First nest all of it in a for loop that loops ten times. Then replace "100 dices have been thrown" with a more dynamic message that uses a variable of your code to print the actual amount.
This should point you in the right direction.


I see, what do you think about the removal of dices that equal 6? I am a bit unsure of how to do that step. Also how am I gonna remove dices for every step when i loop everything together 10 times?

Because the end result window will look something like this:

Exponential decline :

100
84
73
60
50
44
etc for ten steps.
Back to top
me7




Posts: 3936

PostPosted: Wed, 8th Dec 2010 21:10    Post subject:
I'd do it this way:

Code:

int dices = 100;

for (int i = 0; i < 10; i++)
{
    System.out.println("There are " + dices + " dices");
   
    int remove = 0;
    for (int j = 0; j < dices; j++)
    {
        int dice = (int) (6 * Math.random() + 1);
        if (dice == 6)
        {
            remove++;
        }
    }
    dices = dices - remove;
}
Back to top
Werelds
Special Little Man



Posts: 15098
Location: 0100111001001100
PostPosted: Wed, 8th Dec 2010 21:14    Post subject:
Start by storing the rolled values into an array rather than appending them to a string Smile

Allows you to easily get rid of specific values, or a specific number of values, etcetera. A string is rarely the datatype you want to be working with, that's usually the last conversion you do in order to display it to the user, and even then it's often done implicitly Smile

I'd personally get some recursion going for stuff like this, but the quick and dirty way is indeed to nest several for loops. One big one that goes around 10 times, then a couple of ones inside that to roll x times, followed by one that loops over all the results to check for sixes.
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Wed, 8th Dec 2010 21:16    Post subject:
I don't know what an array is, seems like that is unfortunate in my case. I'll try what you wrote me7. thanks.
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Wed, 8th Dec 2010 21:38    Post subject:
Thanks though when I write it out in a complete table the 100 doesn't come with so I had to revise the code you sent:

Code:

import java.util.StringTokenizer;

import javax.swing.*;
      
public class Proguppgift866 {
   public static void main(String[] arg) {
      
      int dices = 100;
      String table = "";
      for (int i = 0; i < 9; i++)
      {
         
          int remove = 0;
          for (int j = 0; j < dices; j++)
          {
              int dice1 = (int) (6 * Math.random() + 1);
              if (dice1 == 6)
              {
                  remove++;
              }
          }
          dices = dices - remove;
          table = table + "\n" + dices;
      }
      String completetable ="Exponential Decline" + "\n" + "---------------------" + "\n"+ 100 +  table;
      JOptionPane.showMessageDialog(null,completetable);
      System.exit(0);
      
      }

      
      
      }

   


I had to add + 100 manually in the completetable string and reduce the big loop to 9 times. maybe there is a more proper fix then what I did? But generally you will always have 100 in the first step so it should be valid right? Reason I also reduced it to 9 loops is that with 100 you'll have 10 steps total. if i have 10 loops i'll have 11.

What do you think? Thanks a lot me7, really appreciate it. very elegant fix. Would have never seen it myself Sad
Back to top
me7




Posts: 3936

PostPosted: Wed, 8th Dec 2010 21:45    Post subject:
My original code works for me, this is the output I get on the console:
Code:
There are 100 dices
There are 92 dices
There are 78 dices
There are 67 dices
There are 56 dices
There are 43 dices
There are 35 dices
There are 32 dices
There are 24 dices
There are 20 dices


Maybe "JOptionPane.showMessageDialog()" screws things up, I hardly ever used Java for GUI applications so I don't know.

...and what's the lesson, kids? Just because you need to calculate 100 rolled dices you don't really need a data structure to store all 100 values. Read the exercise more carefully next time Wink
Back to top
Razacka2




Posts: 2832
Location: Sweden
PostPosted: Wed, 8th Dec 2010 22:20    Post subject:
Another problem: "A sum that converges very slowly towards pi can be written like this: pi = (4/1) - (4/3) + (4/5) - (4/7) + .... Write a program which determines how many terms you need to add to reach pi with 6 correct decimals ( 3.141592). TIP: use a while loop. set (diff>0.0000005) in the while loop"

I solved it like this:

Code:


import javax.swing.*;

public class Proguppgift855 {
   public static void main(String[] arg) {
      int n = 0;
      double s = 0;
      
      while (Math.abs(Math.PI-s) > 0.0000005) {
      s = s + (Math.pow((-1), n) * 4)/(2*n+1);
      n= n+1;
      
      
      }
      JOptionPane.showMessageDialog(null, n );
      System.exit(0);
   }
   
}


What do you guys think? Did I do it right or is there another cleaner way to do it?
Back to top
me7




Posts: 3936

PostPosted: Wed, 8th Dec 2010 22:38    Post subject:
Looks very clean, good job
Back to top
Page 1 of 2 All times are GMT + 1 Hour
NFOHump.com Forum Index - Programmers Corner Goto page 1, 2  Next
Signature/Avatar nuking: none (can be changed in your profile)  


Display posts from previous:   

Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB 2.0.8 © 2001, 2002 phpBB Group