Below you will find sample codes for reference to perform basic functions like printing or finding out whether a number is odd or even using Java. For codes using string functions, click here
To print:
System.out.println()
Place the things you want to print inside of the brackets. If you want to print a set of characters, place them inside " ".
Eg: To print Hello World!
System.out.println("Hello World!");
To find out if a number is even:
Let the number be stored in the variable num
if(num%2==0)
//if this is true, the code inside the if block will execute and you will know that your number is even
To find out if a number is odd:
Let the number be stored in the variable num
if(num%2==1)
//if this is true, the code inside the if block will execute and you will know that your number is odd
To extract the last digit of a number without using String methods:
while(num%10!=num) or while(num!=0)
{
int storesDigit=num%10;//
this stores the last digit of the of the number.
num=num/10;// t
his removes that last digit so the next time you can get the digit before that.
}
By using this base code, you can add different lines of code between those two lines in order to suit your needs regarding the output of the program.
To accept input using Scanner class:
Scanner in=new Scanner(System.in);// initialize Scanner
Note: The in can be replaced by any word other than a reserved word (keyword). One just has to make sure that Scanner is initialized using the same variable.
To find average:
public double average(int first, int last)
{
double s=0; // Made double so we get double type quotient in the end
int d=0;
for(int i=first;i<=last;i++)
{
s+=scores[i]; //keeps track of sum
d++; //keeps track of number of values
}
return s/d;
}