Counting unique numbers from int array - Java [duplicate] - java

This question already has answers here:
counting occurrence of numbers in array
(6 answers)
Closed 8 years ago.
I am trying to build and array where the user enters numbers. Then at the end the program outputs a list of the entered numbers along side the amount of times each individual number was entered.
Currently I have:
package arraypractice;
import java.util.Scanner;
public class Entry {
private Scanner scan = new Scanner(System.in);
public void userInput(){
System.out.println("Please tell me the amount of numbers you will be $ entering: ");
int [] arr = new int[scan.nextInt()];
for(int i=0;i<arr.length; i++) {
scan = new Scanner(System.in);
System.out.println("Please enter a number: ");
while(scan.hasNextInt()){
int x = scan.nextInt();
arr[i]= x;
break;
}
}
for(int i:arr){System.out.println(i + " occurs");
}
}
}
For example this outputs:
run:
Please tell me the amount of numbers you will be $ entering:
2
Please enter a number:
25
Please enter a number:
21
25 occurs
21 occurs
BUILD SUCCESSFUL (total time: 10 seconds)
In a perfect world I would like to output to look like this:
run:
Please tell me the amount of numbers you will be $ entering:
2
Please enter a number:
25
Please enter a number:
21
Number Times Entered
25 occurs 1
21 occurs 1
BUILD SUCCESSFUL (total time: 10 seconds)
I am not sure how to implement this. A second array? If so how? Also is there a way I can get the headings Number and Times Entered?
You are not seeing a main method because it is in another class that instantiates this.
Thanks.

To get a heading you just put a println() method before you run the for loop to print out the array.
It seems like you want to format the print out. To do that you would need to use
printf("%6d%10s%6d", i, "occurs", array[i])
That's the general idea.

Related

How can i input multiple times in one line? [duplicate]

This question already has answers here:
How to read multiple Integer values from a single line of input in Java?
(21 answers)
Closed 1 year ago.
How can I input multiple times in one line?
public class Awit {
static void numbers(){
Scanner user = new Scanner(System.in);
int arraylist[] = new int [5];
System.out.println("Enter five integers:");
System.out.print("");
for(int i = 0; i<=4; i++){
arraylist[i] = user.nextInt();
}
public static void main (String []args){
numbers();
}
}
Output:
Enter five integers:
1
2
3
4
5
I want the output to be like this
1 2 3 4 5
The program that you have written will read multiple numbers from a line ... if you give it multiple numbers on a line.
$ java Awit.java
Enter five integers:
1 2 3 4 5
$
The only issues with the code you have written are:
it is missing an import for Scanner, and
there is a } missing at the end of your numbers method.
Those problems will give compilation errors. Assuming that you correct them, you will not get any output (apart from the prompt to enter some numbers) because your program doesn't print the array(!)
If you want to know how to print the numbers, read the following:
What's the simplest way to print a Java array?

Finding the average of certain numbers out of a text file

Here is my code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class QuestionTwo
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.println("Please enter a file name");
Scanner keyboard = new Scanner(System.in);
double average;
double numbertocheck;
int length;
String filename = keyboard.next();
Scanner reader = new Scanner (new File(filename));
length = reader.nextInt();
//Here is where I would put the statement that says "File is not found, enter the filename again"
System.out.println("The number to check: ");
numbertocheck = keyboard.nextDouble();
if (length > numbertocheck)
{
//here is where I would put the average calculation
System.out.println("The average of the numbers that are greater than" + numbertocheck + "is " /**+ average*/);
}
}
}
with the text file looking as such:
30
44
23
56
43
2
32
35
90
12
My output comes out to nothing; it simply asks the two questions and draws a blank (even before I made a bunch of things into comments). This code is attempting to answer the question:
"Write a program that asks the user to enter the name of a file that contains a set of integer values, and then asks the user to enter an integer number.
The program should display the average of the numbers
that are greater than the input number. Use Notepad or another text editor to create a simple file that can be used to test the program.
First, the user enters the file name as below:
Enter the file name: input.txt
and if, for example, the file ‘input.txt’ contains the following numbers:
30
44
23
56
43
2
32
35
90
12
and then, if the user enters an integer number, as:
The number to check: 40
the program should display the output as:
The average of the numbers that are greater than 40 is 58.25
Note that average of numbers 44, 56, 43 and 90 is 233/4 = 58.25. The average must be shown up to two decimal points.
If the input file is not found, the user must be prompted to enter the filename again with the following message
“File is not found, enter the filename again”.
Which will then prompt the question to be again until a valid file is found."
The problems arise for me when it comes to parsing the text file and finding the average of the numbers greater than the value asked for. That and looping the question asking the user to enter the file name and then repeating that question until a file is found. I have thought of using the Decimal format class, but do not know how to properly utilize it. Any help would be appreciated!
My first comment is you might want to take some lessons. This is pretty basic stuff.
But to answer your question, use a while loop, with an if/else statement inside, to get proper input.
For your next problem, you probably want to use .nextLine instead of .next, because some file names have spaces in them.
Third problem, use a for loop to check each integer one at a time, and compare it to the range needed. Then use if/if else statements/switch statements and an array to store the values, and after all values are checked, do the math on the content of the array.
Again, i highly recommended taking some basic java lessons.

why the exception is thrown when it should not [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I'm creating a program of letting people enter 10 integers and display them from the smallest to the largest. Here is my program:
import java.util.Scanner;
public class EnterTenNumbers {
public static void main(String[] args){
System.out.println("Enter 10 numbers");
int small=0;
for(int i=0; i<10; i++){
Scanner in=new Scanner(System.in);
int[] i1=new int[10];
int num=in.nextInt();
i1[i]=num;
if(i1[i]<i1[i+1] || i1[i]==i1[i+1]){
System.out.println(i1);
}else if(i1[i]>i1[i+1]){
i1[i+1]=i1[i];
System.out.println(i1);
}
}
}
}
When I run my program, after the user input the numbers, such things like "[I#55f96302" appear.
And after the user entered 10 integers, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at EnterTenNumbers.main(EnterTenNumbers.java:13)
appears while it should display the numbers from smallest to largest.
What happened?
Every time you are asking the user to give a number as input, you are creating a new array of integers. Aren't you supposed to create only one array to hold those 10 integers ? So, declare the integer array outside the loop. in this way, it will be declared only once.
You have to take all the 10 integers from user at the very beginning, then you have to run the operations over these 10 integers in order to show them from smallest to the largest.
after taking all the 10 integers from user and saving them in An array, you have to again loop through among those numbers one by one and check which number is smallest and which number is largest. When the loop check the last index of the array, you can't check the next index of that array (because that index of the array doesn't exists). That's why you are having an exception every time.
if(i1[i]<i1[i+1] || i1[i]==i1[i+1]){
System.out.println(i1);
}else if(i1[i]>i1[i+1]){
i1[i+1]=i1[i];
System.out.println(i1);
}
When I run my program, after the user input the numbers, such things
like "[I#55f96302" appear.
This is because you are printing the string representation of your array, not the elements of the array.
Replace
System.out.println(i1);
with
System.out.println(i1[i]);
And after the user entered 10 integers, Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 10
As the exception clearly indicates, you are trying to access 10th index (index starts from 0) or 11th element of the array. But your array has only 10 elements. So that's why you get AIOOBE. In your conditional statement, the predicate i1[i+1] becomes i1[10] when i=9. You need to fix this.
Lastly, you can achieve your objective the following way too:
System.out.println("Enter 10 numbers");
int small=0;
for(int i=0; i<10; i++){
Scanner in=new Scanner(System.in);
int[] i1=new int[10];
int num=in.nextInt();
i1[i]=num;
}
Arrays.stream(i1).sorted().forEach(System.out::println);

Java program makes user enter same input twice to run after initial input error

I am having problems with my program. Everything is running smoothly, however, when the user inputs the wrong variable it does display the right feedback, but the user then has to enter one extra variable than previously stated.
Maybe it's a simple mistake I have made, but I can't see it..
It's confusing. An example when I run the program:
How many grades would you like to average?
3
Please enter 3 grades:
90
jf //Intentional user input error
You've entered a non-numerical variable. Please enter a number:
95
100 //The program should go ahead and calculate the average after this is entered
100 //It should not expect this fourth input if the amount of grades is 3
Your average is: 96.67
The second 100 input in the console should not appear, but it does when the user has at least one input error. If I were to run the program and input all the correct variables, then the program works smoothly.
This error also occurs when asking for how many grades the user would like to average. I thought it'd be easier to view what's wrong with my program by the second part.
I'm trying to get this program to run smoothly. Help is appreciated!
for (gradesCount = 0; gradesCount < gradeNumber; gradesCount++) {
// Check if the input variables are numerical variables
while (!input.hasNextDouble()) {
input.next();
System.out.println("You've entered a non-numerical variable. Please enter a number: ");
while (input.nextInt()<= 0){
System.out.println("You've entered a negative number. Please eneter a positive number: ");
}
}
// Read grade input
gradesInput = input.nextDouble();
Instead of input.hasNextDouble() you can try below
Scanner scan = new Scanner(System.in);
System.out.print("Enter total no of input ");
int total = Integer.parseInt(scan.nextLine());
int[] input = new int[total];
for (int i = 0; i < total; i++) {
while (true) {
try {
System.out.print("Enter number ");
String in = scan.nextLine();
input[i] = Integer.parseInt(in);
break;
} catch (RuntimeException re) {
System.err.print("Invalid input. ");
}
}
}
scan.close();
System.out.println(Arrays.toString(input));
It'll force the user input only numbers, you can add boundaries or change data type if required.

scan the array input [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Array sorting input
Implement a program to process votes for 5 candidates in a talent
contest.
The program should use a String array to hold the names of the 5
candidates and an integer array to record the number of votes for each
contestant.
It should prompt the user to enter the number of the candidate they
wish to vote for (in the range 0 – 4), until -1 is entered, which
signifies the end of voting. An error message should be output if the
candidate selected is not in the required range.
At the end of voting, the program should sort the votes into
descending order and output them, before outputting messages showing
who was in 3rd, 2nd and 1st place
Well, so far I had some failures that's all. I will not have any problem with sorting and swapping the input. But the input itself is a pain for me.
//exam result processing - using selection sort
import java.util.*;
public class VoteCount {
public static void main(String[] args) {
//create empty array
int[] votes = new int[5];
//input data
input(votes);
}
public static void input(int[] votes)
{
Scanner kybd = new Scanner(System.in);
System.out.println("Enter vote number of the candidate results: ");
int votecount = kybd.nextInt();
while (votecount !=-1)
{
votes[votecount]++;
System.out.println("Candidate" + votes +"Has" +votecount + "votes");
}
}
}
you have to read the user's input inside the while cycle, like this:
Scanner kybd = new Scanner(System.in);
System.out.println("Enter vote number of the candidate results: ");
int votecount = kybd.nextInt();
while (votecount !=-1)
{
votes[votecount]++;
System.out.println("Candidate "+names[votecount]+" Has "+votes[votecount]+" votes");
System.out.println("Enter vote number of the candidate results: ");
votecount = kybd.nextInt();
}
in additional, "votes" is an array, so printing in will give you something like "0#562fb45", so let's say you wil create some "names" array, which will hold the candidates names, like this for example:
String names = {"Peter", "Tomas", "Jonny", "Mark", "Jane"};
You should use kybd.hasNext() to test whether there is any more vote number. and you can input in the terminal like this:
0,1,2,1,3
and modify while() to:
while(kybd.hasNext())
there is no need of -1 to end input, and you have to input all vote number in one line. you can use <space>、comma or <Tab> to split vote numbers.

Categories