How do I calculate the Average marks? - java

I'm making a histogram which collects the results of student marks and displays which marks are in a certain range e.g 0-29 or 70-100.
I'm trying to figure out how I can edit my code so that I can calculate the average mark. I know the average mark is calculated by adding all numbers and dividing by the amount of numbers but I'm having trouble implementing that into my program.
Here's my code:
public static void main(String[] args) {
int studentMark = 0;
// ranges from (1)0-29, (2)30-39, (3)40-69, (4)70-100 (4 ranges)
int firstRange = 0; // (1)
int secondRange = 0; // (2)
int thirdRange = 0; // (3)
int fourthRange = 0; // (4)
// counts all 'mark' attempts (except anything > 100)
int numberOfStudents = 0;
Scanner input = new Scanner(System.in);
do{
System.out.println("Enter a mark from 1-100: ");
studentMark = input.nextInt();
if (studentMark < 29)
{
firstRange++;
numberOfStudents++;
}
if ((studentMark > 29) && (studentMark <= 39))
{
secondRange++;
numberOfStudents++;
}
if ((studentMark <= 69) && (studentMark > 39))
{
thirdRange++;
numberOfStudents++;
}
if ((studentMark <= 100) && (studentMark > 69))
{
fourthRange++;
numberOfStudents++;
}
}while ((studentMark <= 100))
System.out.println("\nResults: \n");
System.out.println("Number of students in total: " + numberOfStudents);
System.out.println("\nStudents who ranged from 0-29: " + firstRange );
System.out.println("Students who ranged from 30-39: " + secondRange);
System.out.println("Students who ranged from 40-69: " + thirdRange);
System.out.println("Students who ranged from 70-100: " + fourthRange);
}

In addition to counts for each range, you need to keep total of all grades and total count (or just add individual range totals)

The border tests are redondant and at least two cases aren't treated:
- rank = 29
- rank < 0
Below a simplified code:
// ranges from (1)0-29, (2)30-39, (3)40-69, (4)70-100 (4 ranges)
final int[] roofs = new int[] {30, 40, 70, 101};
final int[] compters = new int[roofs.length];
final double[] sums = new double[roofs.length];
final double[] means = new double[roofs.length];
final Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a mark from 0-100: ");
final int studentMark = input.nextInt();
int index = -1;
if (studentMark < 0) {
continue; // here to be ignored
} else if (studentMark < roofs[0]) {
index = 0;
} else if (studentMark < roofs[1]) {
index = 1;
} else if (studentMark < roofs[2]) {
index = 2;
} else if (studentMark < roofs[3]) {
index = 3;
} else {
break;
}
compters[index]++;
sums[index] += studentMark;
} while (true);
input.close();
final int numberOfStudents = Arrays.stream(compters).sum();
IntStream.range(0, roofs.length).forEach(i -> means[i] = sums[i] / compters[i]);

Related

How to separate integers using arrays?

I am a noob at programming so I might have trouble with some key terms.
I'm trying to write a program where a user types in a minimum number and a maximum number and it generates a random number. After that I want to know how many even numbers and odd numbers are in the random generated number. I was able to successfully complete the first part but I am having trouble detecting how many even and odd numbers are in the random generated number.
SAMPLE OUTPUT:
Ex:
Random generated number is: 478,099
# of even digits: 2
# of odd digits: 3
I tried creating local variables that did not work, I want to use a switch case statement but I am having trouble. For now I used a for loop but I want to use a switch case.
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("###,###,###,###,###");
Scanner scanner = new Scanner(System.in);
int max = -1;
int min = 0;
int [] diffvalue = new int [1];
System.out.println("Enter in a maximum value: ");
max = scanner.nextInt();
System.out.println("Enter in a minimum value: ");
min = scanner.nextInt();
if (min > max)
{
System.out.println("Your minimum value is greater then your
maximum value.");
}
for (int i = 0; i < diffvalue.length; i++)
{
diffvalue[i] = (int)(Math.random()*(max-min)+min);
}
System.out.println("Random Value: ");
for(int i = 0; i < diffvalue.length; i++)
{
System.out.println(fmt.format(diffvalue[i]));
}
}
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
}
I can't look at the whole number separately.
**EDIT 1**
import java.util.Scanner;
import java.text.DecimalFormat;
public class MyClass
{
public static void main(String args[])
{
DecimalFormat fmt = new DecimalFormat("###,###,###,###,###");
Scanner scanner = new Scanner(System.in);
int max = -1;
int min = 0;
int [] diffvalue = new int [1];
System.out.println("Enter in a maximum value: ");
max = scanner.nextInt();
System.out.println("Enter in a minimum value: ");
min = scanner.nextInt();
int even = 0; int odd = 0;
if (min > max)
{
System.out.println("Your minimum value is greater then your
maximum value.");
}
for (int i = 0; i < diffvalue.length; i++)
{
diffvalue[i] = (int)(Math.random()*(max-min)+min);
}
System.out.println("Random Value: ");
for(int i = 0; i < diffvalue.length; i++)
{
System.out.println(fmt.format(diffvalue[i]));
}
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
System.out.println("Even:" + even);
System.out.println("Odd: " + odd);
}
}
}
I have gotten it to detect the even numbers and the odd numbers now I am curious to know if there is a way to do it without having the the two variables (odd, even).
You are not dividing the value l by 10. Which is why it is going into a infinite loop.
public static void even(int[] diffvalue)
{
int even = 0;
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
if((l % 10)%2==0) // this line is changed
{
even++;
}
l = l/10; // this line is changed
}
}
}
Also, if you are checking for even, you have to do ...%2 == 0. Find your errors fixed in the code above.
EDIT: you can also calculate the odd numbers in the same loop, like this:
if((l % 10)%2==0) // this line is changed
{
even++;
}
else
{
odd++;
}
EDIT3: The code was supposed to go inside the method, not replace the method.
I do not see any use case for a switch case here, but it can be accommodated like this:
public static void even(int[] diffvalue)
{
int even = 0;
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
}
Hope this helps. Good luck.

How can I use values stored in an array to another method to do a calculation?

static void diceRoll(int[] val) {
for (int i=0;i<6;i++) {
int roll1 = (int) ((Math.random() * 1000 % 6 + 1));
int roll2 = (int) ((Math.random() * 1000 % 6 + 1));
int roll3 = (int) ((Math.random() * 1000 % 6 + 1));
int roll4 = (int) ((Math.random() * 1000 % 6 + 1));
int total =0;
if ((roll1 < roll2) && (roll1 < roll3) && (roll1 < roll4)) {
total= roll2 + roll3 + roll4;
} else if ((roll2 < roll1) && (roll2 < roll3) && (roll2 < roll4)) {
total= roll1 + roll3 + roll4;
} else if ((roll3 < roll1) && (roll3 < roll2) && (roll3 < roll4)) {
total = roll1 + roll2 + roll4;
} else if ((roll4 < roll1) && (roll4 < roll2) && (roll4 < roll3)) {
total = roll1 + roll2 + roll3;
}
}
}
static void calculateBonus(int[] bonusVal){
int bonus=0;
int[] val= new int[6];
for (int i=0;i<6;i++)
for(int j=0;j<6;j++)
if (val[i] > 10 && val[i] != 11) {
bonusVal[j] = (val[i] - 10) / 2;
} else if (val[i] < 10) {
bonusVal[j] = ((val[i] / 2) - 5);
} else if (val[i] == 10 || val[i] == 11) {
bonusVal[j] = 0;
}
}
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
//Declaring variables
int level;
String choice = null;
//Getting the Level value
System.out.println("Enter the Level value :");
level = sc.nextInt();
while ((level<=0)||(level>20)){
System.out.println("Invalid input.Please enter a number between 1-20.");
System.out.println("Enter the Level value : ");
level = sc.nextInt();
}
do{
int[] val= new int[6];
int _str= val[0];
int con= val[1];
int dex= val[2];
int _int= val[3];
int wis= val[4];
int _cha= val[5];
int [] bonusVal=new int[6];
int bonus1= bonusVal[0];
int bonus2= bonusVal[1];
int bonus3= bonusVal[2];
int bonus4= bonusVal[3];
int bonus5= bonusVal[4];
int bonus6= bonusVal[5];
//Printing the Level
System.out.println("\n\n\n\n\nLevel : [ "+level+" ]");
//Displaying out put
System.out.println("_Str : ["+_str+" ]"+"["+bonus1+"]");
System.out.println("Dex : ["+dex+" ]"+"["+bonus2+"]");
System.out.println("Con : ["+con+" ]"+"["+bonus3+"]");
System.out.println("Int : ["+_int+" ]"+"["+bonus4+"]");
System.out.println("Wis : ["+wis+" ]"+"["+bonus5+"]");
System.out.println("_Cha : ["+_cha+" ]"+"["+bonus6+"]");
//Calculating the Hit points
double hp = (((Math.random()*1000 %6+1)+bonus3)*level);
//Print the Hit points
System.out.println("HP : ["+hp+"]");
//Give the chance to re-roll or continue
System.out.println("Type r if you want to re-roll or any other character if you want to continue :");
choice = sc.next();
}
while (choice.equals("r"));;
}
}
I think i had made mistakes in the second method .I want to figure out how can i use above stored values in the array to calcuate bonus and store the values for bonus in another array.This is the program i have so far.I still didnt got the output i neede.I need to get 6 values from dice roll method and store them in an array.and then i want to call the values to calculate bonus and store those bonus values in another array.
I think you want to do something like below. I haven't compiled the code, let me know if you face any issues in compiling.
static int[] calculateBonus(int[] val) {
int[] bonusVal = new int[val.length];
for(int j=0; j < val.length; j++) {
if (val[j] > 10 && val[j] != 11) {
bonus[j] = (val[j] - 10) / 2;
} else if (val[j] < 10) {
bonus[j] = ((val[j] / 2) - 5);
} else if (val[j] == 10 || val[j] == 11) {
bonus[j] = 0;
}
}
return bonusVal;
}
You need to return an array from the first method to start with, right now it doesn't work with an array at all.
Change it to the below to return an array and have a new array variable
static int[] diceRoll() {
final int rolls = 6;
int[] result = new int[rolls];
//the for loop...
at the end of the for loop you store the value in the array and then at the end return the array so the end of the method will look like
result[i] = total;
}
return result;
}
The calculateBonus will use this returned array as input and it will also work internally with an array and not an int as you have now. I also added that it will return an array.
static int[] calculateBonus(int[] val){
int count = val.length;
int[] bonus = new int[count];
for(int j=0;j<count;j++) {
if (val[j] > 10 && val[j] != 11) {
bonus[j] = (val[j] - 10) / 2;
} else if (val[j] < 10) {
bonus[j] = ((val[j] / 2) - 5);
} else if (val[j] == 10 || val[j] == 11) {
bonus[j] = 0;
}
}
return bonus;
}
A simple run
public static void main(String[] args) {
int[] values = diceRoll();
int[] bonus = calculateBonus(values);
for(int i=0; i<bonus.length; i++) {
System.out.println(bonus[i]);
}
}
Update
Below is a new version of the two methods that addresses the questions I asked in the comment and also clean up the code some.
Main difference is that I use a ArrayList in the diceRole method and that calculateBonus now uses double.
static int[] diceRoll() {
int[] result = new int[6];
for (int i=0;i<6;i++) {
List<Integer> list = new ArrayList<>();
for (int j = 0; j < 4; j++) {
list.add(new Integer((int) ((Math.random() * 1000 % 6 + 1))));
}
Collections.sort(list); //list is now in ascending order
int total =0;
for (int j = 1; j < list.size(); j++) {
total += list.get(j).intValue();
}
result[i] = total;
}
return result;
}
static double[] calculateBonus(int[] val) {
int count = val.length;
double[] bonus = new double[count];
for(int j=0;j<count;j++) {
double value = 0.0;
if (val[j] > 11) {
value = (val[j] - 10.0) / 2.0;
} else if (val[j] < 10.0) {
value = ((val[j] / 2.0) - 5.0);
}
bonus[j] = value;
}
return bonus;
}

Java - Arrays/Loops

I wanted to display the second highest and second lowest number in a given random array values ranges from(0 to 999999) and also the way the highest number will be printed in tagalog word and the shortest number will be printed in Spanish word. Here is by far is my work,can you cite or add some code for it to work? I'm having a hard time on my Main method and connecting all of them.
package demo;
import java.util.Scanner;
public class MachineProject {
public static void main(String[] args) {
int number = 5;
Scanner in = new Scanner(System.in);
int[] array=new int[5];
System.out.println("Input 6 numbers between 0 and 999,999 :");
number = in.nextInt();
for (int i=0;i<5;i++) {
array[i]=in.nextInt();
}
if(number>=0 && number<=999999){
if(number==0){
System.out.print("NUMBER AFTER CONVERSION:\tZERO");
} else {
System.out.print("NUMBER AFTER CONVERSION:\t");
convertNumberToWordsTagalog(((number / 100) % 10), " HUNDRED");
convertNumberToWordsSpanish((number % 100), " ");
}
} else{
System.out.print("NUMBER OUT OF RANGE");
}
System.out.print("\nPlease type a number between 0 and 999 OR type -1 to exit: ");
number = in.nextInt();
}
public static final String[] unitsSpanish = {
"", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete",
"ocho", "nueve", "diez", "once", "doce", "trece", "catorce",
"quince", "dieciseis", "diecisiete", "dieciocho", "diecinueve"
};
public static final String[] tensSpanish = {
"", // 0
"", // 1
"veinte", // 20
"treinta", // 30
"cuarenta", // 40
"cincuenta", // 50
"sesenta", // 60
"setenta", // 70
"ochenta", // 80
"noventa" // 90
};
public static final String[] unitsTagalog = {
"", "isa", "dalawa", "tatlo", "apat", "lima", "anim", "pito",
"walo", "siyam", "sampu", "labing isa", "labing dalawa", "labing tatlo", "labing apat",
"labing lima", "labing anim", "labing pito", "labing walo", "labing siyam"
// 0-19
};
public static final String[] tensTagalog = {
"", // 0
"", // 1
"dalawampu", // 20
"tatlumpu", // 30
"apat-na-pu", // 40
"limampu", // 50
"anim-na-pu", // 60
"pitumpu", // 70
"walumpu", // 80
"siyam-na-pu" // 90
};
public static String convertNumberToWordsTagalog(final int num) {
if (num < 20) {
return unitsTagalog[num];
}
if (num < 100) {
return tensTagalog[num / 10] + ((num % 10 != 0) ? " " : "") + unitsTagalog[num % 10];
}
if (num < 1000) {
return unitsTagalog[num / 100] + " daan" + ((num % 100 != 0) ? " " : "") + convertNumberToWordsTagalog(num % 100);
}
return convertNumberToWordsTagalog(num / 1000) + " libo" + ((num % 1000 != 0) ? " " : "") + convertNumberToWordsTagalog(num % 1000);
}
public static String convertNumberToWordsSpanish(final int num) {
if (num < 20) {
return unitsSpanish[num];
}
if (num < 100) {
return tensSpanish[num / 10] + ((num % 10 != 0) ? " " : "") + unitsSpanish[num % 10];
}
if (num < 1000) {
return unitsSpanish[num / 100] + " cien" + ((num % 100 != 0) ? " " : "") + convertNumberToWordsSpanish(num % 100);
}
return convertNumberToWordsSpanish(num / 1000) + " mil" + ((num % 1000 != 0) ? " " : "") + convertNumberToWordsSpanish(num % 1000);
}
static void SecondSmallest(int arr[]) {
Scanner in = new Scanner(System.in);
//Input size of an array
int n = in.nextInt();
//Array declaration
int arr1[] = new int[n];
//Taking an input value of an array
for (int j = 0; j < arr1.length; j++) {
arr1[j] = in.nextInt();
}
//Initialize with max value of integer
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
//Traverse an array
for (int i = 0; i < arr1.length; i++) {
if (smallest > arr1[i]) {
secondSmallest = smallest;
smallest = arr1[i];
}
if (arr1[i] > smallest && arr1[i] < secondSmallest) {
secondSmallest = arr1[i];
}
}
in.close();
System.out.println("Second smallest number is " + secondSmallest);
}
public static void SecondHighest(int arr[], int second_max) {
int max = 0, temp, numbers;
Scanner in = new Scanner(System.in);
numbers = in.nextInt();
for (int i = 0; i < numbers; i++) {
if (i == 0) {
max = in.nextInt();
} else {
temp = in.nextInt();
if (temp > max) {
second_max = max;
max = temp;
}
else if(temp>second_max)
{
second_max=temp;
}
}
}
in.close();
System.out.println("Second highest number :" + second_max);
}
}
In your code you store the numbers into an array, but you never use it.
The same for
System.out.print("\nPlease type a number between 0 and 999 OR type -1 to exit: ");
number = in.nextInt();
If you want to just find the min and max, you don't need to store every value.
You can look for min and max while the user inputs the numbers.
public static void main(String[] args) {
final int MAX_VALUE = 999999;
int min = Integer.MAX_VALUE;
int second_min = Integer.MAX_VALUE;
int second_max = Integer.MIN_VALUE;
int max = Integer.MIN_VALUE;
final Scanner in = new Scanner(System.in);
System.out.println("How many numbers do you want to insert? (0 or a negative number to exit)");
int n = in.nextInt();
if (n <= 0) {
System.out.println("Goodbye");
System.exit(0);
}
System.out.println("Input "+n+" integers between 0 and " + MAX_VALUE + " :");
int val; // this integer will be used to check the input
for (int i = 0; i < n; i++) {
do {
val = in.nextInt();
if ((val < 0) || (val > MAX_VALUE)) {
System.out.println("Error: NUMBER OUT OF RANGE");
System.out.println("Please insert a valid number");
}
} while ((val < 0) || (val > MAX_VALUE));
// Now we're sure that val contains a valid number
if (val < min) {
second_min = min;
min = val;
} else if (val < second_min) {
second_min = val;
}
if (val > max) {
second_max = max;
max = val;
} else if (val > second_max) {
second_max = val;
}
}
in.close();
System.out.print("Min (in Spanish):\t");
if (min == 0) {
System.out.println("Zero");
} else {
System.out.println(convertNumberToWordsSpanish(min));
}
System.out.println("Second smallest number: " + second_min);
System.out.println("Second highest number: " + second_max);
System.out.print("Max (in Tagalog):\t");
if (max == 0) { // Keep in mind that the user could input N zeros
System.out.println("Zero");
} else {
System.out.println(convertNumberToWordsTagalog(max));
}
}
If you need to store the numbers into an array, you could remove the code for searching min and max, and use Arrays.sort() so
final int min = array[0];
final int second_min = array[1];
final int second_max = array[n-2];
final int max = array[n-1];

Recursion Coin Change

Need help figuring out how to print the individual coins such as quarters = 3, pennies = 1, instead of just giving me 4 coins for 76 cents. I tried setting 4 counters, but that just repeatedly printed out the coin names and answers were wrong.
import java.util.Scanner;
public class Money
{
public static void main(String args[])
{
int[] coins = { 1, 5, 10, 25};
Scanner scan = new Scanner(System.in);
System.out.print("Enter Change (In Cents): ");
int sum = scan.nextInt();
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
String quarter = "";
Money minCoin = new Money();
System.out.println(minCoin.findMinCoins(coins, sum, counter1, counter2, counter3, counter4));
System.out.println(counter4);
}
private int findMinCoins(int[] coins, int sum, int counter1, int counter2, int counter3, int counter4)
{
if (sum <= 0 || coins.length == 0)
{
return 0;
}
for (int i = coins.length - 1; i >= 0; i--)
{
if(coins[i] == 1 && coins[i] != 5)
{
counter1++;
}
if(coins[i] == 5)
{
counter2++;
}
if(coins[i] == 10)
{
counter3++;
}
if(coins[i] == 25)
{
counter4++;
}
if (coins[i] <= sum)
{
System.out.println("Pennies: " + counter1);
System.out.println("Nickels: " + counter2);
System.out.println("Dimes: " + counter3);
System.out.println("Quarters: " + counter4);
return 1 + findMinCoins(coins, sum - coins[i], counter1, counter2, counter3, counter4);
}
}
return 0;
}
}
Try this:
import java.util.Scanner;
public class Money
{
public static void main(String[] args) {
int[] coins = {1, 5, 10, 25};
Scanner scan = new Scanner(System.in);
System.out.print("Enter Change (In Cents): ");
int sum = scan.nextInt();
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
String quarter = "";
Money minCoin = new Money();
System.out.println(minCoin.findMinCoins(coins, sum, counter1, counter2, counter3, counter4));
System.out.println(counter4);
}
private int findMinCoins(int[] coins, int sum, int counter1, int counter2, int counter3, int counter4) {
if (sum <= 0 || coins.length == 0) {
return 0;
}
for (int i = coins.length - 1; i >= 0; i--) {
if (coins[i] == 25 && sum >= coins[i]) {
counter4++;
}
else if (coins[i] == 10 && sum >= coins[i]) {
counter3++;
}
else if (coins[i] == 5 && sum >= coins[i]) {
counter2++;
}
else if (coins[i] == 1 && sum >= coins[i]) {
counter1++;
}
if (coins[i] <= sum) {
System.out.println("Pennies: " + counter1);
System.out.println("Nickels: " + counter2);
System.out.println("Dimes: " + counter3);
System.out.println("Quarters: " + counter4);
return 1 + findMinCoins(coins, sum - coins[i], counter1, counter2, counter3, counter4);
}
}
return 0;
}
}
I suspect you have misunderstood how arguments passed to Java methods work. You are passing in the 'counter' values and then iterating them inside the method and expecting their values in the calling method to have changed. That's not how Java works. See here for more details.
If you're not expecting to get the values back from the method (because you're printing them inside) then there's no point making them arguments. Best to make it a local variable inside the scope of the method.
You might find it a bit easier if you order from largest to smallest and return an array from your change calculator. Then you won't need individual variables for your counters.
Something like the following:
int[] coins = {25, 10, 5, 1};
String[] names = {"Quarters", "Dimes", "Nickles", "Pennies"};
int[] change = getChange(coins, total);
for (int i = 0; i < change.length; i++) {
System.out.println(names[i] + ":" + change[i]);
}
private int[] getChange(int[] coins, int total) {
int[] result = new int[coins.length];
for (int i = 0; i < coins.length; i++) {
result[i] = total / coins[i];
total -= result[i] * coins[i];
}
return result;
}
Note that this takes advantage of Java's integer division rounding down. So if you start with 76 cents it will return 3 quarters (76/25 -> 3). Note also that the second statement in the loop could be total %= coins[i] which would have the same effect but might be more understandable. Either way the code is saying 'remove from the total the value of the current denomination`.

Find largest and smallest numbers number using Arrays

Trying to let users enter number of integers so I can set array length then find the max and min value. However, I can't find max and min. Please help.
import java.util.Scanner;
import java.util.Arrays;
public class ExerciseC{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of integers you would like to enter:");
int numberEnter = keyboard.nextInt();
System.out.println("Enter some integers:");
int integers = keyboard.nextInt();
int numbers [] = new int [numberEnter];
int maxValue = numbers[0];
int minValue = numbers[0];
int max = 0;
int min = 0;
for (int index = 1; index < numbers.length; index ++) {
if (numbers[index] > maxValue) {
maxValue = numbers [index];
}
}
System.out.println("Print: " + maxValue);
System.out.println("The difference between the largest and the smallest is: ");
}
}
You don't seem to be entering more then one value (and you never store integers in your array). Also, you aren't setting the min. I think you wanted
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number of integers to enter:");
int numberEnter = keyboard.nextInt();
int numbers[] = new int[numberEnter];
int pos = 0;
do {
System.out.printf("Please enter integer #%d/%d:%n", pos, numberEnter);
numbers[pos++] = keyboard.nextInt();
} while (pos < numberEnter && keyboard.hasNextInt());
int min = numbers[0];
int max = numbers[0];
for (pos = 1; pos < numbers.length; pos++) {
if (numbers[pos] < min) { // <-- test min.
min = numbers[pos];
}
if (numbers[pos] > max) { // <-- test max.
max = numbers[pos];
}
}
// Display everything.
System.out.printf("%s Min: %d Max: %d%n", Arrays.toString(numbers),
min, max);
}
Your numbers[] is empty. The user's input is not stored into the array.
Here is your fixed code:
package com.company;
import java.util.Scanner;
public class ExerciseC{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number of integers you would like to enter:");
int numberEnter = keyboard.nextInt();
int numbers [] = new int [numberEnter];
for (int i = 0; i < numberEnter; i++) {
System.out.println("Enter integer:");
numbers[i] = keyboard.nextInt();
}
int maxValue = numbers[0];
int minValue = numbers[0];
for (int index = 1; index < numbers.length; index ++) {
if (numbers[index] > maxValue) {
maxValue = numbers [index];
}
}
System.out.println("Print: " + maxValue);
System.out.println("The difference between the largest and the smallest is: ");
}
}
import java.util.Scanner;
class StdR {
public static void main(String[] args) {
// TODO Auto-generated method stub
StdR st = new StdR();
st.stdR();
//System.out.println(st.stdR();
}
void stdR()
{
char[] grade = {'A','B','C','D','E','F'};
Scanner input = new Scanner(System.in);
byte[] st = new byte[3];
double[] percentage = new double[st.length];
for(byte s = 0; s < st.length; s++){
System.out.println("\nStudent " + s);
short noOfMarks = 0;
short totalMarks = 450;
percentage[s] = 0.0;
byte[] marks = new byte[5];
for (byte i = 0; i < marks.length; i++){
System.out.println("Enter marks of Chapter "+ i + ": ");
marks[i] = input.nextByte();
noOfMarks += marks[i];
percentage[s] += (marks[i] * 100) / totalMarks;
}
System.out.print("No of marks: " + noOfMarks + "\t");
System.out.print("Percentage: " + percentage[s] + "\t");
if (percentage[s] > 79.0 && percentage[s] < 100.1)
System.out.print("Grade: " + grade[0]);
else if (percentage[s] > 69.0 && percentage[s] < 80.0)
System.out.print("Grade: " + grade[1]);
else if (percentage[s] > 59.0 && percentage[s] < 70.0)
System.out.print("Grade: " + grade[2]);
else if (percentage[s] > 49.0 && percentage[s] < 60.0)
System.out.print("Grade: " + grade[3]);
else if (percentage[s] > 39.0 && percentage[s] < 50.0)
System.out.print("Grade: " + grade[4]);
else if (percentage[s] < 40.0)
System.out.print("Grade: " + grade[5]);
}
double smallest = percentage[0] , largest= percentage[0];
for (int i=0 ;i< percentage.length; i++) {
if (percentage[i] < smallest) {
smallest = percentage[i];
} // end finding smallest
if (percentage[i] > largest) {
largest = percentage[i];
}
}
System.out.println("\n1st Position and Top percentage is " + largest);
System.out.println("\nLast Position and Least percentage is "+smallest);
}
}

Categories