How to get the repeated number from the key(b) my program is like this a user enter 166456 and key = 6 then the output must be like 6 is repeated 3 times in the array please also show me if this can be done without array
I am even getting error for int cannot be to int[]
int []a,i,j,count=0,b=0,n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt(System.in);
int []a=new int[n];
for(i=0;i<n;++i)
{
a[i]=sc.nextInt();
}
System.out.println("Which nuber would you like to find:");
b=sc.nextInt();
for(j=0;j<n;++j)
{
if(a[i]==b)
{
++count;
}
else
{
System.out.println("Not found");
}
}
System.out.println("No of time "+b+" is repeated "+count);
You are doing some wrong variable declaration. If you declare an array as int []a then it will consider all variables as an array. That's why you are getting the error. Either you can declare as an int a[] or declare other variables on a different line.
Please refer below code,
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int []a;
int b=0, count=0;
int i, j, n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
a=new int[n];
for(i = 0; i < n; ++i)
{
a[i]=sc.nextInt();
}
System.out.println("Which nuber would you like to find:");
b=sc.nextInt();
for(j=0;j<n;++j)
{
if(a[j]==b)
{
++count;
}
else
{
System.out.println("Not found");
}
}
System.out.println("No of time "+b+" is repeated "+count);
}
}
Output
6
1
6
6
4
5
6
Which nuber would you like to find:
6
Not found
Not found
Not found
No of time 6 is repeated 3
As far as I have understood the requirement, You need help regarding finding out the total frequency of the digit from the user's input. (Assuming digits will be only from 0 to 9. Correct me If I am wrong on this assumption).
So, for this, we can just use the integer array of size 10 to store each digit's frequency. For example, consider the input of total 6 digits - "166456". Our integer array's value will be (from index 0 to 9) 0100113000. So, we can directly return the index of the digit we want to search, in this example return value of array[6] which is 3.
int[] num=new int[10]; // storing each digit's frequency
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // count for total digits
for(int i=0;i<n;i++){
int index = sc.nextInt();
num[index]++;
}
System.out.println("Which number you would like to find out?");
int b = sc.nextInt();
if(num[b]!=0)
System.out.println("No. of time "+b+" is repeated "+num[b]);
else
System.out.println("Not found");
Related
I have to write a program that starts by requesting an integer in the range 0 < N < 20. Numbers outside this range are rejected and a new request is made. Output the sum of the sequence of numbers starting at 1 and ending with N.
I have got most of the codes but I can not continuously ask users for inputs until an input meets the requirement. I tried to use "return" in line 11, however, it does not go back into the loop after getting another input. What should I do now?
import java.util.*;
class ExamTesterNine{
public static void main(String args[]){
Scanner kbReader= new Scanner(System.in);
int num=kbReader.nextInt();
System.out.println("Enter an integer smaller than 20 and larger than 0");
int result;
int sum=0;
if (!(num>0&&num<20)){
return;
}else{
for(int i=1; i<=num; i++)
sum=sum+i;
int [] number= new int [num];
for (int a=0; a<(number.length-1); a++ ){
number[a]=a+1;
System.out.print(number[a]+"+");}
System.out.print(num+"="+sum);
}
}
}
IT should be easy with do-while. I am not on my compiler right now however this you should add in your code if you are using scanner
import java.util.*;
class ExamTesterNine{
public static void main(String args[]){
Scanner kbReader= new Scanner(System.in);
int num = 0;
System.out.println("Enter an integer smaller than 20 and larger than 0");
do{
num=kbReader.nextInt();
} while(num<0 && num <20);
int result;
int sum=0;
for(int i=1; i<=num; i++)
sum=sum+i;
int [] number= new int [num];
for (int a=0; a<(number.length-1); a++ ){
number[a]=a+1;
System.out.print(number[a]+"+");}
System.out.print(num+"="+sum);
}
}
}
Let me know if it don't I can get on the compiler quickly however do-while is solution for you.
you will need a while loop as you do not know how many times the wrong input will be entered
while (true) {
System.out.println("Enter an integer smaller than 20 and larger than 0");
int num=kbReader.nextInt(); // get input
// test
if (goodInput (num)) {
break;
}
}
There are many different ways to approach this. However, as a start to become familiar with while loops, I recommend this simple method:
System.out.println("Enter an integer smaller than 20 and larger than 0");
int num = kbReader.nextInt();
while(num > 20 || num < 0)
{
System.out.println("That value does not meet the criteria. Please try again:");
num = kbReader.nextInt();
}
Until the correct value is entered, the user will be asked to retry their input.
To get a number, try using a check like this
int number=0;
boolean flag;
while{
flag=false;
System.out.println("Enter a number smaller than 20 and greater than 0 : ");
try{
number=kbReader.nextInt();
flag=true;
}catch(Exception e){ //catching the exception that occurs when an input other than integer is entered
System.out.println("OOPS!!!only Integer is allowed :-(");
}
if(flag==true && number>0 && number<20){
break;
}else{
if(flag){
System.out.println("Oops!!!only numbers in the range 0<number<20 is allowed...Re-enter again");
}
}
import java.util.*;
class ExamTesterNine{
static int num;
public static void readInput() {
System.out.println("Enter an integer smaller than 20 and larger than 0");
Scanner kbReader= new Scanner(System.in);
num=kbReader.nextInt();
if (!(num>0&&num<20)){
ExamTesterNine.readInput();
}else {
calculate(num);
}
}
public static void calculate(int sum) {
for(int i=1; i<=num; i++)
sum=sum+i;
int [] number= new int [num];
for (int a=0; a<(number.length-1); a++ ){
number[a]=a+1;
System.out.print(number[a]+"+");}
System.out.print(num+"="+sum);
}
public static void main(String args[]){
int result;
int sum=0;
ExamTesterNine.readInput();
}
}
Are you expecting this?
Out put:Enter an integer smaller than 20 and larger than 0
23
Enter an integer smaller than 20 and larger than 0
34
Enter an integer smaller than 20 and larger than 0
56
Enter an integer smaller than 20 and larger than 0
45
Enter an integer smaller than 20 and larger than 0
15
1+2+3+4+5+6+7+8+9+10+11+12+13+14+15=135
I need to allow the user to type exactly 100 numbers, so 100 inputs, and then print the minimum number out of those. It'd be very inefficient to type 100 .nextInt() lines and I thought that I could use an array of exactly 100 inputs and then once it's done find the min and print it out. But I do not know how to do it, so what is a simple way to do that? Thanks
You can do it without an array lets see how.
int smallest=Integer.MAX_VALUE;//assume smallest to be largest integer
for(int i=0;i<100;i++){
int num=sc.nextInt();//this will run 100 times and hence will input 100 number
if(num<smallest){//if number is smaller than smallest then num is smallest
smallest=num;
}
}
System.out.println(smallest);
Try this code sample.
I ran it on my computer and it works.
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
int [] Numbers = new int[100];
Scanner input = new Scanner (System.in);
for (int x=0;x<100;x++){
System.out.println("Enter Number");
Numbers[x]= input.nextInt();
}
int min = Numbers[0];
for (int x=1;x<100;x++){
if (Numbers[x] < min){
min = Numbers[x];
}
}
System.out.println("The Min number is :"+min);
}
}
Hope this Helps :-)
You don't need array, this example is using recursive function/method:
import java.util.Scanner;
public class Code{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
int min = prompt(sc, 1, 5); /* prompts for 5 values, change as required */
sc.close();
System.out.printf("Minium value is: %d%n", min);
}
private static int prompt(Scanner sc, int count, int times){
System.out.printf("Enter number %d of %d: ", count, times);
int n = sc.nextInt();
if(count == times){
return n;
}
return Math.min(n, prompt(sc, (1 + count), times));
}
}
thanks for asking this can be done without any array as explained in other answers but if you want to use a array declare it as
int arr[]=new int[100];
enter the values in it using a for loop,
then apply
Arrays.sort(arr);
arr[0] will be the minimum value element.
I'm trying to create a program which allows the user to addition as many pairs of numbers as they would like, by first taking user input to ask them how many sums they would like to complete (additions of 2 numbers), thereafter creating 2 arrays of whatever size the user has input, and then asking the user to input each pair of numbers on a single line that they would like to addition and storing the first value in one array and the second value in a second array from each input. This is where I am stuck, I don't know how I can take the user input as two int values on each line and store them in the respective indexes of each array to be added later. Please take a look at my code below:
import java.util.Scanner;
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
String[] input = new String[2];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
input = sc.nextLine().split(" ");
int[] intinput = Arrays.asList(input).stream().mapToInt(Integer::parseInt).toArray();
a = intinput[0];
b = intinput[1];
}
}
I think you need to change 2 lines this way:
a[i] = intinput[0];
b[i] = intinput[1];
You're using nextLine() method, which is useful for string input, but it's not the best solution for integer or other primitive data.
In addition, this line of code is wrong :
a = intinput[0];
because you're storing an integer value as integer array.
You must store that value inside a[i] in order to respect the variables type.
I'd do it this way:
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < a.length; i++) {
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
// Read pair and store it inside i-th position of a and b arrays
System.out.println("Enter first number: ");
a[i] = sc.nextInt();
System.out.println("Enter second number: ");
b[i] = sc.nextInt();
}
// Close scanner
sc.close();
// Prints every sum
for(int i = 0; i < a.length; i++){
System.out.println(i + "-th sum is: " + (a[i] + b[i]));
}
}
}
Here you read every pair with nextInt() which is specific for integer data.
Every time you store items in i-th position of arrays, so finally you can sum a[i] and b[i].
Result example:
Enter the amount of sums you would like to calculate:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
2
Enter second number:
1
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
3
Enter second number:
4
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
5
Enter second number:
6
Please enter the values you would like to sum as pairs of two numbers:
Enter first number:
7
Enter second number:
8
0-th sum is: 3
1-th sum is: 7
2-th sum is: 11
3-th sum is: 15
Just read pairs with nextInt() method of scanner, it's use all space symbols like separator (not only end of line):
public class SumsInLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the amount of sums you would like to calculate: ");
int n = sc.nextInt();
int a[] = new int[n];
int b[] = new int[n];
System.out.println("Please enter the values you would like to sum as pairs of two numbers: ");
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
}
}
Having difficulty trying to write code for this problem above. Please find the code below. Have to read in 5 numbers and compute the frequency of positive numbers entered.
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive integer");
int number = input.nextInt();
for(int i = -2 ; i < 4 ; i++)
System.out.println("Positive Count is: " + i);
}
}
Your problem is that you have a task that needs to be repeated (about the user entering a value); but your loop (the perfect mean to do things repeatedly) ... doesn't cover that part!
for(int i=-2 ; i<4 ; i++)
System.out.println("Positive Count is: " +i);
Instead, do something like:
for (int loops = 0; loops < 5; loops++) {
int number = input.nextInt();
Then of course, you need to remember those 5 values, the easiest way there: use an array; Turning your code into:
int loopCount = 5;
int numbers[] = new[loopCount];
for (int loops = 0; loops < loopCount; loops++) {
numbers[loops] = input.nextInt();
And then, finally, when you asked for all numbers, then you check the data you got in your array to compute frequencies. A simple approach would work like this:
for (int number : numbers) {
if (number > 0) {
System.out.println("Frequency for " + number + " is: " + computeFrequency(number, numbers));
}
with a little helper method:
private int computeFrequency(int number, int allNumbers[]) {
...
Please note: this is meant to get you going - I don't intend to do all your homework for you. You should still sit down yourself and figure what "computing the frequency" actually means; and how to do that.
Try this one, Remember if you only want to know the frequency(not storing)
import java.util.Scanner;
public class Lab02Ex2PartB {
public static void main (String [] args){
int i = 1;// is a counter for the loop
int positive =0;// counts positive numbers
while(i<=5){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a whole positive number");
int number = input.nextInt();
if(number > 0){
positive ++;
}
i++;
}
System.out.println("Positive Count is: "+ positive);
This is the code that I have attempted, I can get the 5 integers into the array but my problem is validating that input and giving an error message when it is not. If I put in the 5 integers and they are in the required range it works and when I input a number that is not in the required the range I get an error message which is what I want but if I enter a symbol or letter my program crashes.
import java.util.Scanner;
public class QuestionNr1 {
public static void main(String[] args) {
//Keyboard Initialization
Scanner scanner = new Scanner(System.in);
//Declare an array to hold 5 integers values
int list[] = new int[5];
int i = 0;
int sum = 0;
System.out.println("Please enter 5 numbers within the range 1 - 20, with 1 being the lowest and 20 being the highest.");
while (i < 5) {
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = scanner.nextInt();
if (value >= 0 && value <= 20) {
list[i] = value;
i++;
} else {
System.out.println("Invalid input, please enter a number with the required range of 1 - 20.");
}
}
for (int j = 0; j < list.length; j++) {
int value = list[j];
}
double average = 0;
for (int i1 = 0; i1 < list.length; i1++) {
sum = sum + list[i1];
}
System.out.print("The sum total of your five entered numbers = " + sum);
}
}
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = Integer.MIN_VALUE;
if (scanner.hasNextInt()) int value = scanner.nextInt();
else System.out.println("Please make sure the value you entered is an integer.");
You should check that the user inserts an int before assuming so (scanner.nextInt();).
You are using scanner.nextInt(); so it is expected that the text entered will be int and if you enter other then int it will throw exception
I would use scanner.nextLine() and then try to convert String into int with NumberFormatException check:
int value;
String input = scanner.nextLine();
try {
value = Integer.valueOf(input);
} catch (NumberFormatException ex) {
System.out.println("Number format exception");
continue;
}
if (value >= 0 && value <= 20)
...
If you are doing Q1 for C2 paper in DCU than its the Sum total you display at the end not the average. I was going to do add another While loop after the scanner.nextint() to test the input is a valid integer. The 3 validations would be is number an integer and is it in range and the number of integers to be entered to the array is 5. I am thinking very similar to you, its adding the extra check and where is goes in the sequence.