On this program, it asks you a number, then displays 10 multiples of that number and then sums them but it has to be like this:
Number = 6;
06, 12, 18, 24, 30, 36, 42, 48, 54, 60
60, 54, 48, 42, 36, 30, 24, 18, 12, 06
Sum = 324
The part of displaying the numbers is no problem, the problem is when i have to sum them. I tried to use lists to save the numbers of each row and then use the first row/list and sum it but i can't get it to work.
ArrayList<Integer> i1 = new ArrayList();
ArrayList<Integer> i2 = new ArrayList();
System.out.println("Introduce un nĂºmero:\n"); // Asks you a number
int n1=scan.nextInt();
int add_i = 0;
int rest_i = n1 * 11;
i1.add(add_i);
i2.add(rest_i);
while (add_i <= n1 * 9) // while add_i is less or equal to n1 * 9
{
add_i += n1; // suma n1 a i
System.out.print(i1 + " "); // Prints the result
}
System.out.println(" ");
while (rest_i >= 10) // while rest_i is greater or equal than 10
{
rest_i -= n1; // Resta n1 a i
System.out.print(i2 + " "); // Prints result
}
Also in my program the mults do not show up.
Not sure what logic you are trying to undertake, but it seems a lot more difficult than
Scanner scan = new Scanner(System.in);
System.out.println("Enter number : ");
int input = scan.nextInt ();
int sum = 0;
for (int loop = 1; loop <= 10; loop++) {
int out = loop * input;
sum += out;
System.out.println(out);
}
// and down
for (int loop = 10; loop >= 1; loop--) {
int out = loop * input;
System.out.println(out);
}
System.out.println("sum is "+ sum);
try this:
int sum = IntStream.iterate(startNumber, n -> n+startNumber)
.limit(10)
.peek(System.out::println)
.sum();
Disclaimer because of downvotes. This is an alternate solution. You can look at it when you understand loops well enough I guess.
Related
This is the exercise I am stuck with :
Ask user for minimum, maximum (inclusive) and how many (count) random
numbers user wants to generate. Makes sure minimum is not larger than
maximum and count is not negative. Display error message if inputs are
invalid. If all is fine then generate the random numbers and print
them out, comma-separated on a single line.
I wrote the code in many ways. I can never get the for loop to print the Random numbers.
package randnumsmany;
import java.util.Scanner;
public class RandNumsMany {
public static double getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) + min);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter minimum :");
int min = input.nextInt();
System.out.println("Enter maximum :");
int max = input.nextInt();
System.out.println("Enter number generated :");
int num = input.nextInt();
int[] rand = new int[num];
for (int i = 0; i == num - 1; i++) {
rand[i] = (int) getRandomNumber(min, max);
}
for (int i = 0; i == num - 1; i++) {
System.out.println(rand[i]);
}
System.out.println("How many generated: " + num);
}
}
You do not need an array for it. You can simply print all the numbers when they are calculated. Since you have to print them separated by a comma, you can print all but the last one followed by a comma and then print the last one without a comma.
Also, you can use an infinite loop to check the validity of inputs. If the inputs are valid, you can break the loop otherwise because of the loop, the inputs will be requested again.
Also, since the maximum needs to be inclusive, your formula to calculate the random number should be (int) (Math.random() * (max - min + 1) + min).
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int min, max, num;
System.out.print("Enter minimum: ");
min = input.nextInt();
while (true) {
System.out.print("Enter maximum: ");
max = input.nextInt();
if (min > max) {
System.out.println("Minimum can not be larger than maximum");
} else {
break;
}
}
while (true) {
System.out.print("Enter number generated: ");
num = input.nextInt();
if (num < 0) {
System.out.println("The count can not be negative");
} else {
break;
}
}
// Print all but the last number followed by a comma
for (int i = 1; i <= num - 1; i++) {
System.out.print(getRandomNumber(min, max) + ", ");
}
// Print the last number without a comma
System.out.print(getRandomNumber(min, max));
}
public static int getRandomNumber(int min, int max) {
return (int) (Math.random() * (max - min + 1) + min);
}
}
A sample run:
Enter minimum: 10
Enter maximum: 20
Enter number generated: 20
19, 17, 13, 17, 16, 19, 12, 15, 20, 15, 17, 17, 19, 12, 13, 10, 16, 12, 14, 17
Another sample run:
Enter minimum: 10
Enter maximum: 5
Minimum can not be larger than maximum
Enter maximum: 20
Enter number generated: -10
The count can not be negative
Enter number generated: 5
18, 16, 11, 11, 13
// randomStream(n, min, max): e.g using stream, generate n number between min and max
// randomRandom(min, max) example of getting one random number between min and max
// randomMath(min, max): other way similar to randomRandom(min, max)
// randomThreadLocalRandom(): just for a random number without constrain
// It is effective way to use stream when many random number are needed.
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class Randomize {
public static void main(String args[]){
randomStream(2, 3, 10);
randomRandom(3, 10);
randomMath(3, 10);
}
// (generate random number between 0.0 and 1.0) * (max - min +(1 or 0)) + min
// length: how much number you want to generate
public static void randomStream( int length, int min, int max){
System.out.println("using random as Stream");
Random rand = new Random();
int[] random = rand.ints(length, min, max).toArray();
System.out.print("As integer: ");
for(int i : random)
System.out.print(i+"; ");
System.out.println("");
double[] randomD = ThreadLocalRandom.current().doubles(length, min, max).toArray();
System.out.print("As double: ");
for(double d : randomD)
System.out.print(d+"; ");
System.out.println("");
}
public static void randomRandom(int min, int max){
System.out.println("using Random");
Random rand = new Random();
int int_random = min + rand.nextInt(max-min);
System.out.println("As integer: "+ int_random);
double double_random = min + rand.nextDouble();
System.out.println("As double: "+double_random);
}
public static void randomMath(int min, int max){
System.out.println("using Math:");
int random_int = (int)(Math.random() * (max - min + 1) + min);
System.out.println("As integer: "+random_int);
double random_double = Math.random() * (max - min + 1) + min;
System.out.println("As double: "+ random_double);
}
public static void randomThreadLocalRandom(){
int int_random = ThreadLocalRandom.current().nextInt();
System.out.println("As Integers: " + int_random);
double double_rand = ThreadLocalRandom.current().nextDouble();
System.out.println("As Doubles: " + double_rand);
}
}
//
I made the arithmetic mean for whole the sorted array, but now i want to make the arithmetic mean for first sorted half and second sorted half of array.
Ex: My array is: 77, 99, 44, 55, 22, 88, 11, 00, 66, 33.
My code make in first place the sort.
The outcome of program is: 00 11 22 33 44 55 66 77 88 99.
Now i want to make the mean for first half:
00 11 22 33 44 and print it.
Then i want to make the mean for the second half:
55 66 77 88 99 and print it.
public class Array {
private double[] a;
private int NrElmts;
public Array(int max)
{ a = new double[max];
NrElmts = 0;
}
public void elements(double value)
{ a[NrElmts] = value;
NrElmts++;
}
public void print()
{ for(int j=0; j<NrElmts; j++)
System.out.print(a[j] + " ");
System.out.println("");
}
public void selectionSort()
{
int out, in, min;
for(out=0; out< NrElmts -1; out++)
{ min = out;
for(in=out+1; in< NrElmts; in++)
if(a[in] < a[min] )
min = in;
invertPositions(out, min); }
}
private void invertPositions(int one, int two)
{ double temp = a[one];
a[one] = a[two];
a[two] = temp;
}
public void mean()
{
int i;
double sum = 0;
for(i = 0; i < NrElmts; i++) {
sum+=a[i];}
double medie = sum/NrElmts;
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
}
Try this
public void firstHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts/2;
for (i = 0; i < NrElmts/2; i++) { // take sum only till half.
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half the elements
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
public void secondHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts % 2 == 0 ? NrElmts/2 : NrElmts/2 + 1; // If odd, this second array will contain one more element.
for (i = NrElmts/2; i < NrElmts; i++) { // take sum for the next half
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half elements (half + 1) in case of odd length.
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
To calculate the mean for 9, 2 and 7 you have to firstly add them all up, which equals 18 and then divide by how many there are - so 18 / 3 which is 6.
Although, you will have to account for the possibility of an odd list - if there's an odd amount of elements, say for example 1, 2, 3 the middle point of 3 - is 1.5 - and if you're iterating through indexes the iterative variable will count the middle point as 1. So it's a bit tricky, not sure what you'd want to do.Consider the following code though - it does exactly what you want, but with odd list sizes, it will just divide by a decimal value
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
int size = numbers.size();
int iterativeHalf = size / 2;
float meanHalf = (float) size / 2;
float lowerMean = 0;
float upperMean = 0;
for (int i = 0; i < size; i++) {
int realRef = i + 1;
Integer value = numbers.get(i);
if (realRef > iterativeHalf) { //Should be calculating upper mean
if (upperMean == 0) { //if lowerMean is just a running total, not divided yet to get the mean
System.out.println("the lower mean for numbers is " + lowerMean + " / " + meanHalf);
lowerMean = (lowerMean) / meanHalf; //add last value + divide to set it to the mean
}
System.out.println("upper mean = " + upperMean + " + " + value + " = " + (upperMean + value));
upperMean = upperMean + value; //keep the upper values up total going
} else {
System.out.println("lower mean = " + lowerMean + " + " + value + " = " + (lowerMean + value));
lowerMean = lowerMean + value; //keep adding the lower halfs values up
}
}
//When it breaks, must divide upperMean by size to get mean
System.out.println("the upper mean for numbers is " + upperMean + " / " + meanHalf);
upperMean = (upperMean) / meanHalf;
System.out.println(" ");
System.out.println("FINAL lower mean = " + lowerMean);
System.out.println("FINAL upper mean = " + upperMean);
Output is:
lower mean = 0.0 + 10 = 10.0
lower mean = 10.0 + 20 = 30.0
the lower mean for numbers is 30.0 / 2.0
upper mean = 0.0 + 30 = 30.0
upper mean = 30.0 + 40 = 70.0
the upper mean for numbers is 70.0 / 2.0
FINAL upper mean = 35.0
FINAL lower mean = 15.0
This, for a [10, 20, 30, 40] will yield the output shown above but essentially (10+20)/2 as the lower mean and (30+40)/2 for the upper mean.
For [10, 20, 30, 40, 50] will yield (10 + 20) / 2.5 the lower mean and (30+40+50)/2.5 for the upper mean
Only take sum of half the array. Give one more element to your second or first half in case if your array size is odd.
public void firstHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts/2;
for (i = 0; i < NrElmts/2; i++) { // take sum only till half.
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half the elements
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
public void secondHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts % 2 == 0 ? NrElmts/2 : NrElmts/2 + 1; // If odd, this second array will contain one more element.
for (i = NrElmts/2; i < NrElmts; i++) { // take sum for the next half
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half elements (half + 1) in case of odd length.
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
Since you already have way to make mean for entire array, all you need to do is find mid position of array and then run from and to that point.
In your example: NrElmts is 10, so divide your NrElmnts by 2, so you can get mean for 1 to 5, and then 6 to 10 both 5 each.
Think about situation where you have odd number of elements in array, how do u want to do it, whether in first array or second. let me know if this need help as well.
Steps:
1) create a new variable say a1 to NrElmts/2, and go with your mean function from 1 to a1
2) go from a1+1 to NrElmnts
Let me know if you need any help.
For my program, I'd want to code an array 1-100. In that array, I want to store the number + their digits. For example, if the number is 6 the stored value would be 6 because of 6 + 6 = 12. If the number is 17 the stored value should be 25 because 17 + 1 + 7 = 25. I want to do it for every number. My code has a method and 2 for loops but currently outputs everything as 0; Here's my code.
public class GeneratedNums {
public static void main(String[] args) {
int [] numbers = new int [101];
for ( int x=0; x < 101; x++){
numbers[x] = sumDigits (x);
}
for ( int x=0; x < numbers.length; x++){
System.out.println(x + ": " + numbers[x]);
}
}
public static int sumDigits ( int num) {
int sum = num;
while ( num != 0){
num += num%10;
num /= 10;
}
return num;
}
}
You should be adding the result of modulo operation to sum. And you should return sum.
while ( num != 0){
sum += num % 10;
num /= 10;
}
return sum;
You don't need these many loops, you can improve it by caching the previous outputs and reusing it (Dynamic programming tabulation). Considering you don't have values greater than 100 following code can work for you
public static int sumDigits(int num) {
int[] cache = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1 };
int sum = num + cache[num % 10] + cache[num / 10];
return sum;
}
basically, I've cached outputs for first 10 inputs.
FYI, you can make scale the program for larger inputs by storing the previous outputs in HashMap
The Word Problem I'm trying to solve:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
I'm sure you've seen questions about this problem on Project Euler before, but I'm not sure why my solution doesn't work, so I'm hoping you can help!
public class Problem2Fibonacci {
public static void main(String[] args) {
/* Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */
int sum = 0; // This is the running sum
int num1 = 1; // This is the first number to add
int num2 = 2; // This is the second number
int even1 = 0;
int even2 = 0;
int evensum = 0;
while (num2 <= 4000000){ // If i check num2 for the 4000000 cap, num will always be lower
sum = num1 + num2; // Add the first 2 numbers to get the 3rd
if(num2 % 2 == 0){ // if num2 is even
even1 = num2; // make even1 equal to num2
}
if(sum % 2 == 0){ // if sum is even
even2 = sum; // make even2 equal to sum
}
if (even1 != 0 && even2 != 0){ // If even1 and even2 both have values
evensum = even1 + even2; // add them together to make the current evensum
even2 = evensum;
}
num1 = num2;
num2 = sum;
System.out.println("The current sum is: " + sum);
System.out.println("The current Even sum is: " + evensum);
}
}
}
So my 2 questions are,
1. Why doesn't my plan to get sum of even numbers work correctly?
and
2. The last time my loop runs, it uses a num2 that is > 4000000. Why?
Thanks!
This should help you :
int first = 0;
int second = 1;
int nextInSeq =first+second;
int sum =0;
while(nextInSeq < 4000000) {
first = second;
second = nextInSeq;
nextInSeq = first + second;
if(nextInSeq % 2 ==0)
sum = sum + nextInSeq;
System.out.println("Current Sum = " + sum);
}
System.out.println("Sum = " + sum);
For your piece of code : even1 and even2 are not required and they are carrying value they hold from previous iterations as you continue.
int Cnt(){
return Count (10);
}
int Count (int init){
int u = init % 10;
int t = (init % 100) - u;
int u2 = u * u;
int t2 = t * t;
int m = u2 + t2;
if(m <= 1)
System.out.println("Happy!");
else {
return Count (m);
}
This code should (in theory) check if number is Happy, and if it's not sets initial value to be same as the result and whole process repeats.
Infinite loop should occur if number is not happy.
However none of this happens, does anyone know how to make this work?
According to the Wiki article that you linked, you have to repeat the process of summing the digits of the digits in each number. For the example of 7:
7^2 = 49
49 = 4^2 + 9^2 = 16 + 81 = 97
97 = 9^2 + 7^2 = 81 + 49 = 130
130 = 1^2 + 3^2 = 10
10 = 1^2 = 1
I see a few problems with your code. First, you haven't divided your tens digit by 10, which means for the number 52, you will get u = 2, and t = 50, rather than 5. This part, I'm sure you can easily fix.
Second, it looks like you will never reach a conclusion if your number is unhappy. For example with the number 4, you will reach 16, 37, 72, 53, 34, 25, 29, 85, 89, 145, 42, 20, 4. But your program, since you have no way of checking that you've entered a loop, will run until you run out of memory.
Try using the approach as outlined in the article you referenced:
private static boolean isHappy(int number)
{
List<Integer> set = new ArrayList<Integer>();
while (number > 1 && !set.contains(number))
{
set.add(number);
number = sumSquaresOfDigits(number);
}
return number == 1;
}
private static int sumSquaresOfDigits(int number)
{
String numberString = Integer.toString(number);
int result = 0;
for (char character : numberString.toCharArray())
{
int digit = Character.digit(character, 10);
result += digit * digit;
}
return result;
}
This can be done more efficiently by computing the squares of all 10 digits (0-9) and storing the results in an integer array.
Since this is homework I am not putting in the answer... but here is the clue..
You are not handling 3 digit numbers well.
t=init%100-u computes to 10%100-0 = 10
and once m=u2+t2 i.e. m=0+100 reaches to 100 and your program doesn't handle 3 digit numbers. Hope this helps.
add following...
int h = init/100;
int h2 = h * h;
int m = u2+t2+h2;
and it should keep you going... :)
import java.io.*;
class happy_no
{
void happy(double n)
{
int c=0;
double s=0;
double d,p,i,_sa;
for(i=1;i<=n;i++)
{
while(n!=0)
{
d=n%10;
p=d*d;
s=s+p;
n=n/10;
}
if(s==1)
{
System.out.println("HAPPY NO.");
break;
}
else
{
n=s;
}
}
}
public static void main()throws IOException
{
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
double a;
System.out.println("ENTER A NO.");
a=Double.parseDouble(in.readLine());
happy_no obj=new happy_no();
obj.happy(a);
}