Excluding an integer from an array to find the 2nd smallest - java

I have an assignment where my prof. will input an unspecified number of integers into my program, and my program will process the data accordingly to assign a grade to each value and find the highest and lowest value, however he always places a -1 at the end of the data so that when input<0 it will stop prompting for input.
The problem is my program isn't supposed to process the -1. It doesn't get added as a grade, but it is a part of the list of grades, so the lowest value is always -1.
I've tried writing code that would remove the -1 from my array when detected as a part of the logic to evaluate a grade, but everything I've tried only returns errors.
How can I ignore the -1 and find the next lowest value, or remove the -1 from the list before evaluating?
import java.util.*;
public class Hw5{
public static void main(String[] args){
Scanner console = new Scanner(System.in);
int input = console.nextInt();
ArrayList<Integer> GradeList = new ArrayList<>();
while(input >= 0){
input = console.nextInt();
GradeList.add(input);
}
evaluateGrade(GradeList);
System.out.print(GradeList);
}
public static void evaluateGrade(List<Integer> Scores){
int count = Scores.size();
int high = Collections.max(Scores);
int low = Collections.min(Scores);
int Aplus = 0;
int A = 0;
int Amin = 0;
int Bplus = 0;
int B = 0;
int Bmin = 0;
int Cplus = 0;
int C = 0;
int Cmin = 0;
int Dplus = 0;
int D = 0;
int Dmin = 0;
int F = 0;
for(int i : Scores){
if(i > 97){
Aplus += 1;
}
else if(i >= 93 && i <= 96){
A += 1;
}
else if(i >= 89 && i <= 92){
Amin += 1;
}
else if(i >= 85 && i <= 88){
Bplus += 1;
}
else if(i >= 81 && i <= 84){
B += 1;
}
else if(i >= 77 && i <= 80){
Bmin += 1;
}
else if(i >= 81 && i <= 84){
B += 1;
}
else if(i >= 77 && i <= 80){
Bmin += 1;
}
else if(i >= 76 && i <= 73){
Cplus += 1;
}
else if(i >= 69 && i <= 72){
C += 1;
}
else if(i >= 65 && i <= 68){
Cmin += 1;
}
else if(i >= 61 && i <= 64){
Dplus += 1;
}
else if(i >= 57 && i <= 60){
D += 1;
}
else if(i >= 53 && i <= 56){
Dmin += 1;
}
else if(i >= 52 && i <= 0){
F += 1;
}
}
System.out.printf("Total number of grades = %d", count);
System.out.println();
System.out.printf("Number of A+'s = %d", Aplus);
System.out.println();
System.out.printf("Number of A's = %d", A);
System.out.println();
System.out.printf("Number of A-'s = %d", Amin);
System.out.println();
System.out.printf("Number of B+'s = %d", Bplus);
System.out.println();
System.out.printf("Number of B's = %d", B);
System.out.println();
System.out.printf("Number of B-'s = %d", Bmin);
System.out.println();
System.out.printf("Number of C+'s = %d", Cplus);
System.out.println();
System.out.printf("Number of C's = %d", C);
System.out.println();
System.out.printf("Number of C-'s = %d", Cmin);
System.out.println();
System.out.printf("Number of D+'s = %d", Dplus);
System.out.println();
System.out.printf("Number of D's = %d", D);
System.out.println();
System.out.printf("Number of D+'s = %d", Dmin);
System.out.println();
System.out.printf("Number of F's = %d", F);
System.out.println();
System.out.printf("The highest grade = %d", high);
System.out.println();
System.out.printf("The lowest grade = %d", low);
System.out.println();
}

Change this
int input = console.nextInt();
ArrayList<Integer> GradeList = new ArrayList<>();
while(input >= 0){
input = console.nextInt();
GradeList.add(input);
}
To something like
List<Integer> gradeList = new ArrayList<>();
int input;
while ((input = console.nextInt()) >= 0) {
gradeList.add(input);
}
Which programs to the List interface, follows the Java idiomatic convention of assignment and evaluation and observes standard variable naming conventions.

Related

Why doesn't my program run correctly?

for my school project I have to create a program that outputs perfect numbers based on how many perfect numbers the user(teacher) want. The user can pick any number from 1-4 and it should display however many number the user chooses. Here is my current code. Please ignore the sumupTo, factorial, isprime, and the testGoldbach methods, please only look at the Perfect numbers method/code.
import java.util.Scanner;
public class MyMathB
{
public static int sumUpTo(int n)
{
int sum = 0;
for (int k = 1; k <= n; k++)
sum += k;
return sum;
}
public static long factorial(int n)
{
long f = 1;
for (int k = 2; k <= n; k++)
f *= k;
return f;
}
public static boolean isPrime(int n)
{
if (n <= 1)
return false;
int m = 2;
while (m * m <= n)
{
if (n % m == 0)
return false;
m++;
}
return true;
}
public static void PerfectNumbers(int number)
{
System.out.println("How many perfect numbers would you like to see? Please enter an integer from 1 to 4");
Scanner s = new Scanner(System.in);
int numbersToSee = s.nextInt();
int counts = 0;
for(counts = 0; counts <= numbersToSee; counts++)
{
for (int n = 5; n <= 10000; n++)
{
int temp = 0;
for(int i = 1; i <= number / 2; i++)
{
if (number % i == 0)
{
temp += i;
}
if (temp == number)
{
System.out.println(number);
}
}
}
}
}
public static boolean testGoldbach(int bigNum)
{
for (int n = 6; n <= bigNum; n += 2)
{
boolean found2primes = false;
for (int p = 3; p <= n/2; p += 2)
{
if (isPrime(p) && isPrime(n - p))
found2primes = true;
}
if (!found2primes)
{
System.out.println(n + " is not a sum of two primes!");
return false;
}
}
return true;
}
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int n;
do
{
System.out.print("Enter an integer from 4 to 20: ");
n = kb.nextInt();
} while (n < 4 || n > 20);
kb.close();
System.out.println();
System.out.println("1 + ... + " + n + " = " + sumUpTo(n));
System.out.println(n + "! = " + factorial(n));
System.out.println("Primes: ");
for (int k = 1; k <= n; k++)
if (isPrime(k))
System.out.print(k + " ");
System.out.println();
System.out.println("Goldbach conjecture up to " + n + ": " + testGoldbach(n));
}
}
you didn't declare the variable "number" in your method.
Edit: you didn't SET the variable number to anything, I misworded my last statement.

Common Occurrence Issue

my whole code works fine, except for the common occurrences part. If you input 1 number the most, it will work, but if you enter 2 numbers an equal amount of times, it won't work anymore. Any additional advice to improve my code would be much appreciated.
public static void Thingy() {
Scanner input = new Scanner(System.in);
int min = 999;
int max = 0;
int range;
int prevocc = 0;
int occ = 0;
int common = 0;
int enter = 1;
int a1_5 = 0;
int a6_10 = 0;
int a11_15 = 0;
int a16_20 = 0;
int a21_25 = 0;
int a26_30 = 0;
int a31_35 = 0;
int a36_40 = 0;
int a41_45 = 0;
int a46_50 = 0;
int[] num;
num = new int[99999];
for (int i = 1; i < 99999 && enter != 0; i++) {
System.out.println("Enter a number between 1 and 50, enter 0 to quit");
num[i] = input.nextInt();
enter = num[i];
if (num[i] > max) {
max = num[i];
}
if (num[i] < min) {
if (num[i] != 0) {
min = num[i];
}
}
if (num[i] > 50) {
System.out.println("Your number is too high, enter another number");
num[i] = input.nextInt();
}
if (num[i] < 0) {
System.out.println("Your number is too low, enter another number");
num[i] = input.nextInt();
}
for (; num[i] > 0; num[i]--) {
if (enter == num[i]) {
occ++;
}
if (occ > prevocc) {
common = num[i];
}
prevocc = occ;
}
num[i] = enter;
}
for (int j = 50; j > 0; j--) {
if (num[j] >= 1 && num[j] <= 5) {
a1_5++;
} else if (num[j] >= 6 && num[j] <= 10) {
a6_10++;
} else if (num[j] >= 11 && num[j] <= 15) {
a11_15++;
} else if (num[j] >= 16 && num[j] <= 20) {
a16_20++;
} else if (num[j] >= 21 && num[j] <= 25) {
a21_25++;
} else if (num[j] >= 26 && num[j] <= 30) {
a26_30++;
} else if (num[j] >= 31 && num[j] <= 35) {
a31_35++;
} else if (num[j] >= 36 && num[j] <= 40) {
a36_40++;
} else if (num[j] >= 41 && num[j] <= 45) {
a41_45++;
} else if (num[j] >= 46 && num[j] <= 50) {
a46_50++;
}
}
System.out.print("1 - 5: ");
while (a1_5 > 0) {
System.out.print("*");
a1_5--;
}
System.out.println("");
System.out.print("6 - 10: ");
while (a6_10 > 0) {
System.out.print("*");
a6_10--;
}
System.out.println("");
System.out.print("11 - 15: ");
while (a11_15 > 0) {
System.out.print("*");
a11_15--;
}
System.out.println("");
System.out.print("16 - 20: ");
while (a16_20 > 0) {
System.out.print("*");
a16_20--;
}
System.out.println("");
System.out.print("21 - 25: ");
while (a21_25 > 0) {
System.out.print("*");
a21_25--;
}
System.out.println("");
System.out.print("26 - 30: ");
while (a26_30 > 0) {
System.out.print("*");
a26_30--;
}
System.out.println("");
System.out.print("31 - 35: ");
while (a31_35 > 0) {
System.out.print("*");
a31_35--;
}
System.out.println("");
System.out.print("36 - 40: ");
while (a36_40 > 0) {
System.out.print("*");
a36_40--;
}
System.out.println("");
System.out.print("41 - 45: ");
while (a41_45 > 0) {
System.out.print("*");
a41_45--;
}
System.out.println("");
System.out.print("46 - 50: ");
while (a46_50 > 0) {
System.out.print("*");
a46_50--;
}
System.out.println("");
System.out.println("The highest number is: " + max);
System.out.println("The lowest number is " + min);
System.out.println("The most commonly occuring number is: " + common);
System.out.println("The range is: " + (max - min));
}

Luhn's Algorithm not working properly

For those who are familiar with Luhn's Algorithm, I am compiling a program that verify credit card numbers using this Algorithm. Here's what I have already:
Scanner input = new Scanner(System.in);
String ccNum = "";
int product = 0;
int sum = 0;
System.out.print("Please enter a credit card #: ");
ccNum = input.next();
for(int i = 0 + 1; i < ccNum.length(); i--){
int number = Integer.parseInt(ccNum.substring(i, i + 1));
if(i % 2 != 0){
product = number * 1;
}
else{
product = number * 2;
}
if(product > 9){
product -= 9;
sum += product;
}
}
boolean valid = (sum % 10 == 0);
if(valid){
System.out.println("Valid!");
}
else{
System.out.println("Invalid!");
}
}
}
I am confused about this program. When I run it, I got the "StringIndexOutOfBoundsExpection" error. What should I change up? We cannot use arrays with this program, however. Instead of the full 16-digit number, we are only using 8 digits.
Try this.
boolean alt = false;
for(int i = ccNum.length() - 1; i >= 0; i--, alt = !alt){
int number = ccNum.charAt(i) - '0';
if(alt)
number *= 2;
if(number > 9)
number -= 9;
sum += number;
}
boolean valid = (sum % 10 == 0);

How do I terminate this loop?

"Only one while loop should be used to determine all even and odd numbers between 50 and 100."
public class EvenOdd {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 0;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i != x) || (j != y)) {
n++;
System.out.print(i + x + ", ");
i += 2;
if(i != x)
continue;
System.out.println("100");
System.out.print("\nOdd numbers between 50 and 100: ");
System.out.print((j+1) + y + ", ");
j += 2;
if(j != y)
continue;
}
}
}
The evens print fine but the odds continue on forever. This may be a dumb question, but I'm having the biggest brainfart right now, and I would really appreciate help on this.
Simply try this and let me know. It's based on your code, with just a few minor adjustments:
public class Teste4 {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 1;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i < x) || (j < y)) {
if(i < x){
System.out.print(i + x + ", ");
i += 2;
continue;
}else if(i == x){
System.out.println("100");
i++;
}
if(j == 1){
System.out.print("\nOdd numbers between 50 and 100: ");
}
System.out.print(j + y + ", ");
j += 2;
}
}
}
Perhaps you should try this
int even_counter = 50;
int odd_counter=51;
System.out.println("Even numbers between 50 and 100: ");
while((even_counter < 100 ) || (odd_counter < 100)){
if(even_counter < 100){
System.out.print(even_counter+ " ");
even_counter+=2;
continue;
}
if(odd_counter < 100){
if(odd_counter == 51){
System.out.println("\nOdd numbers between 50 and 100: ");
}
System.out.print(odd_counter+ " ");
odd_counter+=2;
}
}
I'm sure this is an assignment but i'll add my 2 cents since it's solved. This one will give you an array.
final int EVEN = 0, ODD = 1;
int low = 50, high = 100, current = low;
int[][] numbers = new int[2][];
numbers[EVEN] = new int[((high - low) / 2) + ((high - low) % 2)];
numbers[ODD] = new int[((high - low) / 2)];
while(current < high){
numbers[current % 2][(current - low) / 2] = current++;
}
System.out.println("EVEN" + Arrays.toString(numbers[EVEN]));
System.out.println("ODD " + Arrays.toString(numbers[ODD]));
Alternative approach ,
int current = 50 , end = 100 ;
String odd , even ;
while(current <= 100){
if (current % 2 == 0)
even = even.concat ("," + current);
else
odd = odd.concat("," + current);
current++;
}
System.out.println("Even no are : " + even);
System.out.println("Odd no are : " + odd);
I dont have a compiler now . I think this should be right :) .

Argument values error [duplicate]

This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
For one of my classes, we had to find a way to make a certain amount of change given an arbitrary amount of coins, with the least amount of coins. Here is my code below:
public class Changemaker {
public static void main ( String[] args ) {
int amount = Integer.parseInt(args[args.length-1]);
int coins = args.length - 1;
if (amount < 0){
throw new IllegalArgumentException("IMPROPER AMOUNT");
} else {
for (int i = 1; i <= coins; i++) {
int coin = Integer.parseInt(args[i]);
if (coin <= 0){
throw new IllegalArgumentException("IMPROPER DENOMINATION");
} else {
for (int j = 1; j <= coins; j++) {
int validCoin = Integer.parseInt(args[j]);
if (validCoin == coin && j != i ) {
throw new IllegalArgumentException("DUPLICATE DENOMINATION");
}
}
}
try {
String firstCoin = args[1];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("INSUFFICIENT DATA");
throw new ArrayIndexOutOfBoundsException(" ");
}
}
}
Tuple [][] table = new Tuple [coins][amount + 1];
for(int x = 0; x < coins; x++) {
for (int i = 0; i <= amount; i++) {
Tuple tuple = new Tuple (coins);
table[x][i] = tuple;
}
}
for (int i = 1; i <= amount; i++) {
Tuple tuple = table[0][i];
int coin = Integer.parseInt(args[1]);
int total = i;
int remainder = total % coin;
int coinAmt= (int)Math.floor(total / coin);
if (remainder == 0) {
tuple.setElement(0, coinAmt);
}
}
for(int x = 1; x < coins; x++) {
int coin = Integer.parseInt(args[x + 1]);
for (int i = 1; i <= amount; i++) {
Tuple tuple = table[x][i];
int total = i;
int remainder = total % coin;
int coinAmt= (int)Math.floor(total / coin);
if (remainder == 0) {
tuple.setElement(x, coinAmt);
int optimalRow = optimalCheck(table, tuple, x, i);
Tuple optimalTuple = table[optimalRow][i];
tuple.copy(optimalTuple);
} else if (remainder != 0 && amount < coin) {
tuple.copy(table[x - 1][i]);
} else if (remainder != 0 && amount > coin) {
tuple.setElement(x, coinAmt);
Tuple remainderTuple = table[x][remainder];
tuple.add(remainderTuple);
int optimalRow = optimalCheck(table, tuple, x, i);
Tuple optimalTuple = table[optimalRow][i];
tuple.copy(optimalTuple);
}
}
}
Tuple finalAnswer = table[coins - 1][amount];
String result = "";
result = result + finalAnswer.total() + " COIN(S) IN TOTAL: ";
for (int i = 0; i < coins; i++) {
result = result + finalAnswer.getElement(i) + " x " + args[i + 1] + " cent , ";
}
if (finalAnswer.total() == 0) {
System.out.println("AMOUNT CANNOT BE MADE");
} else {
System.out.println(result);
}
}
public static int optimalCheck(Tuple[][] table, Tuple tuple, int row, int column) {
int total = tuple.total();
int optimalRow = 0;
for (int i = 0; i <= row; i++ ){
int checkedTotal = table[i][column].total();
if (checkedTotal < total && checkedTotal > 0) {
optimalRow = optimalRow + i;
break;
} else if (checkedTotal == total && i == row) {
optimalRow = optimalRow + row;
break;
}
}
return optimalRow;
} }
For the most part, my code is correct. The only thing wrong with it is that it counts the amount of change to make as a denomination, and it cuts out my first denomination amount.
So, for example, if I put 1 5 10 25 133 in the command line (1,5,10, and 25 cent coins to make 133 cents), it returns:
1 COIN(S) IN TOTAL: 0 x 5 cent , 0 x 10 cent , 0 x 25 cent , 1 x 133 cent ,
I looked at the code, and I don't see where I went wrong. Can anyone tell me where I made the error? Thanks a ton.
In your for loop, you want
for (int i = 1; i < coins; i++) {
not
for (int i = 1; i <= coins; i++) {
<= will include coins, which is length - 1 - the last argument.

Categories

Resources