I need to write a code that finds the largest difference between two integers in a sequence. The user is supposed to input the stock prices from 10 consecutive days and the program will tell you the biggest day to day change. I'm stuck though.
import java.util.Scanner;
public class Change {
public static void main (String [] args) {
final int days = 10;
int largeDiff = 0; // largest difference
Scanner sc = new Scanner(System.in);
System.out.println("Enter a stock price:");
int price1 = sc.nextInt();
int price2 = sc.nextInt();
int diff1 = price1 - price2;
for (int i = 1; i <= 8; i++) {
int priceA = sc.nextInt();
int priceB = sc.nextInt();
int diff2 = priceA - priceB;
if (diff2 > diff1) {
diff2 = largeDiff;
}
else {
diff2 = diff1;
}
}
System.out.println(largeDiff);
}
}
The user is supposed to input the stock prices from 10 consecutive days and the program will tell you the biggest day to day change
Your code is allowing the user to enter more than 10 prices. You should be tracking the difference in price as the user enters the next price. See the below algorithm:
import java.util.Scanner;
public class LargestDiff {
public static void main(String[] args) {
final int days = 10;
Scanner sc = new Scanner(System.in);
int largeDiff = calculateLargestDiff(sc, days);
System.out.println(largeDiff);
sc.close(); //don't forget to close scanner
}
public static int calculateLargestDiff(Scanner sc, int days){
int largeDiff = 0;
System.out.println("Enter a stock price for day 1");
int price1 = sc.nextInt();
for (int i = 2; i <= days; i++) {
System.out.println("Enter a stock price for day "+i);
int price2 = sc.nextInt();
int diff2 = Math.abs(price1 - price2);
price1 = price2;
if (diff2 > largeDiff) {
largeDiff = diff2;
}
}
return largeDiff;
}
}
You may notice I created a second method that takes its dependencies - a Scanner
and an int
as parameters. This makes it easier to write automated tests.
Something else to consider - your code doesn't handle invalid inputs. For example if the user enters a letter instead of an integer. You should probably add logic to handle these kinds of scenarios.