How do you divide all the input integers in an array? I have this method called division. It only gets the sum of the integers I've input. How do divide them?
public class Arithmetic {
public int division(int[] n) {
int quotient = 0;
for (int num : n) {
quotient = quotient / num;
}
return sum;
}
public static void main(String[] args) throws IOException {
Arithmetic a = new Arithmetic();
Scanner sc = new Scanner(System.in);
System.out.println("1: Division");
System.out.print("Enter selection here: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter no. of elements you want in array: ");
int numOfElements = sc.nextInt();
System.out.println("Enter elements in the array ~ ");
if (sc.hasNextInt()) {
int arraysInput[] = new int[numOfElements];
for (int i = 0; i < numOfElements; i++) {
arraysInput[i] = sc.nextInt();
}
System.out.println("Quotient: " + a.division(arraysInput));
}
}
}
}
The accepted answer will not work. Unfortunately I don't have enough "rep" to post comments.
for reference:
public int division(int[] n) {
int quotient = n[0] ;
for (int i = 1; i < n.length ; i++) {
quotient = quotient / n[i];
}
return quotient;
}
You need to change your division method with this
public int division(int[] n) {
int quotient = n[0] ;
for (int i = 1; i < n.length ; i++) {
quotient = quotient / n[i];
}
return quotient;
}
The whole class looks like with some test code :
public class Arithmetic {
public int division(int[] n) {
int quotient = n[0] ;
for (int i = 1; i < n.length ; i++) {
quotient = quotient / n[i];
}
return quotient;
}
public static void main(String[] args) throws IOException {
Arithmetic a = new Arithmetic();
Scanner sc = new Scanner(System.in);
// Test Division
// System.out.println( "Divison of {10,5,1} : " + a.division(new int[]{10,5,1}));
System.out.println("1: Division");
System.out.print("Enter selection here: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter no. of elements you want in array: ");
int numOfElements = sc.nextInt();
System.out.println("Enter elements in the array ~ ");
if (sc.hasNextInt()) {
int arraysInput[] = new int[numOfElements];
for (int i = 0; i < numOfElements; i++) {
arraysInput[i] = sc.nextInt();
}
System.out.println("Quotient: " + a.division(arraysInput));
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.