Create a NumberInTheRange application that prompts the user for two numbers.
The first number is a min value and the second is a max value. Prompter then prompts the user for a number between the min and max numbers entered. The user should be continually prompted until a number within the range is entered. Be sure to include the min and max numbers in the prompt.
I wrote a code allowing the users to write the two min and max values. However, I am wondering what code should I write in order to fulfill the conditions above. I am thinking about using loops and it would be very helpful if you guys correct me and give some instructions on how to process these.
import java.util.Scanner;
public class NumberinTheRange {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type two numbers:");
int n1=scan.nextInt();
int n2=scan.nextInt();
}
}
Use a do...while loop.
int num;
do {
System.out.println("Enter a number between " + n1 + " and " + n2 + ":");
num = scan.nextInt();
} while(num < n1 || num > n2);
Now, you need to put a condition to loop-back if the input is not in the range. You can use a do-while loop for the same. You can do it with any other loop but using a do-while loop guarantees that its body will be executed at least once.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Type two numbers: ");
int min = scan.nextInt();
int max = scan.nextInt();
int n;
do {
System.out.print("Enter a number in the range of " + min + "-" + max + ": ");
n = scan.nextInt();
} while (n < min || n > max);
System.out.println("Your number is: " + n);
}
}
A sample run:
Type two numbers: 10 20
Enter a number in the range of 10-20: 34
Enter a number in the range of 10-20: 5
Enter a number in the range of 10-20: 15
Your number is: 15
Related
NB: Java beginner!
I am trying to make a program that asks the user to input two integers (Using JOption Pane dialog boxes). The program should then find the sum of all the numbers between the two input integers. For example if the user inputs 1 and 8, the program would show in System.out: 1+2+3+4+5+6+7+8=36. The first input dialog asks the user to enter a number, and the second to enter a higher number than the first. I want the program to check if number 2 actually is higher than number 1, and if not, tell the user that number 2 should be higher and prompt for a new entry.
I am currently unable to check if number 2 is higher than number 1
I have tried using different if statement and a while loop. I manage to get the program to show a message dialog if the second number is higher than the first, and ask the user for a new input. However I am unable to get the new input from the user, check if it is correct, and if it is continue with the calculations.
package numbersum;
public class NumberSum {
public static void main(String[] args) {
String input1 = JOptionPane.showInputDialog( "Write a number :" );
String input2 = JOptionPane.showInputDialog( "Write a larger number :" );
int number1 = Integer.parseInt(input1);
int number2 = Integer.parseInt(input2);
if ( number2 <= number1 ) {
JOptionPane.showMessageDialog(null,"The second number must be higher
than the first");
}
int sum=0;
for ( int i = number1; i <= number2; i++ ) {
sum = sum + i;
System.out.print( i + "+" );
}
System.out.print( "=" + sum );
}
You need to use a while loop and provide the JOptionPane untill the user enters valid numbers. Also be sure to test what happens with your application if the user inserts a non numeric value, it probably will crash at the moment :)
public static void main(String[] args) {
// initially set the number 2 smaller than number 1
int number2 = 0;
int number1 = 1;
while (number2 < number1) {
String input1 = JOptionPane.showInputDialog("Write a number :");
String input2 = JOptionPane.showInputDialog("Write a larger number :");
number1 = Integer.parseInt(input1);
number2 = Integer.parseInt(input2);
if (number2 < number1)
JOptionPane.showMessageDialog(null, "The second number must be higher!");
}
int sum = 0;
for (int i = number1; i <= number2; i++) {
sum = sum + i;
System.out.print(i + "+");
}
System.out.print("=" + sum);
}
This program should take a user defined number, create an array of that size and let the user input the elements - which are grades - using a do..while loop. The program then needs to display all grades entered from lowest to highest, accumulate the grades, and find the average.
My output isn't displaying the entered grades correctly (if I enter 10,20,30, it displays 00,10,20) and I can't figure out what I'm doing wrong. Any help, please?
import java.util.Arrays;
import java.util.Scanner;
public class LoopArray
{
public static void main(String[] arg)
{
Scanner keyboard = new Scanner(System.in);
int count = 0;
double totalAverage = 0;
double gradesTotal = 0;
System.out.println("Please input the number of grades you would like to submit for an average: ");
int numberOfGrades = keyboard.nextInt();
int[] studentScores = new int[numberOfGrades];
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
Arrays.sort(studentScores);
for(count=0; count < studentScores.length; count++)
{
System.out.println("Grades entered were: " + count + studentScores[count]);
}
totalAverage = gradesTotal / numberOfGrades;
System.out.println("The total of all grades entered is: " + gradesTotal);
System.out.println("The average of grades entered is: " + totalAverage);
}
}
Result
Grades entered were: 00
Grades entered were: 10
Grades entered were: 20
is generated with
System.out.println("Grades entered were: " + count + studentScores[count]);
So last number in each line is pair representing count + studentScores[count]. This means that:
00 -> at position 0 array studentScores stores 0.
10 -> at position 1 array studentScores stores 0
20 -> at position 2 array studentScores stores 0
Which means you didn't fill your studentScores array with values from user.
You are not putting any value inside the array. You need to add this to your do part of the loop studentScores[count] = inputGrade;
Now your do while loop should look like this:
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
studentScores[count] = inputGrade;
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
Also, inside your last for-loop, you are printing extra info. Just remove that count from System.out.println
System.out.println("Grades entered were: " + studentScores[count]);
Anything you don't understand let me know thanks
Because count start from 0. You should check it.
you forgot to populate the array using the gardes entered
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
studentScores[count]=inputGrade;
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
I want my program that to accept user number input and output the sum from 1 up to the input number (using while loop).
Example: If input value is 4, the sum is 10 i.e., 1 + 2 + 3 + 4.
My code compiles but returns a never ending 1 until my jcreator stops responding.
import java.util.Scanner;
import java.io.*;
public class SumLoopWhile {
public static void main(String[] args) {
int number;
int sum = 1;
Scanner in = new Scanner (System.in);
System.out.println("Enter number: ");
number = in.nextInt();
while (sum <= 10) {
System.out.println("Sum is: " + sum);
number++;
}
}
}
You should be comparing the value to the number that was input, and adding to the sum. Finally, display the result after the loop. Something like
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number: ");
int number = in.nextInt();
int sum = 0;
int v = 0;
while (v <= number) {
sum += v;
v++;
}
System.out.println("Sum is: " + sum);
}
Which will print Sum is: 10 when the input is 4 (as requested).
I guess that what you want it's to modify the sum inside your while loop. Do it like this:
while (sum <= 10) {
sum = sum + number;
number++;
}
}
System.out.println("Sum is: " + sum);
You have to put your System.out.println out of the loop because you want to print the total value, not each sum that it's calculated in each iteration.
Also, it should be nice that when you want to initialize some int that will be a "total" variable (like the result of a sum, rest or whatever), initialize it to zero.
int sum = 0;
Your output variable sum is having the same value throughout the program.it is not getting altered.the while loop becomes infinite loop
The Condition
(sum <= 10) never becomes true and the while loop will run for infinite times
import javax.swing.JOptionPane;
public class SumUsingWhileLoop {
public static void main(String[] args) {
String input;
input = JOptionPane.showInputDialog("Input the number:");
int number;
number = Integer.parseInt(input);
int sum = 0;
int i = 1;
while (i <= number) {
sum += i;
i++;
}
JOptionPane.showMessageDialog(null, "Sum = " + sum);
System.exit(0);
}
}
The System.out.println should not be placed inside the while loop, because it will get executed as many times as the loop.If you want to print the sum value only once, then the statement System.out.println must be placed outside the loop block.
Just use another variable for counting the iterations.For example
while(count<=number)
{
sum=sum+count;
count++
}
System.out.println("Sum is: "+ sum);
I have a little averaging program I have made and, I am trying to only allow it to take in numbers. Everything else works but, I can't seem to figure it out. I am still learning so, any advise or pointers would be awesome!
Here is my code.
import java.util.Scanner;
public class THISISATEST {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int sum = 0;
int count = 0;
int i = 1;
while (i <= 10) {
i++;
{
System.out.print("Enter the test score: ");
int tS = keyboard.nextInt();
count++;
sum = (sum + tS);
}
System.out.println(sum);
}
System.out.println("The Average is = " + sum / count);
}
}
Inside your while loop use the following code:
System.out.print("Enter the test score: ");
while (!keyboard.hasNextInt()) {//Will run till an integer input is found
System.out.println("Only number input is allowed!");
System.out.print("Enter the test score: ");
keyboard.next();
}
int tS = keyboard.nextInt();
//If input is a valid int value then the above while loop would not be executed
//but it will be assigned to your variable 'int ts'
count++;
sum = (sum + tS);
I'm in a university and I don't understand how to fix this problem. I'm trying to make a program where a user types in all the numbers s/he wants, and enter -1 when s/he is done. "Expected" results are as directed by my professor:
Write a program that will allow the user to enter any number of positive integers.
The user will enter a -1 when they are done entering numbers
(do not include the -1 as a number).
The program must print out, when the user is done entering numbers, the following:
Which number had the longest run of identical values, and how long the run was
The minimum number entered
The maximum number entered
For example, if the user enters these numbers:
5
9
5
7
5
7
-1
Then the program would print out:
Longest run: 5 entered 3 times
Minimum number: 2
Maximum number: 9
If there are multiple runs of equal length, print out the first such run encountered.
import java.util.Scanner;
public class ExSixNumber {
public static void main(String args []) {
int mostUsedNumber = 0;
int mostUsedCount = 0;
System.out.println("I will track all your numbers!");
System.out.println("Enter any digits between 1 and 9.");
System.out.println("Enter '-1' when done:");
Scanner scn = new Scanner (System.in);
while(scn.hasNext()) {
String userInput = scn.next();
while (scn.equals (userInput)) {
mostUsedNumber++;
mostUsedCount++;
}
if(userInput.equals("-1")) {
System.out.println("Your tracked data:");
System.out.println("Longest run: " + mostUsedNumber + " entered " + mostUsedCount + " .");
break;
}
}
}
}
This is as far as I had gotten. It doesn't like to track my userInput, could someone point me in the right direction on improving the program? I'm new and not asking for a direct answer, but "dummy" terms would be greatly appreciated. :)
hope this will help :)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class one {
public static void main(String args[]) {
int mostUsedNumber = 0;
int mostUsedCount = 0;
int maxNo=-1;
int minNo=-1;
List numberList = new ArrayList<Integer>();
List mostOccuranceList = new ArrayList<Integer>();
System.out.println("I will track all your numbers!");
System.out.println("Enter any digits between 1 and 9.");
System.out.println("Enter '-1' when done:");
Scanner scn = new Scanner(System.in);
while (scn.hasNext()) {
String userInput = scn.next().trim();
int user_input = Integer.parseInt(userInput);
if(maxNo==-1 && minNo ==-1){
maxNo=minNo=user_input;
}
if (user_input > 0 && user_input < 10) {
// returns the number of occurrences
int occurrences = Collections.frequency(numberList,user_input);
if (occurrences == mostUsedCount) {
mostOccuranceList.add(user_input);
} else if (occurrences > mostUsedCount) {
mostUsedCount = occurrences;
// emptying the most occurrence list since current input is the most frequent number
mostOccuranceList.removeAll(mostOccuranceList);
mostOccuranceList.add(user_input);
}
if(user_input>maxNo)
{
maxNo=user_input;
}
if(user_input<minNo){
minNo=user_input;
}
numberList.add(user_input);
}
mostUsedNumber+=1;
mostUsedNumber=Integer.parseInt(mostOccuranceList.get(0).toString());
if (userInput.equals("-1")) {
System.out.println("Your tracked data:");
System.out.println("Longest run: " + mostOccuranceList + " entered " + mostUsedCount + " .");
System.out.println("Maximum Number :- "+maxNo);
System.out.println("Minimum Number :- "+minNo);
break;
}
}
}
}