2 questions in Java. all grey lines of code can not be edited. must edit inbetween grey blocks of code.
2 questions in Java. all grey lines of code can not be edited. must edit inbetween grey blocks of code.
Program - 1
Import the Scanner class to read input from the user.
Define the
MileData
class, which contains the main method where the program execution starts.Create a
Scanner
object namedscnr
to read input from the standard input (keyboard).Declare a constant
NUM_ELEMENTS
with a value of 8, which represents the number of elements in theyearlyMiles
array.Declare an integer array
yearlyMiles
with a length ofNUM_ELEMENTS
(8 in this case) to store the user's input.Declare an integer variable
i
to be used as a loop counter.Use a
for
loop to read integers from the user and store them in theyearlyMiles
array. The loop iterates from 0 toyearlyMiles.length - 1
(from 0 to 7) using the variablei
. Inside the loop, it usesscnr.nextInt()
to read an integer and stores it inyearlyMiles[i]
.After reading all the integers, use another
for
loop to print the integers in the first half of theyearlyMiles
array in reverse order. The loop starts from the middle of the array (NUM_ELEMENTS / 2 - 1
) and goes backward until it reaches the first element (0). Inside the loop, it prints each element with a hyphen separator. The conditionif (i > 0)
is used to avoid printing a hyphen after the last element.After printing all the integers in reverse order, move to a new line to separate the output.
Close the
main
method and theMileData
class.
Program - 2
- Import the Scanner class to allow you to read input from the user.
- The
public static void main(String[] args)
method is the entry point of the program. - Initialize variables:
Scanner scr
is used to read user input.int numElements
will store the number of elements in the array.int[] userScore
is an array to store the user's scores.int i
is a loop counter.
- Use the
nextInt()
method of the Scanner to read an integer from the user. This will determine the size of theuserScore
array. - Use a for loop to read
numElements
integers from the user and store them in theuserScore
array. - Calculate and print the sum of the first and last elements:
- Calculate the sum of the first and last elements by accessing
userScore[0]
anduserScore[numElements - 1]
. - Print the result using
System.out.println()
.
- Calculate the sum of the first and last elements by accessing
Step by step
Solved in 5 steps with 6 images