I am attempting to create a small java program where the user will enter a string of numbers such as 2 4 6 7 8 9 0 3 4 5. These numbers will be saved to an array of int[] type. I then need the program to calculate how many of each number has been entered and output 2 columns, one containing the number entered and the other containing the amount of times the individual number was entered. Using the above numbers, I need the output to be as below:
Number Times Entered
2 1
4 2
6 1
7 1
8 1
9 1
0 1
3 1
5 1
So far I am using 3 classes. An application class that contains the main method, a driver class and the class containing the logic and objects. At this stage I have only started work on the class containing the logic. The code I have so far is below:
package arrayentry;
import java.util.Scanner;
public class Entry {
private Scanner scn = new Scanner(System.in);
private int[] count = new int[51];
public void countNumberEntry(int[] countArray){
int input = scn.nextInt();
for (int i=0; i<10; i++)
if (input == i)
count[i]++;
}
public void dataEntry(){
System.out.println("Please enter numbers between 1 and 50");
count = scn.nextInt[]();
}
}
Any ideas as to how I can get this to work would be greatly appreciated, this is driving me up the wall.
Thanks.
EDIT: To elaborate, I am have issues with everything. I for some reason can't get my head around it. I have read books etc but I can't get it. I need to store the entered numbers into an array of 50, then calculate the amount of times each number is entered and output as above.
To be honest I am just trying to get a grip / start on this.
You can create another array that will store number of occurences for you
public int [] countOccurences(int originalArray[]){
int countedOccurencesArray[]= new int [51];
for(int i=0;i<originalArray.length){
contedOccurencesArray[originalArray[i]]++;
}
return countedOccurences;}
This would actually be easier with a HashMap. Every time you read a number, check to see if it's in the map. If it is, increment the count, otherwise, insert it with a count of 1.
Since this assignment requires arrays, you'll want to create 2 50-cell arrays. In 1, store the value of the number read, in the second, store the count. Put both values in the cell that corresponds with the number read. Then just print off the values you need.
package arrayentry;
import java.util.Scanner;
public class Entry {
private Scanner scn = new Scanner(System.in);
private int[] numbers = new int[51];
private int[] count = new int[51];
public Entry() {
// All counts start at 0, all numbers start at -1 (invalid, so we know it's not from user input)
for (int cell = 0; cell < count.length; cell++) {
count[cell] = 0;
values[cell] = -1;
}
}
public void dataEntry(){
System.out.println("Please enter numbers between 1 and 50");
int[] input = scn.nextInt[]();
for (int value : input) {
numbers[value] = value;
counts[value] += 1;
}
}
public void printCounts() {
System.out.println("Number\tTimes Encountered.");
for (int cell = 0; cell < numbers.length; cell++) {
// Don't print counts of any number we didn't see in the input.
if (numbers[cell] > 0) {
System.out.println(numbers[cell] + "\t" + counts[cell]);
}
}
}
}
Related
i am writing a java program, i want the user to enter 5 numbers within the range 10 and 100 if the user enters any number less than 10 or greater than 100, or a repeated number, it should ask me for a number to replace it with, but my program just puts a zero (0).so if i put any repeated number my program just stores it in the array as zero, i want it to ask me what number i want to replace it with then store the new number.
here's a segment of my code:
while (wahala < thearray.length)
{
System.out.print("Enter the number you want: ");
for (int w=0; w<5; w++)
{
value=input.nextInt();
if (value>=10 && value<=100)
{
boolean containsNumber = false;
wahala++;
for(int j=0; j<thearray.length; j++)
{
if (array[j]==value)
{
containsNumber=true;
break;
}
}
if (!containsNumber)
{
array[w]=value;
count++;
}
else
System.out.printf("%d has already been entered\n", value);
}
else
System.out.println("Number must be between 10 and 100");
}
for (int element: array)
{
System.out.println(element +"");
}
}
Nowhere in your sample code do you prompt the user for a new number.
Also, if the array has to avoid duplicates, consider using a Set instead, so that you can quickly check if a duplicate has been entered.
Ex (Java 10):
private final int maxValues = 5;
private int input;
var intSet = new HashSet<Integer>();
while(intSet.size() < 5 && askedAndReceivedInput())
if(intSet.contains(..some input))
//ask again
else
intSet.put(someInput);
You can make the input-reading function however you wish..
Also please note that you're finding zeroes in your array because that's what java fills it with upon creation. It's the default value, this is guaranteed by the language spec.
I am trying to get the number of pattern to printout from the array but under my number of pattern no pairs were printed out this is an example of what i am trying to get
(Array: 2 7 2 3 1 5 7 4 3 6
Number of patterns: 3)
but I do not know what to write from beyond number of patterns
The code:
public class FindIt {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int Sum = 0;
int[] InsertNumbers = new int[10];
System.out.println("Sample output #1:");
System.out.print("Array: ");
for(int i = 0; i < 10; i++)
{
InsertNumbers[i]=(int)(Math.random()*10)+1;
System.out.print(InsertNumbers[i] + " ");
}
System.out.println("");
System.out.print("Array: ");
for(int i = 0; i < 5; i++)
{
ComputePattern(InsertNumbers, Sum);
System.out.print(InsertNumbers[i] + " ");
}
System.out.println("");
System.out.print("Number of patterns: ");
}
public static void ComputePattern(int[] InsertNumbers, int Sum)
{
for(int i = 0; i < 2; i++)
{
InsertNumbers[i] = Sum;
Sum = Sum + Sum;
}
}
}
It is quite hard to understand your code but here is what I can tell you.
You have managed to get to ask the user input but I feel that the following would be better.
Instead, try having two arrays, one which the user can input 10 integers, and the other array with the sum of the pairs, hence an array containing 5 integers.
With the help of a For Loop and a formula, you can use it to get the 2 consecutive values. The first formula being x*2, the second being (x*2)+1.
With x being 0 in the for loop, and loop it for 5 times.
Afterwards, you get the values of the x*2 and the (x*2)+1 in the array, and sum them together.
Then with the sum, you can then use it to calculate the count of patterns.
Suggestion : Try to be consistent with your println and print. It is quite confusing and I am not quite sure as to why you have set println for certain text and print for the rest.
No patterns were printed because you have no print statements after you print Number of patterns.
Chandu's girlfriend loves arrays that are sorted in non-increasing order. Today is her birthday. Chandu wants to give her some sorted arrays on her birthday. But the shop has only unsorted arrays. So, Chandu bought T unsorted arrays and is trying to sort them. But, he doesn't have much time to sort the arrays manually as he is getting late for the birthday party. So, he asked you to write a program to sort the T arrays in non-increasing order. Help him, or his girlfriend will kill him.
Input:
First line contains an integer T, denoting the number of test cases.
First line of each test case contains an integer N, denoting the size of the array.
Second line contains N space separated integers, denoting the array elements Ai.
Output:
For each test case, print the sorted array in non-increasing order.
Constraints:
1 <= T <= 100
1 <= N <= 105
0 <= Ai <= 109
MYApproach
My first approach is to code the solution using simple approach.For this,I tried BubbleSort Algorithm.But in the last TestCase,I am not getting Expected Output.I Used bubble sort to sort the elements which compares adjacent element for every iteration of k in sort loop.Thus,The smallest element will go at the end
Can anyone guide me Why?
Below is the Code:
public static void main(String args[] ) throws Exception
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();//Take the int Input from user
sc.nextLine(); //to move to nextLine after consuming token
int NoOfElements=sc.nextInt();
sc.nextLine();//to move to nextLine
int x[]=new int[NoOfElements];
for(int i=1;i<=T;i++)
{
for(int j=0;j<NoOfElements;j++)
{
x[j]=sc.nextInt();
}
sort(x);
}
}
public static void sort(int p[])
{
for(int k=0;k<p.length-1;k++)
{
//bubble sort
for(int i=0;i<p.length-k-1;i++)
{
if(p[i]<p[i+1])
{
//swap
int temp=p[i];
p[i]=p[i+1];
p[i+1]=temp;
}
}
}
for(int m=0;m<p.length;m++)
{
System.out.print(p[m]);
System.out.print(" ");
}
System.out.println();
}
}
Input
2
5
2 5 2 4 3
5
5 4 2 3 1
My Code's Output
5 4 3 2 2
5 5 4 3 2 //Why I am getting 5 here.I could not correct it.
Expected Correct Output
5 4 3 2 2
5 4 3 2 1
You are only reading the number of elements once. Not once per test case.
Below I have updated your code to read the NoOfElements once for each test case and allocate an array there as well.
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System. in );
int T = sc.nextInt(); //Take the int Input from user
sc.nextLine(); //to move to nextLine after consuming token
for (int i = 1; i <= T; i++) {
int NoOfElements = sc.nextInt(); // THIS LINE MOVED INTO LOOP
sc.nextLine(); // THIS LINE MOVED INTO LOOP
int x[] = new int[NoOfElements];
for (int j = 0; j < NoOfElements; j++) {
x[j] = sc.nextInt();
}
sort(x);
}
}
According to Pascal's triangle,the value of every number is nCr where n is the row number and r the column number.
The problem seems to be where I pass the values to the arraylist, it doesn't show errors but it doesn't do anything either.
import java.util.*;
class arl5
{ public static void main(String []ar)
{ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of rows: ");
int k= sc.nextInt();
for(int m=0;m<k; m++)
{ al.add(new ArrayList<Integer>()); //initialize column list
}
for ( int i=0; i<al.size();i++ )
{ for ( int j=0; j<al.get(i).size(); j++)
{ int n = ncr(i,j);
al.get(i).add(2);
System.out.print(al.get(i).get(j)+" ");
}
}
}
public static int fact(int s)
{ int fact =1;
for(int i=0;i<s;i++)
fact*=i;
return fact;
}
public static int ncr(int n, int r)
{ int sub = fact(n-r) * fact(r);
int f= fact(n)/sub;
return f;
}
}
Given that you are asking the use for the number of rows, you should be providing an input bound or switching to longs or BigInteger. The results in the table overflow ints with an input of only 35, but the intermediate calculations overflow on row 14, since fact(14-1) is greater than 4 billion. Try calculating using the "add two above" method (see below) instead of actually calculating the combination values.
Now onto your problem. In your for loop in main that does all the assigning of values for each of the combinations, you calculate the combination and store it in a variable called n, then add the constant 2 to the ArrayList. You calculate the combination but then never use it.
Add Two Above method (in case you don't know):
Given:
1
1 1
1 2 1
_ _ _ _
The first and last blanks on any row are 1.
The middle blanks are equivalent to the sum of the two numbers above the blank
So the last row would be:
1, since it is the first blank in a row
3, since 1 + 2 is 3
3, since 2 + 1 is 3
1, since it is the last blank in a row
I am trying to make a program wherein a user will be prompt on how many inputs to input. I have 3 user inputs in my multi array, if the user will input 1 then only one user input will appear. Otherwise, if the user inputs 2 or 3, then 2 or 3 user inputs will appear. Upon testing my program, it ran, but the java.lang.ArrayIndexOutOfBoundsException error appeared. I can't seem to find the error in here, I've tried adding extra index on my multi array but I still get the same error.
import java.io.*;
public class student {
private int stud_id;
private String stud_prog;
Object ctr1;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Object stud [][] = {{1,2,3},{"enter name:","enter age:","enter gender:"}};
public void stud() throws NumberFormatException,IOException{
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
for (int x = 1; x<=num1;x++){
for (int i = 0 ; i<num1;){
System.out.println(stud[x][i]);
ctr1 =in.readLine();
i++;
}
}
}
}
///////////////////////////////////////////////////////////////////main/////////////////////////////////////////////////////////////////////////////////
import java.io.IOException;
public class persontest {
public static void main(String[]args) throws NumberFormatException,IOException{
student s = new student();
s.stud();
}
}
Array index starts from 0 and end to length-1
Change:
for (int x = 1; x<=num1;x++){
To:
for (int x = 0; x<num1;x++){
First check for length of array before iterating
if(num1<=stud.length){
for (int x = 0; x<num1;x++){
....
}
}
Note: Multidimensional array can contains variable no of columns. You should use stud[row].length to get the no of columns of any row.
stud.length gives no of rows
stud[i].length gives no of columns of ith row
As per comment
what I mean is that if the user inputs 1 then 1 user attribute will appear, if 2 then 2 and so on...
Is this what are you looking for?
String stud[] = { "enter name:", "enter age:", "enter gender:" };
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
if (num1 <= stud.length) {
for (int x = 0; x < num1; x++) {
System.out.println(stud[x]);
//read input from user
}
}
Java uses zero-indexed arrays, meaning that counting starts at 0 (not 1!), 1, 2, 3, 4...
This means that when you attempt to reference array[4], it's actually getting the fifth element in the array (and if it doesn't exist? ArrayIndexOutOfBoundsException!)
You can fix your for-loops by changing it to look like this; it starts with zero, and goes up to (but not equaling) num1.
for(int x = 0; x < num1; x++) {
for (int x = 1; x<=num1;x++){
for (int i = 0 ; i<num1;){
System.out.println(stud[x][i]);
ctr1 =in.readLine();
i++;
}
}
Here it will run in two for loop. first one start from 1 to num1. but in next iteration invoking stud[x][i] x will be 2 . but stud has index 0,1 only. Please check your logic