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);
}
}
SimpleJavaProgram
Started by Sha01001, Oct 13 2010 10:19 AM
3 replies to this topic
#1
Posted 13 October 2010 - 10:19 AM
|
|
|
#2
Posted 13 October 2010 - 11:00 AM
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:
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, 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
Posted 13 October 2010 - 11:08 AM
Thank you so much.
#4
Posted 26 October 2010 - 07:08 AM
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));


Sign In
Create Account

Back to top









