I need to generate a specified number of random integers between any
two values specified by the user (example, 12 numbers all between 10 and 20), and then calculate the average of the numbers.
The problem is if I ask for it to generate 10 numbers, it will only generate 9 (shown in output.)
Also, if I enter a max range of 100 and min range of 90, the program will still generate #'s like 147, etc that are over the max range... did I mess up the random number generator? Can someone help?
Here is the code I have so far:
public class ArrayRandom
{
static Console c; // The output console
public static void main (String[] args)
{
c = new Console ();
DecimalFormat y = new DecimalFormat ("###.##");
c.println ("How many integers would you like to generate?");
int n = c.readInt ();
c.println ("What is the maximum value for these numbers?");
int max = c.readInt ();
c.println ("What is the minimum value for these numbers?");
int min = c.readInt ();
int numbers[] = new int [n];
int x;
double sum = 0;
double average = 0;
//n = number of random integers generated
for (x = 1 ; x <= n-1 ; x++)
{
numbers [x] = (int) (max * Math.random () + min);
}
for (x = 1 ; x <= n-1 ; x++)
{
sum += numbers [x];
average = sum / n-1);
}
c.println ("The sum of the numbers is: " + sum);
c.println ("The average of the numbers is: " + y.format(average));
c.println ("Here are all the numbers:");
for (x = 1 ; x <= n-1 ; x++)
{
c.println (numbers [x]); //print all numbers in array
}
} // main method
} // ArrayRandom class
Java arrays are zero based. Here you leave the first array element at its default value of 0. Replace
for (x = 1 ; x <= n-1 ; x++)
with
for (x = 0 ; x < n ; x++)
Edit: To answer question (from now deleted comment) of why this does not produce values between min and max
max * Math.random () + min
Math.random generates double values between 0.0 and 1.0. So for example, a min of 90 and max of 100 would generate numbers between and 90 and 190(!). To limit the values between the min and max you would need
min + Math.random() * (max - min)
^ |_________________________|
| |
90 value between 0 - 10
Java arrays start indexing at 0. Also your loop is exiting one index short. So, when n==6, your condition is then, "x <=5", and the loop exits. Try this:
for ( x = 0; x < n; x++ {
// stuff
}
Related
I'm trying to make a program that generates random two-digit integers until I get a 10 or a 20. To then find the mount of numbers, the sum of the numbers less than 10, the sum of the numbers equal to 15, the sum of the numbers greater than 70. Can someone help me, please?
This is my code:
// Variables
int numRandom = 0, less10, equal15, more70;
// Process
txtS.setText("Random numbers: " + "\n");
for (int mountNum = 0; numRandom == 40 || numRandom == 20; mountNum++) {
numRandom = (int) (99 * Math.random());
txtS.append(numRandom + "\n");
}
You could just store the values directly and create variables for each case.
This is an example for you less than 10 case. (The 'if statement' would be contained inside your for loop).
int sumLessThanTen = 0;
int countLessThanTen = 0;
...
if(numRandom < 10){
sumLessThanTen += numRandom;
countLessThanTen++
}
Essentially I'm trying to create a program that counts up the sum of the digits of the number, but every time a number that is over 1000 pops up, the digits don't add up correctly. I can't use % or division or multiplication in this program which makes it really hard imo. Requirements are that if the user inputs any integer, n, then I will have to be able to compute the sum of that number.
I've already tried doing x>=1000, x>=10000, and so forth a multitude of times but I realized that there must be some sort of way to do it faster without having to do it manually.
import java.util.Scanner;
public class Bonus {
public static void main(String[] args) {
int x;
int y=0;
int u=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
x = s.nextInt();
int sum = 0;
{
while(x >= 100) {
x = x - 100;
y = y + 1;
}
while(x>=10) {
x = x - 10;
u = u + 1;
}
sum = y + u + x;
System.out.println("The sum of the digits in your number is" + " " + sum);
}
}
}
So if I type in 1,000 it displays 10. And if I type in 100,000 it displays 100. Any help is appreciated
Convert the number to a string, then iterate through each character in the string, adding its integer value to your sum.
int sum = 0;
x = s.nextInt();
for(char c : Integer.toString(x).toCharArray()) {
sum += Character.getNumericValue(c);
}
package test;
import java.util.Scanner;
public class SplitNumber
{
public static void main(String[] args)
{
int num, temp, factor = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
num = sc.nextInt();
temp = num;
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
System.out.print("Each digits of given number are: ");
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
}
}
I can't understand this int factor's job. Can someone help me to understand this codes algorithm?
In programming languages, if you hold double value in the int,it rounds the number to lower one thus if you do 15/10 it will return 1 as int and if you do 5/10 it will return 0. With this knowledge you can understand.
For example,let the number be 953,
while (temp != 0) {
temp = temp / 10;
factor = factor * 10;
}
1.Iteration temp = 95 , factor = 10
2.Iteration temp = 9 , factor = 100
3.Iteration temp = 0 , factor = 1000
end of while loop because temp is 0.
while (factor > 1) {
factor = factor / 10;
System.out.print((num / factor) + " ");
num = num % factor;
}
1.Iteration num = 953 factor = 100 , 953/100 = 9 (you get first digit)
2.Iteration num = 953%100 = 53 , factor = 10 , 53/10 = 5 (you get second digit)
3.Iteration num = 53%10 = 3 , factor = 1 , 3/1 = 3 (you get last digit)
End of while loop.
Actually it is basic math. When you want to extract nth digit of number, you just have to divide it by 10^n.
The modulus operator to extract the rightmost digit or digits from a number. For example, x % 10 yields the rightmost digit of x (in base 10). Similarly x % 100 yields the last two digits.
Here more info
If you would not care about flipping the order of digits, you could simply write
int num = sc.nextInt();
do {
System.out.println(num % 10);
num = num / 10;
} while(num != 0);
The modulo operation num % 10 calculates the remainder of dividing num by 10, effectively gets the digit at the lowest position ("ones"). 0 % 10 is 0 ... 9 % 10 is 9, 10 % 10 is 0 again, and so on. Then the division by 10 makes the old "tens" the new "ones", and the entire thing is repeated until 0 remains.
The hassle in your code is about emitting the digits in the "correct" order, highest position first, ones last. So it first checks how many digits are in your number, factor grows to the same size in the process. temp=temp/10; has the same role as num=num/10; in the short snippet (cutting a digit from the number in each iteration), and factor=factor*10 "adds" a digit to factor at the same time. [I just stop here as there is an accepted answer already explaining this]
First I would apologize if my question seems not clear.
I want output to be the largest possible number from user input. Example:
input: x = 0; y = 9; z = 5;
output: 950
I tried something like the below code.
import java.util.Scanner;
class LargestOfThreeNumbers{
public static void main(String args[]){
int x, y, z;
System.out.println("Enter three integers ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
if ( x > y && x > z )
System.out.println("First number is largest.");
else if ( y > x && y > z )
System.out.println("Second number is largest.");
else if ( z > x && z > y )
System.out.println("Third number is largest.");
}
}
The code above will print something like: The seconde number is largest. That is correct the way I define the conditional statements. But how do I get 950 as final result? I know some logic is required here but my brain doesn't seem to produce it.
Your help is appreciated.
You could do something like this to print the numbers in order:
// make an array of type integer
int[] arrayOfInt = new int[]{x,y,z};
// use the default sort to sort the array
Arrays.sort(arrayOfInt);
// loop backwards since it sorts in ascending order
for (int i = 2; i > -1; i--) {
System.out.print(arrayOfInt[i]);
}
A solution using java 8 IntStream:
int x = 0, y = 9, z = 5;
IntStream.of(x,y,z).boxed().sorted( (i1,i2) -> Integer.compare(i2, i1)).forEach( i -> System.out.print(i));
You can find the maximum with successive calls to Math.max(int, int) and the minimum with calls to Math.min(int, int). The first number is the max. The last is min. And the remaining term can be determined with addition of the three terms and then subtraction of the min and max (x + y + z - max - min). Like,
int max = Math.max(Math.max(x, y), z), min = Math.min(Math.min(x, y), z);
System.out.printf("%d%d%d%n", max, x + y + z - max - min, min);
Something like this would work
ArrayList<Integer> myList = new ArrayList<Integer>();
Scanner val = new Scanner(System.in);
int x = 0;
for (int i = 0; i < 3; i++) {
System.out.println("Enter a value");
x = val.nextInt();
myList.add(x);
}
myList.sort(null);
String answer = "";
for (int i = myList.size() - 1; i >= 0; i--) {
answer += myList.get(i).toString();
}
System.out.println(answer);
}
I am trying to write a simple and quite useless program to generate a list of all integers 1><1000 where the sum of digits is 11. Every time I run this, I end up in an infinite loop. I've tried different things - for(){}, while(){}, adding a if(count>500){break;} to halt it after the loop counter reaches 500....still nothing...where am I going wrong in this?
Thanks in advance
//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}
You are using same variable as controller for your fors. Try to change the controller variable within the for structure from number to number1
You are changing the variable here:
---------------------------------
int hPlace = number / 100; number = number - (hPlace * 100);
---------------------------------
Don't do this
number = number - (hPlace * 100);
when your condition is dependent on number
for(int number = 29; number < 1000; number++)
because you have two nested for loops which both of them use the same variable as counter
for(int number = 29; number < 1000; number++) {
for(number = 29;number < 930;number++) {
//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100;
**number** = number - (hPlace * 100); // PROBLEM!!!
int tPlace = number / 10;
**number** = number - (tPlace * 10); // PROBLEM!!!
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}
if(count>500){break;} to halt it after the loop counter reaches 500....still nothing
This won't work because you're redeclaring count with an initial value of 0 everytime. So the if will always return false.
Also, these following lines:
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
Modify number, which is your loop variable. Your loop will not perform correctly if you modify the loop variable in unexpected ways. Instead, copy the value over to another variable.
Don't change the value of you loop control variable inside the loop, or dangerous things may result. Instead, copy the value into a new variable and use that in the loop.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SumDigits
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a Number:");
String string=br.readLine();
System.out.println("length of Number:"+string.length());
int sum=0;
int number=0;
for(int i=0;i<=string.length()-1;++i)
{
char character=string.charAt(i);
number=Character.getNumericValue(character);
sum=sum+number;
}//for
System.out.println("Sum of digits of Entered Number:"+sum);
}//main()
}//class