Java Program Calculation - java

Write a program in Java to calculate the following:
1+2-3+4-5 …-99+100
this program is provably very simple but I am a beginner to java and this is what i have so far I'm not sure if i am in the right path
I get one java: 13 error message error:not a statement sub;
class Loop{
public static void main(String[] args){
int sum=0;
int sum=0;
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub;
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}

This is complaining about this line:
sub;
This is not a valid instruction, which is why the compiler is yelling at you.

In the following:
if(num%2 == 0){
sum=sum+num;
}
sub;
That last line sub; is not a Java statement. You probably want to delete it.
Update:
Looks like you want to add even and subtract odd (except for 1 which you want to add). If I understood the requirement properly:
You can start by declaring two variables as follows:
int sum = 1; //this will add 1
int n = 2;
Loop condition should be as follows:
while(n <= 100) { //because you want to include 100 also
Then on each iteration of the loop:
If n is even add it to sum, else if n is odd subtract it from sum.
After that increment n by 1.
Finally, print the value of sum.

You can using simple way to implement it :
public static void main(String[] args) {
int sum = 1;
for (int i = 2; i < 100; i++) {
if (i % 2 == 0) {
sum = sum + i;
} else {
sum = sum - i;
}
}
System.out.println(sum);
}

class Loop{
public static void main(String[] args){
int sum=0;
int sum=0;
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub; <-- sub is not a statment
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}
You are on the right track, with a little trial and error you will get it :-) The cause of your problem is commented in the code above, in the middle of your program you have a random sub; on its own line. sub doesn't have a meaning in that context so the compiler doesn't know how to treat it.

1) You can't have 2 variables with the same name sum
2) You need to declare and initialize a variable before you use it
3) What does the statement sub; signify?
Make all the chages mentioned above and try!

Well, you declare "sum" twice, and "sub;" isn't a valid expression.
class Loop{
public static void main(String[] args){
int sum=0;
int sum=0; // second declaration? should probably be num, right?
int sub=0;
while(num<100){
num++;
if(num%2 == 0){
sum=sum+num;
}
sub; // what's this doing here?
if(num%3== 0||num%5==0||num%7==0){
sub=sub-num;
}
}
System.out.println("Sum is: " +sum+sub);
}
}

public class Loop {
public static void main(String[] args) {
int sum = 1;
int sub = 0;
for (int i = 2; i <= 100; i += 2)
//sum =sum+i;
sum +=i;
System.out.println(sum);
for (int i = 3; i <= 100; i += 2)
sub += i;
System.out.println(sub);
System.out.println("Sum is: " +(sum-sub));
}
}
Try this code will give you your desired result

Related

Java method to get sum of int based on test logic

I am new to learning java and I have a written a method below. I am trying to understand how to satisfy the tester methods. Is there a way to get the correct logic with the while loop?
I stated that the sum = 0 and while the sum is less than i, increment the sum and loop till it reaches i then return the sum (or thats what i think that's what im trying to do) to satisfy the test. When i look at the junit error message for 1) it says its giving me 10 but expects 55, 2) says im getting 49 but expects 1225. 3) is satisfied. What am i doing wrong here? Is it possible to do this method either with an if statement or while loop?
public int sumOfInts(int i) {
int sum = 0;
while(sum < i)
++sum;
return sum;
}
public void testSumOfInts2() {
int sumOfInts = math.sumOfInts(10);
assertEquals(55, sumOfInts);
public void testSumOfInts3() {
int sumOfInts = math.sumOfInts(49);
assertEquals(1225, sumOfInts);
public void testSumOfInts4() {
int sumOfInts = math.sumOfInts(-49);
assertEquals(0, sumOfInts);
You are looking to make a method that gives you the cumulative sum. The method you have written just gives you the number of times it runs, which is exactly the number you have provided as argument.
You need to differentiate between the counter (the argument) and the cumulative sum, and also update the value of the counter so that the while loop knows when to exit.
Lastly, the <= comparison is necessary to get the correct value (vs just <).
Here is an example:
public int sumOfInts(int i) {
int sum = 0;
int counter = 0;
while(counter <= i) {
sum = sum + counter;
counter = counter + 1;
}
return sum;
}
Try this
public int sumOfInts(int i) {
int sum = 0;
int iteration = 0;
while(iteration < i){
sum = sum+iteration;
iteration++;
}
return sum;
}

How to avoid returning a zero

I have got the code working, it is a prime factorization method class and tester. It prints out the code fine but I am forced to return a zero value, because the method is an Integer method.
public class FactorGenerator{
private int num;
public FactorGenerator(int numberToFactor){
num = numberToFactor;
}
public int nextFactor(){
for(int i = 2; i <= num;){
if (num%i==0){
num = num/i;
System.out.println(i);
}
else{
i++;
}
}
return 0;
}
public boolean hasMoreFactors(){
for(int i = 1; i < num; i++){
if(num % i == 0){
return true;
}
}
return false;
}
}
And this is the tester I am using, which cannot be changed, and must stay the same:
import java.util.Scanner;
public class FactorPrinter{
public static void main(String [] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number to Factor:");
int numberToFactor = in.nextInt();
System.out.println("You chose: "+numberToFactor+" to factor.");
FactorGenerator fg = new FactorGenerator(numberToFactor);
while (fg.hasMoreFactors())
System.out.println(fg.nextFactor());
}
}
When I input 150, it prints 2,3,5,5,0
Is there anyway to remove the 0?
Don't print the factors in nextFactor(). Return them.
public int nextFactor() {
for (int i = 2; ; i++) {
if (num % i == 0) {
num /= i;
//System.out.println(i);
return i;
}
}
}
The test num % i == 0 is guaranteed to return true eventually, so if you remove the i <= num test from the for loop the compiler won't require you to add return 0 at the end.
All required prints are done in nextFactor. So just don't print the return code. Change this:
System.out.println(fg.nextFactor());
by this:
fg.nextFactor();
That said, the nextFactor name is then ill-named. Even if it yields the result, the name suggests that it's a generator which should return each factor at each call, the memory effect being provided by the num member method.
So doing what I'm advising works, but it may not be in the spirit of the problem. John's answer would be better if you have to examine/store the factors, not only print them.
Your hasMoreFactor() method should have returned false by the time it has been invoked four times (and nextFactor returned 2, 3, 5, 5, respectively) and is invoked the fifth time.

java: how to calculate multiplication between all values in variable difference

I received that task:
"A small method, calculateProduct is to be written. It will ask the user to enter two int values, and then calculate and display the product of all the values between the two values entered. For example if the user enters the numbers 2 and 5 the program will display the result 120 (calculated as 2 * 3 * 4 * 5)"
I tried to build something like this:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a;
int b;
int big;
int small;
//ask to insert two variables
System.out.println("Insert variable a");
a = in.nextInt();
System.out.println ("Insert variable b");
b=in.nextInt();
// compare two variables
// set the biggest variables to b, the smallest - to a
if (a >=b){
big=a;
small=b;
}
else {
big=b;
small=a;
}
// set the do while loop to complete the code. Run multiplying before counter won't fit to b variable
int result = small;
for (int i=small; i<=big;i++){
result*=i;
}
System.out.println("the multiplication progression between "+small+" and "+big+" equals to "+result);
}
}
However, when I insert 2 and 5 the result is 240. Does anybody know how to fix it? thanks!
Change loop to:
for (int i = small + 1; i <= big; i++)
{
result *= i;
}
you init result with small then multiply it by small again.
Fix: Start the for statement with small+1
...
int result = small;
for (int i=small+1; i<=big;i++){
result*=i;
}
....
The other obvious solution here is to change the init statement from
int result = small;
to
int result = 1;
In that case you don't have to touch your looping code.
And for the record: "small" is a rather bad name here, why not call it "smallerInput" or something like that.
Finally: you could avoid dealing with "small" - if a < b you can simply loop from a to b; and otherwise you could loop "backwards" from "b to a".
Just change your for loop as below mentioned will solve your problem.
The problem in your loop is :
In its first iteration it is multiple with itself rather than its
incremented value.
From:
for (int i=small; i<=big;i++)
To:
for (int i=small+1; i<=big;i++)
The task is to write a method called "calculateProduct". Above you are doing all your callculation in your main method. Try to separate that. Example :
import java.util.Scanner;
public class Exam {
public static void main (String[]args) {
Scanner in = new Scanner(System.in);
int a;
int b;
System.out.println("Insert variable a");
a = in.nextInt();
System.out.println ("Insert variable b");
b=in.nextInt();
if(a>=b){
calculateProduct(b,a);
}
else{
calculateProduct(a,b);
}
}
public static void calculateProduct (int m, int n) {
int result = 1;
for (int i = m; i <= n; i++) {
result *= i;
}
System.out.println("the multiplication progression between "+m+" and "+n+" equals to "+result);
}
}

Recursive Number Sequence

I want to make a program to output this number sequence: (2),(5),(11),(23),...
where xi = 2*xi-1 + 1, and x0=2.
Here's my code:
public static int num(int n){
if(n <= 0)
return 2;
else
return ((2 * 2)+1);
}
I'm having trouble finding a way to output the numbers 11, 23 and onwards. Would it work if I set a counter variable and continuously loop around the second return statement?
Well seeing as you want it to be recursive, let's make it recursive!
public static int num(int n){
if(n <= 0)
return 2;
else
return (2 * num(n-1))+1; //Recursive call here
}
With a quick runnable method to check it:
public static void main(String[] args){
for(int i = 0; i < 10; i++){
System.out.println("num(" + i + ")=" + num(i));
}
}
Output:
num(0)=2
num(1)=5
num(2)=11
num(3)=23
num(4)=47
num(5)=95
num(6)=191
num(7)=383
num(8)=767
num(9)=1535

Converting decimal to binary in Java

I'm trying to write a code that converts a number to binary, and this is what I wrote. It gives me couple of errors in Eclipse, which I don't understand.
What's wrong with that? Any other suggestions? I'd like to learn and hear for any comments for fixing it. Thank you.
public class NumberConverte {
public static void main(String[] args) {
int i = Integer.parseInt(args);
public static void Binary(int int1){
System.out.println(int1 + "in binary is");
do {
System.out.println(i mod 2);
} while (int1>0);
}
}
}
The error messages:
The method parseInt(String) in the type Integer is not applicable for the arguments (String[])
Multiple markers at this line
Syntax error on token "(", ; expected
Syntax error on token ")", ; expected
void is an invalid type for the variable Binary
Multiple markers at this line
Syntax error on token "mod", invalid AssignmentOperator
Syntax error on token "mod", invalid AssignmentOperator.
Integer.toBinaryString(int) should do the trick !
And by the way, correct your syntax, if you're using Eclipse I'm sure he's complaining about a lot of error.
Working code :
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
toBinary(i);
}
public static void toBinary(int int1){
System.out.println(int1 + " in binary is");
System.out.println(Integer.toBinaryString(int1));
}
}
Maybe you don't want to use toBinaryString(). You said that you are learning at the moment, so you can do it yourself like this:
/*
F:\>java A 123
123
1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0
*/
public class A {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
System.out.println(a);
int bit=1;
for(int i=0; i<32; i++) {
System.out.print(" "+(((a&bit)==0)?0:1));
bit*=2;
}
}
}
I suggest you get your program to compile first in your IDE. If you are not using an IDE I suggest you get a free one. This will show you where your errors are and I suggest you correct the errors until it compiles before worring about how to improve it.
There are a two main issues you need to address:
Don't declare a method inside another method.
Your loop will never end.
For the first, people have already pointed out how to write that method. Note that normal method names in java are usually spelled with the first letter lowercase.
For the second, you're never changing the value of int1, so you'll end up printing the LSB of the input in a tight loop. Try something like:
do {
System.out.println(int1 & 1);
int1 = int1 >> 1;
} while (int1 > 0);
Explanation:
int1 & 1: that's a binary and. It "selects" the smallest bit (LSB), i.e. (a & 1) is one for odd numbers, zero for even numbers.
int1 >> 1: that's a right shift. It moves all the bits down one slot (>> 3 would move down 3 slots). LSB (bit 0) is discarded, bit 1 becomes LSB, bit 2 becomes bit one, etc... (a>>0) does nothing at all, leaves a intact.
Then you'll notice that you're printing the digits in the "wrong order" - it's more natural to have them printed MSB to LSB. You're outputting in reverse. To fix that, you'll probably be better off with a for loop, checking each bit from MSB to LSB.
The idea for the for loop would be to look at each of the 32 bits in the int, starting with the MSB so that they are printed left to right. Something like this
for (i=31; i>=0; i--) {
if (int1 & (1<<i)) {
// i-th bit is set
System.out.print("1");
} else {
// i-th bit is clear
System.out.print("0");
}
}
1<<i is a left shift. Similar to the right shift, but in the other direction. (I haven't tested this at all.)
Once you get that to work, I suggest as a further exercise that you try doing the same thing but do not print out the leading zeroes.
For starters you've declared a method inside a method. The main method is the method that runs first when you run your class. ParseInt takes a string, whereas args is an Array of strings, so we need to take the first (0-based) index of the array.
mod is not a valid operator, the syntax you wanted was %
You can use System.out.print to print on the same line rather than println
Try these corrections and let me know how you get on:
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
Binary(i);
}
public static void Binary(int int1){
System.out.println(int1 + " in binary is ");
do {
System.out.print(int1 % 2);
int1 /= 2;
} while (int1 > 0);
}
}
Here is a small bittesting code I made for Android.
int myres = bitTest(7, 128);
public int bitTest(int bit,int value)
{
int res = 0;
int i = 0;
while (i <= bit) {
res = (value & 1);
value = value >> 1;
i++;
}
return res;
}
Best Regards
Mikael Andersson
StringBuffer sb = new StringBuffer("");
void breakNumber(int num){
if(num == 0 || num == 1){
System.out.println(num);
}else{
int modr = num % 2;
sb.append(modr);
int divr = num / 2;
if(divr > 1){
breakNumber(divr);
}else{
sb.append(modr);
StringBuffer sbr =sb.reverse();
System.out.println(sbr.toString());
}
}
}
package gg;
import java.util.*;
public class Gg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean flag = true;
while (flag) {
menu();
int n = in.nextInt();
switch (n) {
case 1:
System.out.println("enter an integer decimal number : ");
int d = in.nextInt();
System.out.print("the answer is ");
DTB(d);
System.out.println();
break;
case 2:
System.out.println("enter a binary number : ");
int b = in.nextInt();
System.out.print("the answer is " + BTD(b));
System.out.println();
break;
case 3:
flag = false;
break;
}
}
}
public static void menu() {
System.out.println("1.convert decimal to binary : ");
System.out.println("2.convert binary to decimal : ");
System.out.println("3.exit");
}
public static void DTB(int x) {
int n = 0;
int y = x;
while (y > 0) {
y /= 2;
n++;
}
int s[] = new int[n];
int i = 0;
while (x > 0) {
s[i] = x % 2;
x /= 2;
i++;
}
for (int j = s.length - 1; j >= 0; j--) {
System.out.print(s[j]);
}
}
public static int BTD(int x) {
int y = 2;
int sum = 0;
double k = 1;
int c = 0;
while (x > 0) {
double z = x % 10;
x /= 10;
k = Math.pow(y, c);
c++;
k *= z;
sum += k;
}
return sum;
}
}

Categories

Resources