I am writing a program that asks the user to input a positive integer and to calculate the sum from 1 to that number. Need some tips on what i'm doing wrong.
Here is the code:
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a positive integer");
int getNumber=keyboard.nextInt();
int x;
int total = 0;
for (x=1;x<=getNumber;x++) {
total=x+1;
}
System.out.println(total);
}
Try below code:
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a positive integer");
int getNumber = keyboard.nextInt();
int x;
int total = 0;
for (x=1;x <= getNumber;x++) {
total += x;
}
System.out.println(total);
}
The logic should be changed from
total=x+1; // you evaluate total each iteration to initialize it with x+1
to
total=total+x; // you keep adding to the existing value of total in each iteration
to get the sum from 1 to the input number you want to increment total by each time with the new number x.
so do total = total + x.
also a tip:
you want to declare int x with your for loop. delete int x and do the following:
for (int x=1; x<=getNumber; x++) {
total = total + x;
}
Your issue is:
your total value is wrong, Because of this line:
total=x+1;
It should be:
total = total + x;
Change this:
total=x+1;
to this:
total=total+x;
Related
after adding two int variables to (a) and (b),
I have to gamble (a) times values between 10 to 100 and
calculate which square root of these gambled numbers is the closest to (b).
For example a=3 and b=2
output:
Gambled 16,25,49.
The number 16 was chosen since it's square root (4) is the closest to b=2.
I am stuck in the part of calculation of the square root, and saving the closest value to b each time the loop runs, i'm not allowed to use arrays,
this is the third question of my first task and i'd appreciate any experienced ideas to be shared ^^.
(MyConsole is a replacement for the scan command)
int a = MyConsole.readInt("Enter value a:");
int b = MyConsole.readInt("Enter value b:");
for(int i = 0; i<a; a--){
int gambler = ((int)(Math.random() *91)+10);
double Root = Math.sqrt(gambler);
double Distance= Root-b;
{
System.out.println();
Here is how I found the minimum. You can also use arrays to store all the gambling values if you want for future use. I also used Scanner but you can use your MyConsole I'm just not familiar with it. I hope it helps. דש מישראל
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter value a:");
int a = scanner.nextInt();
System.out.println("Enter value b:");
int b = scanner.nextInt();
double min = 100;
for (int i = 0; i < a; i++) {
int gambler = ((int) (Math.random() * 91) + 10);
double root = Math.sqrt(gambler);
double distance = Math.abs(root - b);
if (min > distance)
min = distance;
}
System.out.println("minimum value is: " + min);
}
I'm writing a code which will be multiplying 'x' until it'll reach the 'y'.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
do {
x = (int)(x*(1.1f));
}
while(x < y);
}
In the answer I have to get the amount of times 'while' was executed. I'm not sure how to do this.
So general approach would be, create variable i of type int, and increment it at the end of while loop block (this one looks simple actually). So overall, I'd do it this way:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int i = 0;
do {
x = (int)(x*(1.1f));
i++;
} while (x < y);
System.out.println("Loop executed " + i + " times.");
}
If you can use for loop, check out this way of solving your problem:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int i = 0;
for (; x < y; i++)
x = (int)(x*(1.1f));
System.out.println("Loop executed " + i + " times.");
}
}
Thanks to the fact that for loop allows execution of some statement every iteration, you can increment your counter variable everytime loop is looping (this can solve some cases where you use continue; statement).
Basically you need to find out how many times x should be multiplied by 1.1 for it to get larger than y. Or in other words, to what power should 1.1 be raised in order for it to get larger than y/x.
Therefore, an alternative to using a counter would be observing that you need to calculate log1.1(y/x) and round it up to the next int, which in Java can be done with:
Math.ceil (Math.log ((double)y/x) / Math.log (1.1));
This was part of my assignment and was asked to calculate factorial of 5 and 7.
I finished it as below:
import java.util.Scanner;
public class Factorial {
public static void main(String [] args)
{
System.out.println("Please enter a number: ");
Scanner input=new Scanner(System.in);
int number=input.nextInt();
int i,fact=1;
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
}
It worked for 5 and 7 (resulting 120 and 5040).
But my professor came over and test it with 20 and 987654321, result returns -2102132736 and 0.
Why is that?
P.S. I thought for the case of 987654321, the result would crush the application or return error since it would be huge.
This code can solve your problem . It is taken from here
class BigFactorial
{
static void factorial(int n)
{
int res[] = new int[300];
// Initialize result
res[0] = 1;
int res_size = 1;
// Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n
for (int x=2; x<=n; x++)
res_size = multiply(x, res, res_size);
System.out.println("Factorial of given number is: ");
for (int i=res_size-1; i>=0; i--)
System.out.print(res[i]);
}
// This function multiplies x with the number represented by res[].
// res_size is size of res[] or number of digits in the number represented
// by res[]. This function uses simple school mathematics for multiplication.
// This function may value of res_size and returns the new value of res_size
static int multiply(int x, int res[], int res_size)
{
int carry = 0; // Initialize carry
// One by one multiply n with individual digits of res[]
for (int i=0; i<res_size; i++)
{
int prod = res[i] * x + carry;
res[i] = prod % 10; // Store last digit of 'prod' in res[]
carry = prod/10; // Put rest in carry
}
// Put carry in res and increase result size
while (carry!=0)
{
res[res_size] = carry%10;
carry = carry/10;
res_size++;
}
return res_size;
}
// Driver program
public static void main(String []args)
{
factorial(100);
}
}
Because 5040! is a very larger number (even long overflows). Use a BigInteger like
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
BigInteger fact = BigInteger.ONE;
for (int i = 2; i <= number; i++) { // <-- x * 1 = x
fact = fact.multiply(BigInteger.valueOf(i));
}
System.out.println("Factorial of " + number + " is: " + fact);
This is because of the fact that the container that you have taken for storing and printing your result does not have the capacity to hold such big integer (I mean factorial of 20). So, you need a bigger container. As others already suggested, you can use BIGINTEGER.
I need to write a program which accepts non-negative double type of
numbers as
income amounts one by one unti
l a negative number
is entered
, and the negative number ends the
program. When the program is completed by entering a negative number
, it prints out the
minimum, average, and maximum for the set of entered incomes (excluding the last negative
number
be
cause it only indicates the end of user input).
package incomeapp;
import java.util.Scanner;
/**
*
* #author Kenneth
*/
public class IncomeApp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an income (any negative number to quit: ");
double sum = 0;
int count = 0;
double i = sc.nextDouble();
while (i > 0){
double nextDouble;
nextDouble = sc.nextDouble();
if (i < 0){
break;
}
}
}
}
There's a few issues with your code here:
You never actually increment either sum or count
You read input into i before the loop, but then you read into nextDouble inside the loop and the loop condition only checks i - which never changes.
You never print out the minimum, average, and maximum
The condition in the while and if statements are redundant (apart from the if condition accepting 0 which the while condition doesn't)
Now, this seems very much like a programming assignment to me so I'm not going to post the complete code for you. Here's what you should do to fix your code though:
Increment sum and count in the loop.
Use either i or nextDouble - not both.
Print the desired output after the loop
Pick one way of terminating the loop. Here's two ideas on how to do it:
double i = sc.nextDouble();
while (i > 0) {
// Do something with i
i = sc.nextDouble();
}
or
while (true) {
double i = sc.nextDouble();
if (i <= 0) {
break;
}
// Do something with i
}
Try this:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter an income (any negative number to quit: ");
double sum = 0;
double max = 0;
double min = Double.MAX_VALUE;
int count = 0;
double nextDouble;
while (sc.hasNext()) {
nextDouble = sc.nextDouble();
max = Math.max(max, nextDouble);
if (nextDouble < 0){
break;
}else {
min = Math.min(nextDouble, min);
sum += nextDouble;
count++;
}
}
System.out.println("Average: " + sum/count);
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
}
I don't have any idea how to display the largest and smallest number after the user enter -1.
Note: I also have to display the sum of all of this number and the average of this sum.
Here's my code so far:
public static void main(String[] args) {
// store
int cnt = 0;
int acumulator = 0;
int larger = 0;
int smaller = 0;
int number;
// inputs
System.out.println("enter the number all the number");
Scanner kb = new Scanner(System.in);
number = kb.nextInt();
// loop
while (number != -1) {
acumulator += number;
number = kb.nextInt();
cnt++;//
}
double average = (acumulator / cnt);
System.out.println(" The total of your number is=" + acumulator);
System.out.println(" The average of your number is=" + average);
}
Seems like schoolwork, but what you could do is making a var and checking in your while if the input number is higher or lower then the saved var.
if(input > max)
max = input;
And
if(input < min)
min = input;
I would make the following changes:
use a for loop instead of a while loop (you need intialization, condition and iteration)
use the JDK's API more - Math.min() and Math.max()
spell "accumulator" correctly
remove all variables you are not using (cnt)
Try this:
public static void main(String[] args) {
int accumulator = 0;
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
int count = 0;
// inputs
System.out.println("enter a number (-1 to end)");
Scanner kb = new Scanner(System.in);
for(int number = kb.nextInt(); number != -1; number = kb.nextInt()) {
count++;
accumulator += number;
largest = number > largest ? number : largest;
smallest = number < smallest ? number : smallest;
}
double average = (accumulator / count);
System.out.println(" The total of your numbers is=" + accumulator);
System.out.println(" The average of your numbers is=" + average);
System.out.println(" The largest of your numbers is=" + largest);
System.out.println(" The smallest of your numbers is=" + smallest);
}
FYI: Math.min/max could be used instead of the ternary statements, but the above is the simplest java that will achieve the result.
Basically you need to check each all numbers with each other.Lets say we have numbers 1,2 and 3
here is the code:
public static void main(String[] args){
int one=1;
int two=2;
int three=3;
if(three>one){
if(three>two){
System.out.println("three is biggest");
}
}
if(two>one){
if(two>three){
}
}
etc etc.
I think you got idea
You need to use an "if" statement.