(Java) For this project, you will create a program that asks the user to enter a
ID: 3769630 • Letter: #
Question
(Java)
For this project, you will create a program that asks the user to enter a positive integer value less than 20.
If the user enters a number greater than 20, the user should get an error.
If the user enters a number equal to or less than 20, display the double of each value beginning with 1 up to the selected number (multiply each number by 2), then provide the total of all doubles. For example, if the user entered the number 5, the following should display:
Double up 1 = 2
Double up 2 = 4
Double up 3 = 6
Double up 4 = 8
Double up 5 = 10
Total = 30
Minimum Requirements:
Create a class that has the following methods.
1.A method that will accept two parameters: an integer array and a integer variable.
a) The integer variable should hold the value provided by the user. The array will be used to hold the double up results.
b) This method should perform the calculations, and store the double up results in the array. Additionally, the total of all double up values should be calculated using an accumulator variable that is also a private instance variable.
c)You must make sure the calling method gets the changes to the array. Remember, arrays are passed by reference by default. This method must use a loop.
2.A separate method that will return (not display) the value stored in the private instance variable called total.
Create a main method that creates an array and integer variable, as well as an instance of your class. The main method should then use the instance to call each of the methods of the class, passing the data needed and handling any return data. Display the entire contents of the array and total.
Explanation / Answer
import java.util.Scanner;
class cal
{
int x;
int total[]=new int[20];
cal(int[] a,int y)//constructor
{
x=y;
for(int i=1;i<=y;i++)
total[i]=a[i];
}
//this method calculates the double,stores it in the array and returns the total
int cal_double(int[] arr,int a)
{
int i,tot=0;
for(i=1;i<=a;i++)
{
total[i]=i*2;
tot+=total[i];
}
return(tot);//returns total
}
//this method prints the output
void display()
{
int i;
for(i=1;i<=x;i++)
{
System.out.println("Double upto"+i+"="+total[i]);
}
}
}
//main method
public class integer_sum
{
public static void main(String args[])
{
int arr[]=new int[20],a,t=1,t_value,i;
Scanner scan = new Scanner (System.in);
do
{
System.out.print ("Enter integer value less than 20: ");
a = scan.nextInt();//takes user input
if(a<=20)
{
t=0;
for(i=1;i<=a;i++)
arr[i]=i;
cal c=new cal(arr,a); //costructor called
t_value= c.cal_double(arr,a);//object calls the method
c.display();//prints the output
System.out.println("Total= "+t_value);
}
else
System.out.println("User input error !");
}while(t==1);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.