Results 1 to 15 of 15
Like Tree3Likes
  • 1 Post By JosAH
  • 1 Post By JosAH
  • 1 Post By kneitzel

Thread: I have a question regarding a simple code in JAVA

  1. #1
    yakirbu is offline Member
    Join Date
    Apr 2014
    Posts
    5
    Rep Power
    0

    Default I have a question regarding a simple code in JAVA

    I'm currently learning JAVA and I decided to make a little test to see my knowledge.
    I wanted to write a simple code that receives information from the user (double-digit number and above) and calculates it's numbers.
    For instance- The user wrote a number- 234, the software will return the number 9 (2+3+4 = 9).
    Tried to use a loop for that, but I got stuck since I didn't know what to write.
    I"ll be glad if you can help.

    This is what I've wrote so far

    Java Code:
    import java.util.Scanner;
    public class Calculate {
    
    
    	public static void main(String[] args) {
    		System.out.println("Please type a number larger than 9");
    		Scanner type = new Scanner(System.in);
    		String number1 = type.nextLine();
    		
    		for( int i = 0; i < number1.length(); i++ ){
    		
    		    int calculate = number1.charAt(i);
    		    }
    	}
    }
    Thanks.

  2. #2
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    272
    Rep Power
    7

    Default Re: I have a question regarding a simple code in JAVA

    the charAt(..) method returns a char

    You can use Character.getNumericValue(..) method to get the int value of each digit and add them in every iteration.

  3. #3
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    6

    Default Re: I have a question regarding a simple code in JAVA

    In addition to superhaNds:

    You could also think about getting the number as an Integer instead of a String (nextInt instead of nextLine). Then you can get all digits in a loop like
    while (number > 0) {
    nextDigit = number % 10;
    number = number / 10;
    }

    So with the module operation you get the first character (from right to left!) and then you divide by 10 to get the remaining characters.

    Just as an alternative. (So maybe you want to try and write a method int crossSum(int number)?

    With kind regards,

    Konrad

  4. #4
    yakirbu is offline Member
    Join Date
    Apr 2014
    Posts
    5
    Rep Power
    0

    Default Re: I have a question regarding a simple code in JAVA

    Quote Originally Posted by kneitzel View Post
    In addition to superhaNds:

    You could also think about getting the number as an Integer instead of a String (nextInt instead of nextLine). Then you can get all digits in a loop like
    while (number > 0) {
    nextDigit = number % 10;
    number = number / 10;
    }

    So with the module operation you get the first character (from right to left!) and then you divide by 10 to get the remaining characters.

    Just as an alternative. (So maybe you want to try and write a method int crossSum(int number)?

    With kind regards,

    Konrad
    Can you write this code? I keep getting error when I use your method.

  5. #5
    lime is offline Member
    Join Date
    Apr 2014
    Posts
    16
    Rep Power
    0

    Default Re: I have a question regarding a simple code in JAVA

    you can use this code:
    public static void main(String[] args) {
    System.out.println("Please type a number larger than 9");
    Scanner s = new Scanner(System.in);
    String line = s.nextLine();
    int result = 0;

    for(int i = 0; i < line.length(); i++) {
    int n = line.charAt(i) - 48;
    result += n;
    }
    System.out.println(result);
    }
    I think the best way is to read the line into string as you did at first, and then simply cast characters to int. You also have to subtract value 48 because charAt returns the decimal value of the character. (see asciitable)

  6. #6
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    6

    Default Re: I have a question regarding a simple code in JAVA

    Hi,

    what kind of error do you get? I just gave a short code extract that is not a method. And I didn't define any variable. But my code should work quite fine. If you want to see how it works, then you could simply modify it a little bit:

    Java Code:
    		int number = 123; // Just defined the number
    		while (number > 0) {
    			System.out.print("Digit: " + number % 10); // Now I simply print out the digit!
    			number = number / 10;
    			System.out.println("  Number left: " + number);
    		}
    So the code is more or less the same but now you can copy & paste it to your main method if you want to play around with it.

    (And maybe you try to build the method to calculate the cross number. If oyu get any error: Please tell us the error and maybe the exact code you tried. Then we can help you further.)

    With kind regards,

    Konrad

  7. #7
    yakirbu is offline Member
    Join Date
    Apr 2014
    Posts
    5
    Rep Power
    0

    Default Re: I have a question regarding a simple code in JAVA

    Quote Originally Posted by lime View Post
    you can use this code:

    I think the best way is to read the line into string as you did at first, and then simply cast characters to int. You also have to subtract value 48 because charAt returns the decimal value of the character. (see asciitable)
    You're right. it works great. I understand it all except the subtraction of the value 48, why did you choose 48 and how does it makes a difference?

  8. #8
    lime is offline Member
    Join Date
    Apr 2014
    Posts
    16
    Rep Power
    0

    Default Re: I have a question regarding a simple code in JAVA

    see Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion
    -look at the numeric characters with red font colour, the method charAt() returns the decimal value of the characters (it's first column) - so for number 1 it will return value 49...simply, each character has its own ascii value

  9. #9
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    6

    Default Re: I have a question regarding a simple code in JAVA

    If you want to code it that way, then please check that it is really a number. So add a check that it is >= 48 and <= 57. If it is not, then you got an illegal input.

    With kind regards,

    Konrad

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: I have a question regarding a simple code in JAVA

    When using ASCII characters in math operations it helps to document the code better to use '0' and '9'. In addition, you don't need to remember the ASCII chart.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  11. #11
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: I have a question regarding a simple code in JAVA

    Using the ascii (or unicode) code of the individual characters is clumsy; aamof using a loop is clumsy too; this little problem begs for a bit of recursion: if the number is a single digit, the result is that digit, otherwise add the rightmost digit to the result as if the rightmost digit wasn't there, i.e. C(123) == C(12)+3 = C(1)+C(2)+C(3) == 1+2+3 == 6; in code:

    Java Code:
    public int C(int n) {
       if (n <= 9) return n;
       return n%10+C(n/10);
    }
    ... assuming that n >= 0.

    kind regards,

    Jos
    milovan likes this.
    Build a wall around Donald Trump; I'll pay for it.

  12. #12
    yakirbu is offline Member
    Join Date
    Apr 2014
    Posts
    5
    Rep Power
    0

    Default Re: I have a question regarding a simple code in JAVA

    Quote Originally Posted by JosAH View Post
    Using the ascii (or unicode) code of the individual characters is clumsy; aamof using a loop is clumsy too; this little problem begs for a bit of recursion: if the number is a single digit, the result is that digit, otherwise add the rightmost digit to the result as if the rightmost digit wasn't there, i.e. C(123) == C(12)+3 = C(1)+C(2)+C(3) == 1+2+3 == 6; in code:

    Java Code:
    public int C(int n) {
       if (n <= 9) return n;
       return n%10+C(n/10);
    }
    ... assuming that n >= 0.

    kind regards,

    Jos
    Very nice,
    Thanks.

    Edit: why did you define the 'int n' like this: 'public int C(int n)' i.e like a class, you couldn't just wrote 'int n'?
    Last edited by yakirbu; 04-21-2014 at 11:40 AM.

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: I have a question regarding a simple code in JAVA

    Quote Originally Posted by yakirbu View Post
    Edit: why did you define the 'int n' like this: 'public int C(int n)' i.e like a class, you couldn't just wrote 'int n'?
    That's not a class, it's a method named 'C' and it takes a parameter 'n' which is an int.

    kind regards,

    Jos
    yakirbu likes this.
    Build a wall around Donald Trump; I'll pay for it.

  14. #14
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    6

    Default Re: I have a question regarding a simple code in JAVA

    Hi,

    that is definition of the function. That way you get a function called C. If you just wrote something like "int n = 123" and remove the { } from the code than you get a piece of code that is doing the calculation. But you should try to keep parts of code readable and small so it is always a good thing to move such things into functions (that get a name that describes what the function is doing!).

    And I am not sure what I prefer. The recursion is quite nice but I think I like the while loop more even if it has a few lines more.

    So the 2 function to compare would be:
    Java Code:
    	public static int crossNumber(int number) {
    		int result = 0;
    		while (number > 0) {
    			result += number % 10;
    			number = number / 10;
    		}
    		return result;
    	}
    Java Code:
    	public static int crossNumber(int number) {
    		if (number <= 9) return number;
    		return (number % 10) + crossNumber(number / 10);
    	}
    the last code is quite small but I find it harder to understand. But that is just my personal optinion and everyone else might see it different (which is completly ok!).

    With kind regards,

    Konrad
    yakirbu likes this.

  15. #15
    yakirbu is offline Member
    Join Date
    Apr 2014
    Posts
    5
    Rep Power
    0

    Default Re: I have a question regarding a simple code in JAVA

    Quote Originally Posted by JosAH View Post
    That's not a class, it's a method named 'C' and it takes a parameter 'n' which is an int.

    kind regards,

    Jos
    Quote Originally Posted by kneitzel View Post
    Hi,

    that is definition of the function. That way you get a function called C. If you just wrote something like "int n = 123" and remove the { } from the code than you get a piece of code that is doing the calculation. But you should try to keep parts of code readable and small so it is always a good thing to move such things into functions (that get a name that describes what the function is doing!).

    And I am not sure what I prefer. The recursion is quite nice but I think I like the while loop more even if it has a few lines more.

    So the 2 function to compare would be:
    Java Code:
    	public static int crossNumber(int number) {
    		int result = 0;
    		while (number > 0) {
    			result += number % 10;
    			number = number / 10;
    		}
    		return result;
    	}
    Java Code:
    	public static int crossNumber(int number) {
    		if (number <= 9) return number;
    		return (number % 10) + crossNumber(number / 10);
    	}
    the last code is quite small but I find it harder to understand. But that is just my personal optinion and everyone else might see it different (which is completly ok!).

    With kind regards,

    Konrad
    Thank you both, always nice to see different ways to get the same answer.

Similar Threads

  1. Just a simple question about a Java Programm
    By thomason93 in forum New To Java
    Replies: 8
    Last Post: 03-26-2014, 02:39 PM
  2. Simple question about array in JAVA
    By hills2720s in forum New To Java
    Replies: 10
    Last Post: 10-17-2013, 04:14 AM
  3. Simple Java question
    By devinmont in forum New To Java
    Replies: 1
    Last Post: 09-11-2012, 11:15 PM
  4. Quick question about this simple code..
    By shroomiin in forum New To Java
    Replies: 2
    Last Post: 11-10-2009, 06:58 PM
  5. Replies: 1
    Last Post: 10-02-2008, 04:06 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •