0
JAVA
write a program witch absorbs a 3 digits number. the program will make sure the number has only 3 digits. if it does ,the program will print the avg of the numbers. my code: System.out.println("enter a 3digits number:"); int digits3 = input.nextInt(); int length; length = String.valueOf(input).length(); if (length == 3) { System.out.println("your number is:"); } else if (length < 0 ) { System.out.println("erorr"); } else if (length > 3) { System.out.println("error"); } im realy at the begining of java study, please help!
3 Antworten
+ 2
//Here is the solution of your problem
// To check it just copy it and run
import java.util.*;
import java.lang.*;
class Rextester
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("enter a 3 digits number:");
int digits3 =input.nextInt();
int length;
length = String.valueOf(digits3).length();
String num = String.valueOf(digits3);
if (length == 3) {
System.out.println("your number is:"+digits3);
}
else if (length < 0 ) {
System.out.println("erorr");
}
else if (length > 3) {
System.out.println("error");
}
System.out.print("Average of the Number\'s digit is "+(Character.getNumericValue (num.charAt(0))+Character.getNumericValue (num.charAt(1))+Character.getNumericValue (num.charAt(2))));
}
}
//If you have any doubt you can ask.
//Hope this helps😀
+ 1
I'm assuming you've importet java.util.Scanner and made one named input.
A much easier way to check if the number is 3 digits is to check if the digits3 >= 100.
If you need leading zeroes, (i.e. 023) you will have to take the input as a string first and check length.
So:
if(digits3 >= 0){
//get average
} else {
//error
}
OR
if(digits3.length() == 3){
// get average
} else {
// error
}
To get the average, loop through the number 3 times. Use modulus to get a digit, and integer division to then remove it.
int Sum = 0;
int Avg = 0;
for(int i = 1; i <= 3; i++){
sum += (digits3 % 10); //modular division gives the remainder
}
Avg = sum/3;
System.out.println(avg);
Hope tjis helps
0
thank you both ,help me elot !