Jump to content

SimpleJavaProgram

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
Sha01001

Sha01001

    Newbie

  • Members
  • Pip
  • 2 posts
Hello I just started programming and have got stuck on a question that asks you to print the three digits of the number 278 in this format

The first didit is: 2
The second didgit is: 7
The third didgit is: 2

Using a Maximum of two Variables. The part that is getting me is the two Variables I was able to do it using 4 but cant figure out who to do it with 2. If anyone culd help me I'd really apreciate it.

This is how I have it done

public class DetermineDigits{
public static void main (String[] args)
{
int num=278, num1, num2, num3;

num1= num/100;
num2=(num%100)/10;
num3= num%10;
System.out.println("The digits in the three digit number 278 are "+ "\n"+ num1+"\n" +num2+ "\n" +num3);
}
}

#2
Roman Y

Roman Y

    Programmer

  • Members
  • PipPipPipPip
  • 189 posts
well there is a number of ways to do that depending on the specifics but the closest I come to your way would be to have one temporery variable:

public class DetermineDigits

{

   public static void main(String[] args)

   {

      int num1 = 278, num2;

      num2 = num1/100;

      System.out.println("The digits in the three digit number 278 are:\nThe first didit is: " + num2);

      num2 = (num1%100)/10;

      System.out.println("\nThe second didit is: " + num2);

      num2 = num%10;

      System.out.println("\nThe third digit is: " + num2);

   }

}


It can even be done with only one variable (which is kind of better) if you do the mathematical stuf inside the print method:

public class DetermineDigits

{

   public static void main(String[] args)

   {

      int num1 = 278;

      System.out.println("The digits in the three digit number 278 are:\nThe first didit is: " + (num1/100));

      System.out.println("\nThe second didit is: " + ((num1%100)/10));

      System.out.println("\nThe third digit is: " + (num%10));

   }

}

other than that I can't really say without having more specifics... it can be done by working with the String instead of mathematical approach...

#3
Sha01001

Sha01001

    Newbie

  • Members
  • Pip
  • 2 posts
Thank you so much.

#4
jun71178

jun71178

    Newbie

  • Members
  • PipPip
  • 17 posts
with correction sir........ num2 = num%10; ......it should be num2 = num1%10; and System.out.println("\nThe third digit is: " + (num%10)); it should be System.out.println("\nThe third digit is: " + (num1%10));