Array to input 100 numbers - java

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.

Related

How to check whether the key number is repeated in the array?

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");

How to write a program which can continuously ask users for inputs until the inputs meet a specific requirement to run the code?

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

Input inside Arrays (java)?

So, I have a very messy code. The purpose of the code is to find the minimum and maximum values of a set of numbers that the user entered using arrays. The problem is I don't know how to put the Array elements (Elements) into my array (numbersArray). Here's what I have so far :
package com.company;
import java.util.*;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner elements = new Scanner(System.in);
System.out.println("Enter in number of numbers:");
String num = elements.nextLine();
int numArrayElements = Integer.parseInt(num);
System.out.println("Enter in numbers please: ");
Scanner console = new Scanner(System.in);
String userInput = console.nextLine();
int Elements = Integer.parseInt(userInput);
int [] numbersArray = new int[numArrayElements];
int sum = 0;
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
numbersArray[i] = temp;
sum += temp;
}
Arrays.sort(numbersArray);
System.out.println((sum - numbersArray[numbersArray.length-1])
+ " " + (sum - numbersArray[0]));
}
}
How can I make it so that I can put Elements into numbersArray?
Your major problem is the part where you try to read values entered by the user:
for (int i = 0 ; i < numbersArray.length ; i++) {
int temp = numArrayElements.nextInt();
...
}
The variable numArrayElements is of type int, you can't call a method nextInt on it, it does not exist.
The method, however, exists for objects of type Scanner, like your elements variable.
After that your code probably compiles and does something useful. At least you set the array items correctly by using
numbersArray[i] = temp;
I'm not that sure about the min/max part though. I don't get why you need the sum if you sort the array. After sorting you can just take the first (min) and last element (max) given by numbersArray[0] and numbersArray[numbersArray.length - 1].
And I'm not sure why you do the parsing stuff in between, does not seem necessary. Same holds for the second scanner, not needed since you already have one.
Let me show you a cleaner approach.
Scanner scanner = new Scanner(System.in);
// Amount of values
System.out.println("Enter amount of values:");
int amount = scanner.nextInt();
// Read values
System.out.println("Enter " + amount + " values:");
int[] values = new int[amount];
for (int i = 0; i < values.length; i++) {
values[i] = scanner.nextInt();
}
// Compute max and min
...
For the last part you have several options. The most efficient would probably be to remember it already at the moment where you read the values. Your sorting approach works too, but is much more work than needed since you don't need the order of all elements, you only need the min and max element.
Let's first do a manual approach
// Compute max and min
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int value : values) {
if (value > max) {
max = value;
}
if (value < min) {
min = value;
}
}
The second approach uses a built-in method which essentially does the same. However, it is less efficient since we will first need to built a Collection on top of the array and then do two iterations instead of only one (one for max, one for min). Also, due to the conversion we need wrapper objects Integer instead of primitive values int.
// Compute max and min
Collection<Integer> valuesAsColl = Arrays.asList(values);
int max = Collections.max(valuesAsColl);
int min = Collections.min(valuesAsColl);
The third approach uses the Java Stream API (since Java 8), looks elegant and does not need to convert stuff to Integer or Collection. But the two iterations instead of one remain.
// Compute max and min
int max = Arrays.stream(values).max();
int min = Arrays.stream(values).min();
I not understand your ask .. however this code for set array size from user and numbers of array by user..
public class JavaApplication2 {
public static int[] numbers() {
Scanner element = new Scanner(System.in);
System.out.print("please insert array long : ");
int count = element.nextInt();
System.out.print("enter numers : ");
element.nextLine(); // throw away the newline.
int [] numbers = new int[count];
Scanner numScanner = new Scanner(element.nextLine());
for (int i = 0; i < count; i++) {
if (numScanner.hasNextInt()) {
numbers[i] = numScanner.nextInt();
} else {
System.out.println("You didn't provide enough numbers");
break;
}
}
return numbers;
}
public static void main(String[] args) {
int[] numbersa = numbers();
System.out.println(Arrays.toString(numbersa));
}
}

Read in 5 numbers from a user and compute the frequency of positive numbers entered

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);

Finding the largest number in an array of integers

I am trying to recursively find the largest element in an array. The user has to input the number of elements that the array will have. My error is that if that the list does not have an element which is larger than the number of elements in the list, the output of the largest number will be the number of elements in the list. eg: array of 5 integers containing {1 1 1 2 3}. the answer will be 5 and not 3.
import java.util.*;
public class test7 {
public static int findLargest(int[] a, int max) {
int i=0, j=0, tempmax=0;
if (a.length == 1) return a[0]>max ? a[0]:max;
else if(max < a[i]){
max = a[i];
int[] tempArr = new int[a.length -1];
for (i=1; i<a.length; i++){
tempArr[j] = a[i];
j++;
}
tempmax = findLargest(tempArr, max);
return tempmax;
}
else{
int[] tempArr = new int[a.length -1];
for (i=1; i<a.length; i++){
tempArr[j] = a[i];
j++;
}
tempmax = findLargest(tempArr, max);
return tempmax;
}
}
public static void main(String[] args) {
int[] values = new int[100];
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of elements in your list: ");
int x = scan.nextInt();
if(x>1 || x<100){
for (int i=0; i<=(x-1); i++){
System.out.print("Enter your number: ");
System.out.println();
values[i] = scan.nextInt();
}
System.out.println();
System.out.println("The largest number is: "+findLargest(values, x));
}
else System.out.println("The maximum number of elements must be less than 100");
}
}
You call your method with:
System.out.println("The largest number is: "+findLargest(values, x))
This tells it to assume the largest number is x and try to find anything in the list that is greater than that. Of course, this produces the exact problem you described.
In general, when finding a maximum number, you want to initialize your candidate to the lowest number possible, or to the first number in your array.
If you initialize to the lowest number possible (Integer.MIN_VALUE) then as soon as you start your algorithm, the first number will definitely be bigger than it and will be chosen as the next candidate for maximum.
If you initialize to the first item in your array, then if that number is the highest, all well and good. If it is not, then when you encounter the next higher number, it will become the candidate, and all is good.
Which one you choose is up to you (and depends also on whether an empty array is possible), but the thing to remember is never to select an initial candidate that might be greater than all the elements in the array.
Try this working example:
public static void main(String[] args)
{
int[] numbers = {2, 5134, 333, 123, 8466};
int largest = numbers[0];
for(int i = 1;i<numbers.length;i++)
{
largest = Math.max(largest, numbers[i]);
}
System.out.println("Largest number: "+largest);
}
As a method that would look like this:
public static int max(int first, int... more)
{
for(int element:more)
{
first = Math.max(first, element);
}
return first;
}
You can then call it using something like max(1,23,564,234,543);

Categories

Resources