Trying to count number of occurrences in an array [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So I'm trying to count the number of integer occurrences in this program. The code still doesn't work, but am I on the right track?
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int userInput = 0;
ArrayList<Integer> myList = new ArrayList<Integer>();
int[] newArray = new int[myList.size()];
int index1 = -1;
int current;
for (int num = 0; num <= userInput ; num++)
{
System.out.println("Please enter a random number between 0 and 50, enter a negative number to end input: ");
num--;
if(userInput >= 0 || userInput <= 50)
{
userInput++;
userInput = scan.nextInt();
index1++;
myList.add(userInput);
}
if (userInput < 0 || userInput > 50)
{
myList.remove(index1);
index1--;
break;
}
}
for (int num2 = 0; num2 < myList.size(); num2++)
{
current = myList.get(num2);
if(current == myList.get(num2))
{
newArray[current-myList.get(num2)]++;
}
}
for (int number=0; number < newArray.length; number++)
{
System.out.println(number + "1");
System.out.println(" : " + newArray[number]);
}
}
}
edit:
just wanted to add that I can run the program, but when I input an integer that is out of bounds (not between 0 and 50), I get an error

I just finished writing this, thanks for the downvotes while I was modifying my code and specifically stated I was modifying the code. Hashmaps will do the trick for you here.
public static void main(String args[]) {
HashMap<Integer, Integer> numbers = new HashMap<Integer, Integer>();
Scanner scan = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("Number: ");
int current = scan.nextInt();
if (current > 0 && current < 51) {
if (numbers.containsKey(current)) {
numbers.put(current, numbers.get(current)+1);
}else{
numbers.put(current, 1);
}
} else {
if(numbers.isEmpty()){
System.out.println("Nothing inputted");
loop = false;
}else{
for(Entry<Integer,Integer> e : numbers.entrySet()){
System.out.println(e.getKey() + " was entered " + e.getValue() + " times");
}
loop = false;
}
}
}
}

You do not need any additional collection like myList.
You can declare array
int[] occurrences = new int[51];
which can store occurence of elements from range [0,50]. When You read n as nextInt from scanner You should increment element of this array at readed n-th position if n is in range or stop reading new values otherwise.
This if statemest is always true:
current = myList.get(num2);
if(current == myList.get(num2))
Code example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] occurrrences = new int[51];
while (true){
int value = scanner.nextInt();
if(value>=0 && value<occurrrences.length){
occurrrences[value]++;
}else{
scanner.close();
break;
}
}
for (int i = 0; i < occurrrences.length; i++) {
if(occurrrences[i]>0){
System.out.println(i + " occured " + occurrrences[i] + " times.");
}
}
}

Related

Working on a Java Program that utilizes For Loops to separate Even, Odd, and Negative Inputted Integers. Try Catch Handler Gives Out-of-bounds Error? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 12 months ago.
I am working on a Java program that determines Evens, Odds, and Negative numbers from 12 inputted integers.
It then separates them into different arrays. The course I am following suggests building an exception handler and I utilized the Try-Catch Method for the Exception error I may receive.
It then creates an Out of Bounds error for counting these numbers when I enter a String.
I've commented on the area in which I have trouble reprompting the user. So far, I've tried prompting at the error with twelveInt [i] = in.nextInt(); and just in.next();.
Why is the program affected outside of the loop?
Here is the program:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int [] twelveInt = new int [12];
int countEven = 0;
int countOdd = 0;
int countNeg = 0;
boolean ehandle = true;
for (int i = 0; i < twelveInt.length; i++) {
while(ehandle){
try{
System.out.println("Enter the #" + (i + 1) + " integer.");
twelveInt [i] = in.nextInt();
ehandle = false;
}
catch(Exception e){
System.out.println("Please enter integers only");
// Unsure of what to add here to handle the errors and allow me to reprompt. in.next();
//does not work nor does twelveInt [i] = in.nextInt();
}
if (twelveInt[i] % 2 == 0){
countEven++;
}
if (twelveInt[i] % 2 != 0){
countOdd++;
}
if (twelveInt[i] < 0){
countNeg++;
}
}
}
int [] evens = new int [countEven];
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
countEven = 0;
countOdd = 0;
countNeg = 0;
for (int i : twelveInt) {
if (i % 2 == 0){
evens[countEven++] = i;
}
if (i % 2 != 0){
odds[countOdd++] = i;
}
if (i < 0){
negatives[countNeg++] = i;
}
}
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));
The problem in your code is that after you run your loop and enter your first number, you then define ehandle = false.
This means that you never enter the rest of your loop since you exit the while loop. Therefore, you never increment the values of countEven, countOdd, or countNeg.
This results in an error because when you try running this line: int [] evens = new int [countEven]; , countEven is still 0, so you get an error when you try to iterate it.
To avoid this error, you can modify your try catch error as so:
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int [] twelveInt = new int [12];
int countEven = 0;
int countOdd = 0;
int countNeg = 0;
for (int i = 0; i < twelveInt.length; i++) {
System.out.println("Enter the #" + (i + 1) + " integer.");
boolean error = true;
while (error) {
try {
twelveInt [i] = in.nextInt();
if (twelveInt[i] % 2 == 0){
countEven++;
}
if (twelveInt[i] % 2 != 0){
countOdd++;
}
if (twelveInt[i] < 0){
countNeg++;
}
error = false;
}
catch (Exception e) {
System.out.println("Please enter integers only");
in.next();
}
}
}
int [] evens = new int [countEven];
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
countEven = 0;
countOdd = 0;
countNeg = 0;
for (int i : twelveInt) {
if (i % 2 == 0){
evens[countEven++] = i;
}
if (i % 2 != 0){
odds[countOdd++] = i;
}
if (i < 0){
negatives[countNeg++] = i;
}
}
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));
}
}
We first try taking in the user input, and if we get an exception error, we will use the catch so our code does not terminate. NOTE: we must do in.next() otherwise we will get an infinite loop (since integers leave a trailing newline, resulting in infinite exceptions).
I hope this helped! Please let me know if you need any further clarifications or details :)
If you want to reiterate your while(ehandle) loop when you get an exception, you can put continue in your catch block. But you should set ehandle back to true at the top of your for-loop.
for (int i = 0; i < twelveInt.length; i++) {
ehandle = true;
while (ehandle) {
try {
System.out.println("Enter the #" + (i + 1) + " integer.");
twelveInt[i] = in.nextInt();
ehandle = false;
} catch(Exception e) {
System.out.println("Please enter integers only");
continue;
}
...

After re-run program with while loop , exception method doesn't work

I'm handling exceptions for an exercise and runs fine until I enter an invalid number (to try) after running the program for the first time, this is after the first run when asking to re-run with different values if I happen to enter invalid values it won't throw the exception and I don't know why? It's something I don't know or is it my code? Thanks
//program ReverseNumbers.java
//This program reverses the digits of each number in an array.
import java.util.Scanner;
public class ReverseNumbers{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
boolean continueInput = true; //controls loop for input
String another = "y";
while(another.equalsIgnoreCase("Y")){ //loop to re-run program
do{
System.out.print("\nEnter 5 positive integers: "); //prompt the user to enter 5 integers
//try block
try{
for(int i = 0; i < numbers.length ; i++) //initialize the array
numbers[i] = input.nextInt();
checkInput(numbers); //handler method
continueInput = false;
}
//catch block
catch(IllegalArgumentException ex){
System.out.print("\nInvalid input: ");
//input.nextLine();
}
}while(continueInput);
//outputs
System.out.print("\nEntered numbers:\t\t");
for(int e: numbers)
System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
reverse(numbers);
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
//Exception method
public static void checkInput(int[] array) throws IllegalArgumentException {
for(int i = 0; i < array.length; i++){
if(array[i]<0)
throw new IllegalArgumentException();
}
}
//method reverse.
public static void reverse(int[] array) {
//reverse order of element within the array
int i, k, t;
int n = array.length;
for (i = 0; i < n / 2; i++) {
t = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = t;
}
reverse(array, array.length-1);
}
//helper method
public static void reverse(int[] array, int n){ //reverse the order of the number for each element in the array
// n, number of elements in the array
if(n>=0){
int Element = array[n]; //element n in array
int NewElement = -1;
int Digit = -1;
String s = "";
if(Element<10)
s = Element + "";
while(Element >= 10){ //loop up to element is reduced to one digit number
Digit = Element%10;
s = s + "" + Digit; //save the digits
NewElement = Element/10;
if(NewElement < 10) //when NewElement has 1 digit left
s = s + "" + NewElement;
Element = NewElement;
}
System.out.print(s + " "); //print digit
reverse(array, n-1); //recursive call
}
}
}
This can be fixed simply by inserting continueInput = true in your outer while loop. Without that, continueInput will always be false after the first time you enter a valid input, and your do-while loop will always exit after one iteration.
However, I wouldn't suggest throwing exceptions yourself, and you should probably handle Scanner's InputMismatchException. Also, your reverse method is unnecessarily complicated. Here's the code I got:
import java.util.Scanner;
public class ReverseNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
String another = "y";
while (another.equalsIgnoreCase("Y")) { //loop to re-run program
boolean continueInput = true; //controls loop for input
outer: do {
System.out.print("\nEnter " + numbers.length + " positive integers: ");
try {
for (int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
if (num < 0) {
System.out.print("Invalid input, found a negative integer " + num)
continue outer;
} else {
numbers[i] = num;
}
}
continueInput = false;
}
//handle bad inputs that aren't digits
catch (InputMismatchException ex) {
System.out.print("\nInvalid input, please enter integers");
}
} while (continueInput); //outputs
System.out.print("\nEntered numbers:\t\t");
for (int e: numbers) System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + (i == 0 ? "\n" : " "));
}
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
}

write a program that repeatedly prompts a user to supply score(out of 100) java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
write a program that repeatedly prompts a user to supply score(out of 100) on a test for 5 students once the program has real all score it should produce a table with the following headings (and automatically fill in the rest of the table) for example
Student No # Score(out of 100)
1 55
2 66
The program should them calculate the total score
Here is my code
import java.io.*;
import java.util.*;
public class test33 {
public static void main(String[]args){
Scanner kbReader = new Scanner (System.in);
int scores[] = new int [100];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 100 or negative to break.");
input = kbReader.nextInt();
if (input < 0) {
break;
} else if (input > 100) {
System.out.println("Score must be out of 100");
} else {
scores[input]++;
counter++;
sum += input;
}
} while (input > 0);
System.out.println("Score\t# of occur...");
for (int i = 0; i < 100; i++) {
System.out.println(i + "\t" + scores[i]);
}
System.out.println("The mean score is " +(sum/counter));
}
}
scores[input]++; if you want to assign value to your array scores[] you must corrected like i did below.
public static void main(String[]args) {
Scanner kbReader= new Scanner (System.in);
int scores[] = new int [100];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 100 or negative to quit.");
input=kbReader.nextInt();
if(input<0) {
break;
}
else if (input>100) {
System.out.println("Score must be out of 100");
} else {
scores[counter]=input;
counter++;
sum+=input;
}
} while (input>0);
if(counter != 0){
System.out.println("Score\t# of occur...");
for(int i =0; i<100; i++) {
System.out.println(i + "\t" + scores[i]);
};
System.out.println("The mean score is " +(sum/counter));
}
}

ending loop without use of break and convert for loop to while

this is my code
import java.util.*;
public class test3
{
public static void main (String [] args)
{
int sum = 0;
int mark;
Scanner sc = new Scanner(System.in);
for (int student = 1; student <=10; student++)
{
System.out.println("enter mark");
mark = sc.nextInt();
if (mark > 0)
{
sum = sum + mark;
}
else
{
student = 10;
}
}
System.out.println("sum is" + sum);
}
}
i want to change this code so that the loop ends without having to use student = 10 to end loop. i cant think of anything that would end the loop. and also convert it to a while loop so far i have
int student = 1 ;
int sum = 0;
int mark
Scanner sc = new Scanner(System.in);
while (student <= 10)
{
System.out.println("enter mark");
mark = sc.nextInt();
sum = sum + mark;
student++;
}
but i dont know how to end loop if 0 is input we're not allowed to use break; to exit loop could i get some help please?
The ways for ending loops are:
using break
if the condition is not satisfied in the next interation
Including the loop in a method and using return
What about this:
int student = 1 ;
int sum = 0;
int mark
Scanner sc = new Scanner(System.in);
while (student <= 10) {
System.out.println("enter mark: ");
mark = sc.nextInt();
if (mark > 0) {
sum += mark;
} else {
student = 10;
}
student++;
}
System.out.println("sum is = " + sum);
Use while (student <= 10) condition and student = 10 statement to exit the loop:
public static void main(String[] args) {
int sum = 0;
int mark;
Scanner sc = new Scanner(System.in);
int student = 1;
while (student <= 10) {
System.out.println("enter mark");
mark = sc.nextInt();
if (mark > 0) {
sum = sum + mark;
} else {
student = 10;
}
student++;
}
System.out.println("sum is" + sum);
}

Java skipping a number in the sequence

This is very interesting, i notice. Before i can explain further its best i show the code and you will understand what i mean.
This is the code:
public class Qn3 {
static BigDecimal[] accbal = new BigDecimal[19];
private static Integer[] accnums = new Integer[19];
public static void main(String[] args) {
addaccount();
}
public static void addAccount() {
int i = 0, accno, input, j, check;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
Scanner in = new Scanner(System.in);
accnums[1] = new Integer(1);
while (accnums.length >= count(accnums)) {
System.out.print("Enter the account number: ");
while (sc.hasNext("[0-9]{7}")) {
accno = sc.nextInt();
System.out.print("Enter account balance: ");
accbala = in.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null)
break;
else if (accnums[j].equals(accno)) {
break;
}
}
if (j == accnums.length) {
System.out.print("No more than 20 accounts can be added.");
} else if (accnums[j] != null) {
if ((accnums[j].equals(accno)))
System.out.println("Account already exists");
break;
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
check = j;
System.out.println("Current number of accounts in the system: "
+ (check + 1)
+ "\nNumber of accounts still can be added: "
+ (20 - (check + 1)));
}
}
while (!sc.hasNext("[0-9]{7}")) {
System.out.println("Wrong NRIC");
break;
}
while (accnums.length <= count(accnums)) {
System.out.println("20 accounts have already been created");
break;
}
break;
}
}
private static int count(Integer[] array) {
int count = 0;
// accnums = new Integer[] {1,2};
for (int index = 0; index < array.length; index++) {
if (array[index] != null) {
count++;
}
}
// System.out.println("You have used " + count + " slots");
return count;
}
}
So now that you have seen the code the problem that is hard to notice is this, take note of the line in the addaccount() method where
System.out.println("Current number of accounts in the system: "+(check+1)+"\nNumber of accounts still can be added: "+(20 - (check+1)));
this line the first check+1 will give me 1 then the next one gives me 3! and then the next time i run the method it gives me 4 and then again 5 and so on so forth, what is happening to 2?
You have that println in an else block, and when j == 1 you're hitting the else if case. Try removing this line
accnums[1] = new Integer (1);

Categories