Java scanner count numbers that are in an interval - java

I'm new with java and i have to write a code that asks the user two numbers an interval. Then the user must introduce n numbers and the program must return how many numbers belong to that interval.
I've tried to do this and this is what i have:
import java.util.*;
public class NumsInter {
public static void main(String[] args) {
Scanner sc;
int a,b,nums,count;
sc = new Scanner (System.in);
System.out.print ("Write two numbers a and b(a<=b)(interval): ");
a=sc.nextInt();
b=sc.nextInt();
count=0;
System.out.println("write a number: ");
while(sc.hasNextInt()){
nums=sc.nextInt();
if (a<=nums && nums>=b){
count= count + 1;
} else {
count= count;
}
}
System.out.println(count +" numbers are included in ("+a+","+b+")");
}
}
Example: If the user writes 2 and 6, and then 4,4,3,1 the output should be 3.
As I am a newbie i don't know how can i do this the good way, can someoen help?
PD: How can i break the loop so i can get the output?
Thank You!

Try something like this
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter the numbers you want to test, enter 'stop' to stop");
boolean userInput = true;
while(input.hasNextInt() && userInput){
if(input.hasNext("stop")){userInput = false;}
numbers.add(input.nextInt());
}
Where you have a loop that checks if there is a next int while at the same time checking to see if the user is done or not.
And them something like this to print your answer
for(int i =0; i < numbers.size(); i++){
testNum = numbers.get(i);
if(testNum > lowerLimit && testNum < upperLimit){
count++;
}
}
System.out.println(count + " valid numbers have been entered!");

take an int [] no_between_max&min after take the input from user and store in this array. after that take a for loop and compare the value of array with max and min ant increase the count variable.
int noOfItem=sc.nextInt();
int [] no_between_max_min = new int[noOfItem];
for(int i=0;i<noOfItem;i++){
no_between_max_min[i]=sc.nextInt();
}
for(int i=0;i<no_between_max_min.length;i++){
if(no_between_max_min[i]>=a&&no_between_max_min[i]<=b){
count++;
}
}

Related

Count How many number multiple by the number from input user between a range

again I have a problem with doing practice prepare for the exam.
Would everyone help me? Thanks a lot
write a program input an integer in the range 100 to 200 inclusive. If the user enters invalid input then your algorithm should re-prompt the user until the input is valid. Your algorithm should then count how many numbers between 500 and 1000 which are multiples of the number input. Finally, the count should be output to the user. You should make good use of sub-modules.
Here my code
import java.util.*;
public class Exam3
{
public static void main(String args[])
{
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while(input < 100 || input > 200)
{
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count ++;
}
System.out.println("count is: " + count);
}
public static void int getCount(int input, int count)
{
for(int i = 499;i <= 1000; i++ )
{
if(i % input==0)
{
count++;
}
}
return count;
}
}
The algorithm should be:
Having correct input, find all multiples of it that are in range [500, 1000]. Count them.
It's a bad approach to check all the numbers, as we know from our math knowledge, that between k*a and k*a + a there is no number divisible by a.
Knowing that and having input we enlarge our temp initialized with value of input by input. If it's in range [500, 1000] we enlarge our counter. Simple as that.
public static void main(String args[]) {
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while (input < 100 || input > 200) {
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count++;
}
System.out.println(input + " fits " + count(input) + " times");
}
private static int count(int input) {
int result = 0;
int temp = input;
while (temp <= 1000) {
if (temp >= 500) {
result++;
}
temp += input;
}
return result;
}
According to your code, I see some issues. I'll point them out, as it is important for practicing Java.
Method can be either void or return int. You can't have void int. In this case, we return int, so int is the return type,
It's important to stick to Java styling. Don't put too many empty lines, keep indents.
Use Eclipse or IntelliJ (IntelliJ is more pro). They will point unused code blocks, so you would know that that getCount wasn't called.

Using a for loop, display the number of entries and the sum in Java

so I was asked to create a program in which the user enters four integers and then displays the number of entries and the sum of the integers using a for loop. This is what I came up with.
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int sum = 0;
int count = 0;
for (int i = 0; i != 4 ; i++)
{
System.out.println(" Enter an integer: ");
int num = in.nextInt();
sum = sum + num;
count = count + 1;
}
System.out.println("Number of entries: " + count);
System.out.println("Total sum of entries: " + sum);
}
}
I was wondering what a cleaner way was to ask the user for the four numbers using a for loop, and what other people might suggest be best for this situation. Thanks for any input, p.s. (I have just started learning!)
i think you are looking something like this
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum=0;
for(int i=0;i<4;i++){
System.out.println("ENter Number"+(i+1));
sum += sc.nextInt();
}
System.out.println("the Sum is "+sum);
sc.close();
}
You can check with enter. If user presses enter, you can break.
enterkey = readinput.nextLine();
System.out.print(enterkey);
if(enterkey.equals("")){
break;
}
Have a look at this solution. I cleaned it up a bit. Maybe you will find some design decisions I made which will help you in the future:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int sum = 0;
for (int count = 1; count <= 4; count++) {
System.out.print(String.format("Please enter %d. integer: ", count));
sum = sum + readNumber(scanner);
}
System.out.println("The sum of numbers entered is: " + sum);
}
}
private static int readNumber(Scanner scanner) {
do {
String input = scanner.nextLine();
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.print(String.format("Input %s is not a valid integer. Try again: ", input));
}
} while (true);
}
As you're a beginner it's the best way for getting input from the user in console. But you are for the condition should be like:
for ( int i =0;i < 4 ; i ++){}

I have been asked to make an Create a new integer array with 16 elements

Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.

Arrays with user input

I am trying to write a program that repeatedly asks the user to supply scores (out of 10) on a test.It needs to continue until a negative value is supplied. Values higher than 10 should be ignored. I also calculated the average of the inputs. After the scores have been inputted, i need to use a single array to produce a table that automatically fills the test scores and the number of occurrences of the certain test score.
I wanted it to look something like this:
Score | # of Occurrences
0 3
1 2
2 4
3 5
4 6
and so on.. P
I am a beginner and this is my first question, so i am sorry if i made a mistake in posting the question or something.
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main()
{
Scanner kbReader= new Scanner (System.in);
int score[] = new int [10];//idk what im doing with these two arrays
int numofOcc []= new int [10];
int counter=0;
int sum=0;
for (int i=0;i<10;i++)// Instead of i<10... how would i make it so that it continues until a negative value is entered.
{
System.out.println("Enter score out of 10");
int input=kbReader.nextInt();
if (input>10)
{
System.out.println("Score must be out of 10");
}
else if (input<0)
{
System.out.println("Score must be out of 10");
break;
}
else
{
counter++;
sum+=input;
}
}
System.out.println("The mean score is " +(sum/counter));
}
}
You could use a do...while loop like this:
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main(String args[]) {
Scanner kbReader= new Scanner (System.in);
int scores[] = new int [10];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 10 or negative to break.");
input=kbReader.nextInt();
if (input<0) {
break;
} else if (input>10) {
System.out.println("Score must be out of 10");
} else {
scores[input]++;
counter++;
sum+=input;
}
} while (input>0);
System.out.println("Score\t# of occur...");
for(int i =0; i<10; i++) {
System.out.println(i + "\t" + scores[i]);
};
System.out.println("The mean score is " +(sum/counter));
}
}
The formatting can certainly be done better (without c-style tabs) but I don't remember the syntax at the moment.
I think what you need is a List Array! Create ArrayList from array
Think of it as a dynamic array, you don't need to specify the size of the array and it is expanded/made smaller automatically.
What you're missing is a while loop. Here is a nice way to loop through a Scanner for input. It also catches numbers greater than 10 and provides an error message:
public static void main() {
Scanner s = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
int response = 0;
while (response >= 0) {
System.out.print("Enter score out of 10: ");
response = s.nextInt();
if (response > 10) {
System.out.println("Score must be out of 10.");
} else if (response >= 0) {
list.add(response);
}
}
// Do something with list
}

Reading user input

I'm trying to ask the user to enter any number of numbers up to 5, each number seperated by space.
for example
enter up to 5 numbers : 3 4 5
I'm going to add them in the integer sum and then later divide them by counter
to get the average of these numbers.
However, my loop does not seem to end. What's wrong with my code?
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt());{
counter++;
sum += scan.nextInt();
}
System.out.println(counter);
System.out.println(sum);
You put a ; between while and {, so it loops. Remove it.
Scanner.hasNextInt() does not do what you seem to think it does. It does not tell you whether there is an integer available in already typed input (it does not have any conception of what has "been typed"), but rather whether the input waiting can be read as an integer. If there is no input already waiting, it will block until there is, so your loop is simply sitting there forever, blocking for more input.
What you probably want to do instead is to read a whole line, and then split it explicitly into space-separated parts, and only then parse those as integers. For example, like this:
String input = scan.nextLine();
for(String part : input.split(" "))
sum += Integer.parseInt(part);
Serge Seredenko's answer is also correct, however, but that's another problem.
Everything in your code is fine except the semicolon(;) just after the while loop, of course it will lead to an infinite loop.
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt()){
counter++;
sum += scan.nextInt();
if(counter >=5)
break;
}
System.out.println(counter);
System.out.println(sum);
scan.close();
First, you need to remove ';' located after while(scan.hasNextInt()) and before {; For the ; means the while statement is complete.
Second, when you use your code, you need CTRL + Z to end up your input. By adding
if(counter >=5)
break;
your input will end up when you input 5 numbers.
If you want to read entire line and then do arithmetic operation later then you dont need to have while loop with hasNextInt() method.
I would suggest you to read line then split by space and iterate over string array. Check out code snippet.
package com.gaurangjadia.code.java;
import java.util.Scanner;
public class SO19204901 {
public static void main(String[] args) {
int counter = 0,
sum = 0;
System.out.println("enter up to 5 numbers");
Scanner scan = new Scanner(System.in);
String strInput = scan.nextLine();
String[] arrayNumbers = strInput.split(" ");
for (int i = 0; i < arrayNumbers.length; i++) {
int n;
try {
n = Integer.parseInt(arrayNumbers[i]);
}
catch (NumberFormatException e) {
n = 0;
}
sum = sum + n;
counter++;
}
System.out.println(sum);
}
}
DataInputStream in = new DataInputStream(System.in);
String[]label = {"quiz #","Total","Average"};
int counter = 0;
int theSum = 0;
System.out.print("Enter up to 5 number : ");
String[]tempNum = in.readLine().trim().split("\\s+");
System.out.println();
while (counter <= tempNum.length)
{
if ( counter == tempNum.length)
{
System.out.printf("%10s %12s\n",label[1],label[2]);
counter = 0;
break;
} else {
System.out.printf("%10s",label[0] + (counter+1) );
}
counter++;
}
while(counter <= tempNum.length)
{
if ( counter == tempNum.length)
{System.out.printf("%10d %10.2f\n",theSum,(double)(theSum/counter));
} else
{System.out.printf("%10d",Integer.valueOf(tempNum[counter]));
theSum += Integer.valueOf(tempNum[counter]);
}
counter++;
}

Categories

Resources