Can someone please help me keep the contents of this program but code it differe
ID: 3545512 • Letter: C
Question
Can someone please help me keep the contents of this program but code it differently? I prefer to have the main in the bottom and function up top...
import java.util.Scanner;
public class Candy {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] totalorder=new int[5];
total(totalorder);
}
public static void total(int [] x)
{Scanner input=new Scanner (System.in);
int [] order1= new int [5];
for(int i=0;i<5;i++)
{ if(i==0)
System.out.print("Boxes of mint for first order :");
if(i==1)
System.out.print("Boxes of chocolate with nuts for first order :");
if(i==2)
System.out.print("Boxes of chewy chocolates for first order :");
if(i==3)
System.out.print("Boxes of dark chocolate cream for first order :");
if(i==4)
System.out.print("Boxes of sugar candy for first order :");
order1[i] =input.nextInt();
}
int [] order2=new int [5];
for(int i=0;i<5;i++)
{
if(i==0)
System.out.print("Boxes of mint for second order :");
if(i==1)
System.out.print("Boxes of chocolate with nuts for second order :");
if(i==2)
System.out.print("Boxes of chewy chocolates for second order :");
if(i==3)
System.out.print("Boxes of dark chocolate cream for second order :");
if(i==4)
System.out.print("Boxes of sugar candy for second order :");
order2[i] =input.nextInt();
}
for(int i=0;i<5;i++)
{
if(i==0)
{x[i]=order1[i]+order2[i];
System.out.println("Total mint order "+x[i]);
}
if(i==1)
{x[i]=order1[i]+order2[i];
System.out.println("Total chocolate with nuts order "+x[i]);
}
if(i==2)
{x[i]=order1[i]+order2[i];
System.out.println("Total chewy chocolate order "+x[i]);
}
if(i==3)
{x[i]=order1[i]+order2[i];
System.out.println("Total dark chocolate cream order "+x[i]);
}
if(i==4)
{x[i]=order1[i]+order2[i];
System.out.println("Total sugar free candy order "+x[i]);
}
}
}
}
Explanation / Answer
import java.util.Scanner;
public class Candy {
public static void total(int[] x) {
Scanner input = new Scanner(System.in);
String contents[]={"mint","chocolate with nuts","chewy chocolates","dark chocolate","sugar candy"};
int[] order1 = new int[5];
for (int i = 0; i < 5; i++) {
System.out.println("Boxes of "+contents[i]+" for first order :");
order1[i] = input.nextInt();
}
int[] order2 = new int[5];
for (int i = 0; i < 5; i++) {
System.out.println("Boxes of "+contents[i]+" for second order :");
order1[i] = input.nextInt();
}
for (int i = 0; i < 5; i++) {
x[i] = order1[i] + order2[i];
System.out.println("Total "+contents[i]+" order " + x[i]);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] totalorder = new int[5];
total(totalorder);
}
}