Please help in Java: The input consists of an integer (the number of elements in
ID: 3781167 • Letter: P
Question
Please help in Java:
The input consists of an integer (the number of elements in the array), followed by the elements of the array. Method Add will add the elements of the array and return that value (the total) to main. Method printResult will take that total and print the following: if the total is divisible by 5, it will print "You lose!" If the total is exactly 21, it will print "You win!" Otherwise it will print "Try again." In each case use a println.
This is what i have so far:
import java.util.Scanner;
public class Lab1Num1 {
public static void main(String[] args) {
//get the input
int[] myArray=getInput();
//add the integers
int total=Add(myArray);
//determine win or lose or try again.
printResult(total);
}
public static int[] getInput()
{ Scanner keyboard = new Scanner(System.in);
//find the length of the array
int num = keyboard.nextInt();
//create the array
int[] myA= new int[num];
//fill the array
for (int i=0; i<num; i++)
myA[i]=keyboard.nextInt();
return myA;
}
public static int Add(int[]myA)
{ //your code goes here
}
public static void printResult(int t)
{ //your code goes here
if(t%5==0)
System.out.println("You lose!");
else if(t==21)
System.out.println("You win!");
else
System.out.println("Try again.");
}
}
Explanation / Answer
Just replace the Add() method like below:
public static int Add(int[]myA)
{ int sum=0;
for(int i=0;i<myA.length;i++){
sum+=myA[i];
}
return sum;
}
No need to do anything in printResult() method.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.