I'm supposed to recreate this code
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = keyboard.nextInt();
double x = 0;
System.out.print("The total is: ");
for (int i = 1; i <= n; i++){
x = x+-(1.0/i);
}
System.out.print(+x);
}
But with alternating signs in the loop (1 – 1/2 + 1/3 – 1/4 + 1/5 – 1/6 + ... + 1/N) and have it print out the value (Enter an integer: 5
The total is: 0.7833333333333332)
I was wondering how I could do this? I was able to write the original code, but I am unaware as to how I could replicate the code but with alternating signs.
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = keyboard.nextInt();
double x = 0;
System.out.print("The total is: ");
for (int i = 1; i <= n; i++){
if(i%2==0){ //even
x = x-(1.0/i);
}
else{ //odd
x = x+(1.0/i);
}
}
System.out.print(+x);
}
This may be what you are trying to do. The important change is the if(i%2==0) logic - Here I use it as a way of alternating on the different iterations of the for loop based on whether i is even or odd.
Hope this helps, feel free to ask any questions
double s = -1; // Sign factor
for (int i = 1; i <= n; i++) {
s = -s;
x += s/i;
}
Change x = x+-(1.0/i); to x -= Math.pow(-1,i)/i;. That should do the trick.
Related
I made a calculator that does multiple things (adding consecutive numbers, adding multiple numbers, etc) but I am having trouble making it so that the calculator can multiply multiple numbers. So far, I've basically copied the code that adds multiple numbers, but I can't figure out how to make it multiply instead of add.
Here is my code:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String arg[])
{
int n;
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to add up to: ");
n = s.nextInt();
System.out.println("you entered: " + n + "");
sum = addConsecutiveNumbers(n);
System.out.println("sum of 1 to "+n+" = "+sum);
//following code is sum of any numbers you entered from console
//store the numbers into an array
int num;
int sumOfNums=0;
System.out.print("Please enter how many numbers you want to sum: ");
num=s.nextInt();
System.out.println("you want to sum "+num+" numbers ");
sumOfNums = addNumbers(num);
System.out.println("sum of "+num+" numbers = "+sumOfNums);
}
//Define a method which add consecutive numbers based on user's input and return the sum of the numbers
private static int addConsecutiveNumbers (int number)
{
int sum = 0;
for (int i = 1; i <= number; i++)
{
sum = sum + i;
}
return sum;
}
//Define a method which add numbers based on user's input and return the sum of the numbers
private static int addNumbers (int num)
{
Scanner s = new Scanner(System.in);
int a[] = new int[num];
int sumOfNums = 0;
for(int k = 0; k < num; k++)
{
System.out.println("enter number "+(k+1)+":");
a[k] = s.nextInt();
System.out.println("The array of a[" + k + "] = " + a[k]);
}
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
return sumOfNums;
}
//below is the part of code that I am having trouble with.
public static int multiplyNumbers(int num)
{
int Area = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[num];
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
for(int l = 0; l < num; l++)
{
System.out.println("enter number "+(l+1)+":");
a[l] = s.nextInt();
System.out.println("The array of a[" + l + "] = " + a[l]);
}
return Area;
}
}
I see one thing right away; The way I see your code, the following two lines a redundant:
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
You should have already asked the user how many numbers they want to multiply, because it's passed in as a parameter. As for your actual problem, take a look at these lines from the addNumbers() method:
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
All you gotta do is copy that code in right before your return statement (return Area;). You'll need to tweak it a bit so instead of using the sumOfNums variable, it uses the Area variable, and instead of adding, it multiplies. This can be done like so:
for(int j = 0;j < num ; j++) //j also needs to start at 0, I think you may have made a mistake when writing the summing method
{
Area *= a[j];
}
You'll notice there's an issue with this algorithm though (almost didn't catch it myself). Area starts off with a value of 0, so 0 multiplied by any number will always still be 0. Simple fix; just manually set Area to the first value before the loop. Something like this:
Area = a[0];
for(int j = 1; j < num; j++)
{
sumOfNums += a[j];
}
Also notice I started the for loop at j = 1 this time. This is because I already started Area as a[0], so we don't want to multiply that number twice.
You don't need to store values in an array for multiplication similarly for addition you can directly update the final result
public static int multiplyNumbers(int num) {
int Area = 1;
Scanner s = new Scanner(System.in);
System.out.println("Please enter how many numbers you want to multiply:");
num = s.nextInt();
for (int l = 0; l < num; l++) {
System.out.println("enter number " + (l + 1) + ":");
int temp = s.nextInt();
Area *= temp;
System.out.println("The array of a[" + l + "] = " + temp);
}
return Area;
}
I need to create a program that prints 6 numbers between 1 and 42 at random where no 2 numbers are the same. The user must also insert 6 numbers. If any number is the same as the one randomly selected by the computer, the computer must print it. If not, the computer prints you are such a loser. Now, the problem is I'm not sure about how to make sure that no 2 randomly selected numbers are the same. The program should also ask for a different number if a number less than 1, greater than 42, or equal to a previous number inserted, and scan it which I am also not able to do. (user cannot enter 2 identical numbers)
import java.util.Scanner;
import java.util.Random;
public class LotoMachine {
public static void main(String[] args) {
System.out.println("Please enter 6 numbers between 1 and 42.");
Scanner scan = new Scanner(System.in);
int[] marks = new int[6];
Random ran = new Random();
int[] x = new int[6];
boolean winner = false;
for (int i = 0; i < 6; i++) {
marks[i] = scan.nextInt();
while (marks[i] > 42) {
System.out.println(marks[i] + " is out of range. Please pick a number that is less than 43.");
marks[i] = scan.nextInt();
i=0;
}
while (marks[i] < 1) {
System.out.println(marks[i] + " is out of range. Please pick a number that is greater than 0.");
marks[i] = scan.nextInt();
i=0;
}
while (marks[i] == marks[i] - 1) {
System.out.println("You have already chosen " + marks[i] + "Please pick a different number.");
marks[i] = scan.nextInt();
i=0;
}
}
for (int j = 0; j < 6; j++) {
x[j] = ran.nextInt(42) + 1;
for (int y = 0; y < j; y++) {
if (x[j] == x[y]) {
x[j] = ran.nextInt(42) + 1;
j = 0;
}
}
}
System.out.print("You chose");
for (int m = 0; m < 6; m++) {
System.out.print(" " + marks[m]);
}
System.out.println(" ");
System.out.print("The random numbers are");
for (int m = 0; m < 6; m++) {
System.out.print(" " + x[m]);
}
System.out.println(" ");
System.out.print("The number(s) that matched are");
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (marks[i] == x[j]) {
winner = true;
System.out.print(" " + marks[i]);
}
}
}
if (winner != true) {
System.out.println("You are such a loser");
}
}
}
You can use a Set to store the values and ask for the size after the addition. Whenever you want to deal with collections of objects which should not be repeated, a Set is a good way to go, since it allows no duplication.
Something like this:
Set<Integer> numbers = new HashSet<Integer>();
random code goes here...
int size = numbers.size();
numbers.add(newValue);
if(numbers.size() == size){
number needs to be created again...
}
Basically, there are two ways to draw 6 from 42.
The first is to draw continuously until you have 6 unique numbers. Each draw has the same probabilty (1/42) to draw a particular number. Although the likelyhood of the case that you always draw the same number is low, it is not 0. So from a statistical point of view, this is not correct. In Java you could do this is
Random rand = new Random();
List<Integer> randomNumbers = Stream.generate(() -> rand.nextInt(42))
.distinct()
.limit(6)
.collect(toList());
What you actually want to have, is to draw 1 of 42, 1 of 41, 1 of 40 ... One approach to do this is to generate a list of all possible number (1..42), draw one, remove it from the list, draw another etc. In Java that would be
final List<Integer> numbers = IntStream.rangeClosed(1, 42)
.boxed()
.collect(toList());
final List<Integer> randomNumbers2 = Stream.generate(() -> rand.nextInt(numbers.size()))
.limit(6)
.map(i -> numbers.remove((int)i))
.collect(toList());
Finally reading input until you have a valid number is easily done with a do-while loop
Scanner scanner = new Scanner(System.in);
int number;
do{
number = scanner.nextInt();
} while(number < 0 && number > 42);
if(randomNumbers2.contains(number)){
System.out.println("Winner");
} else {
System.out.println("Looser");
}
I have in array with some doubles in them. I want to divide them, for example with an array that contains 6.0, 3.0 and 2,0 the result should be 1 (6/3/2). I wrote the following code:
System.out.print("How many numbers do you want to divide? ");
int division = input.nextInt();
double[] divisionArray = new double[division];
for(int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
}
for(int k = 0; k < division; k ++) {
double resultDivision = divisionArray[k] / divisionArray[k + 1];
}
System.out.println("Result: " + resultDivision);
but that doesn't seem to work. I get the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 I'm a complete java beginner. Could anyone help me out? Thanks
Your code has three issues.
resultDivision is defined within the scope of the for loop, so it's not visible afterwards, when you print the result.
With #1 fixed, you'll get an ArrayOutOfBounds exception because the second for loop tries to access divisionArray[k+1].
You don't check the arguments that the user gives you. What if a user specifies that it wants to divide -5 numbers? Your code will try to create an array with a length of -5, causing an Exception. Also, What if a user wants to divide by zero? Are you fine with that?
Here's a slightly better version:
Scanner input = new Scanner(System.in);
int division = 0;
do {
System.out.print("How many numbers do you want to divide? ");
division = input.nextInt();
} while (division <= 0);
double[] divisionArray = new double[division];
for (int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
if (divisionArray[i] == 0 && i>0) { // Remove this if you want to allow the user to divide by zero. Entering zero as the first argument is legal
System.out.println("Zero is an illegal argument, please enter a different number");
i--;
}
}
double resultDivision = divisionArray[0];
for (int k = 1; k < division; k++) {
resultDivision = resultDivision / divisionArray[k];
}
System.out.println("Result: " + resultDivision);
Good luck.
this should work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to divide? ");
int division = input.nextInt();
double[] divisionArray = new double[division];
for(int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
}
//remember the first value and divide it trough the second,
//third, fourth and so on...
double result = divisionArray[0];
for(int k = 1; k < division; k ++) {
result = result / divisionArray[k];
}
System.out.println("Result: " + result);
}
What is not working is the sum part. Its not equaling the right number. Ex: user puts in 25 so the sum should be 75, but the program prints out 50.
My code:
import java.util.Scanner;
public class SumH4
{
public static void main(String[] args)
{
//define data
int x;
int sum;
//scanner is needed
Scanner sc = new Scanner(System.in);
//get user data and initialize variables
System.out.println("Please input a positive whole number.");
x = sc.nextInt();
sc.nextLine();
sc.close();
System.out.println();
sum = 0;
//do computation
for(int a = 0; a < x; a = a + 1)
{
if(a%5==0)
{
sum = sum + a;
}
}
//print results
System.out.println("Sum = " + sum);
}
}
You're not including the number itself that is input by the user. Simply change the for loop to the below so that the input x gets added:
for (int a = 0; a <= x; a = a + 1) {
Change
for(int a = 0; a < x; a = a + 1)
to
for(int a = 0; a <= x; a = a + 1)
At the moment you're not including 25, that only goes upto 24 i.e. a < x means "while a is less than x", then you want "while a is less than OR EQUAL TO x".
Your loop test should be <= (not <), also I suggest you define variables when you need them. Finally, you shouldn't close() a Scanner on System.in because that closes System.in and if you refactor your code you may cause yourself a lot of pain with that. So, I would change your method like
Scanner sc = new Scanner(System.in);
System.out.println("Please input a positive whole number.");
int x = sc.nextInt();
int sum = 0;
for (int a = 0; a <= x; a++) {
if (a % 5 == 0) {
sum += a;
}
}
// print results
System.out.println("Sum = " + sum);
I'm relatively new to the world of OOP, and for some reason, the console of IntelliJ and Eclipse doesn't give me an output in the console for the following program. I'm trying to store 12 numbers into an array using scanner and to find the standard deviation, mean, lowest number, and highest number. Can anyone spot what's wrong?
import java.util.Arrays;
import java.util.Scanner;
public class untitled
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int[] grades = new int[12];
int size = grades.length;
for (int i = 0; i < size; i++)
{
grades[i] = in.nextInt();
}
Arrays.sort(grades);
int low = grades[0];
int high = grades[11];
int sum = 0;
for (int i: grades)
{
sum += i;
}
int m = sum / size;
double var = 0;
double variance;
double sd;
for (int i = 0; i < size; i++)
{
var = var + ((grades[i] - m) * (grades[i] - m));
}
variance = (int) var / size;
sd = Math.pow(variance,.5);
String lowest = ("Lowest Grade:" + low);
String highest = ("Highest Grade:" + high);
String average = ("Average Grade:" + m);
String standdev = ("Standard Dev.:" + sd);
System.out.println(lowest);
System.out.println(highest);
System.out.println(average);
System.out.println(standdev);
}
}
Thanks.
What you have done is to accept 12 inputs.. try entering 12 inputs in console and then your output will appear..
And yeah this doesnt seem to use OOP concepts. Please refer this link for more info regarding OOPS :
http://en.wikipedia.org/wiki/Object-oriented_programming
The problem is, that you need to enter values first, before the calculation and output can continue. Without having some printed text on the console (like "Enter a new number: ") the console will just stay empty.
You could either enter 12 numbers, or fill the list automatically with Random values. In this case the output will immediately be visible on the console.
...
nt[] grades = new int[12];
int size = grades.length;
Random random = new Random();
for (int i = 0; i < size; i++) {
grades[i] = random.nextInt(15); // value between 0 and 14
}
Arrays.sort(grades);
int low = grades[0];
...