i am using the following code:
//Calculating Profit and Loss
float difference= sell_amount-buy_amount;
if (flag == 0) {
if ((difference<0)) {
System.out.print("Loss ");
System.out.println(difference - total_extra);
} else {
System.out.println("Profit ");
System.out.println(difference - total_extra);
}
}
even if in some inputs, the output is -0.53, it still says profit.. where am i going wrong
When you print out the difference, you also remove the value of total_extra.
Thus, let's say diffrence = 0.47 and total_extra = 1. The difference is indeed positive (thus printing "Profit", but when you print the value difference - total_extra, you print out "-0.53"
Related
I tried this a lot, and debugged it a few times, everything seems to be working and largest prime does indeed become the largest prime even if it takes rather long.
I can't get the printed value from System.out.println. I could find it through the debugger but the value is too high to find fast just holding down step over.
It compiles as well so I am stumped about what's the issue here. I would be very happy to know what I did wrong.
Edit: The reason why I wrote this code in the first place is because in the site project euler it asked for the largest prime value that when divided with the value of primer gave a whole number.
Is there a way at least that would allow me to make it faster with the same value? this seems rather impractical.
package unit5;
public class Primefinder { public static void main(String[] args)
{
double primer = 600851475143d;
double largestprime = 0;
Boolean ifprime = false;
for(double x = 2d; x < primer; x++)
{
for(double z = 2d; z<x; z++)
{
if( (x%z == 0) && (z != x) )
{
ifprime = false;
break;
}
else {
ifprime = true;
}
}
if((ifprime != false) && (x > largestprime))
{
largestprime = x;
}
ifprime = false;
}
System.out.print(largestprime);
}
}
for other questions you might ask everywhere, please tell us that what is the purpose of your code. this way it is easier to get the fault.
the code you have written above runs completely but the numbers you have used are too big so you need to wait a lot, so that compiler be able to reach to this line:
System.out.print(largestprime);
use lower numbers (at least for test) or wait properly.
Your 'primer' Value is very big.
So, loop is taking very much time to reach at '600851475143' value.
Wait Sometime and it with show largest prime number
I have recently started a course where the main language we are learning at the moment is Java.
I have been tasked with creating a program that allows people to vote on two candidates - the program then counts the votes, and depending on how man votes have been made depends on what is displayed.
Here is the part I am concerned with at the moment:
public String printResults(){
if(candidate1Votes == 0 && candidate2Votes == 0)
{
System.out.println ("No votes cast, results cannot be displayed.");
return "No votes cast, results cannot be displayed.";
}
else if(this.completed == false)
{
System.out.println ("Voting has not finished");
return "Voting has not finished";
}
else if(this.completed == true)
{
System.out.println ("Voting has finished, no more votes will be allowed.");
return "Voting has finished, no more votes will be allowed";
}
{
double totalVotes = this.candidate1Votes + this.candidate2Votes;
double cand1Share = (double) this.candidate1Votes/totalVotes*100;
double cand2Share = (double) this.candidate2Votes/totalVotes*100;
System.out.format(candidate1 + " received %3.1f percent of the votes\n", cand1Share);
System.out.format(candidate2 + " received %3.1f percent of the votes\n", cand2Share);
return "v";
}
}
Originally I used void in this method, but part of our task was to then change it to a string value. This is where I am struggling - once I set completed to true, it is still allowing me to cast votes. I know that this code is incomplete but I can't finish it as I am unsure what to do! These were the next parts to the questions.
Modify your printResults method so that it applies the first two rules. Note that the value of the completed field indicates whether or not voting is complete. The method should be modified to return a String which indicates whether printing has been successful.
Modify your vote method to apply the third rule.
Test your methods by creating an instance and doing the following – before
doing each test note the result you expect to get, and compare this with what you actually get:
• Try to print results immediately
• Cast votes for both candidates and try to print results
• Set the completed field to true by calling setCompleted
• Try to cast a vote for a candidate
• Print the results
I am new to this (this is my first year) and have managed to do okay in my books to get this far, however any help on this next issue would be greatly appreciated!
First of your code is unnecessary complicated, which makes it hard to read/enhance. It can easily simplified, like
public String printResults(){
if(candidate1Votes == 0 && candidate2Votes == 0) {
System.out.println ("No votes cast, results cannot be displayed.");
return "No votes cast, results cannot be displayed.";
} // you returned ... NO need for ELSE!
if(this.completed == false) {
System.out.println ("Voting has not finished");
return "Voting has not finished";
}
// it is very clear here that completed must be true!
double totalVotes = this.candidate1Votes + this.candidate2Votes;
double cand1Share = (double) this.candidate1Votes/totalVotes*100;
double cand2Share = (double) this.candidate2Votes/totalVotes*100;
System.out.format(candidate1 + " received %3.1f percent of the votes\n", cand1Share);
System.out.format(candidate2 + " received %3.1f percent of the votes\n", cand2Share);
return "v";
}
Probably that easier-to-read code is all that you need to get you going!
Looking at the code the last block will never be reached because either you have no votes or you have votes and in that case completed will be either true or false and will thus reach always one of the else ifs and they all return a string. So I wonder why how you can cast any votes at all.
You could also post the code where you call printResults and setCompleted to see where the problem lies.
Some more hints for improving your code:
Sometimes you have the opening bracket on the same line and sometimes on the next. You should probably choose one style
It is not necessary to surround the last code block with brackets
if (this.completed == true) and else if (this.completed == false) is a bit redundant and can be written like: if (this.completed) and if (!this.completed). Also you can write
if (this.completed) {
...
} else {
....
}
because if completed is not true it can only be false.
Instead of writing every String two times and having to edit it two times in case you want to change something you could also do the following:
String msg = "Voting has not finished"
System.out.println(msg);
return msg;
The purpose of this program is to take in positive integers and once the sentinel value (-1) is hit the program will return the 2 lowest numbers. My program works, but in some scenarios it doesn't. for example if I enter 10,15,20,-1 the program will result in 10 rather than 10 and 15. Here is my program:
public class Small{
public static void main(String [ ] args){
int number;
number=IO.readInt();
int lowest=number;
int lowest2=number;
while (number!=-1){
number=IO.readInt();
if(number>0){
if(number<lowest && number!=-1){
lowest=number;}
else{if((number<lowest2||!(number>=lowest2))&& number!=-1){
lowest2=number;}
}
}
}
IO.outputIntAnswer(lowest);
IO.outputIntAnswer(lowest2);
}
}
The main problem with your code is that you set lowest and lowest2 to the first value you enter. If all the other numbers you enter are higher than the first number, it will never be able to find anything lower.
With your example, the first number is 10 which you assign to lowest and lowest2. When you enter 15, it's not lower than 10, so neither variable can be reset. Same with 20.
You've also got a lot of redundant checks in your if-statements.
public class Small {
public static void main(String [ ] args) {
int number;
int lowest = Integer.MAX_VALUE;
int lowest2 = Integer.MAX_VALUE;
while (number!=-1) {
number=IO.readInt();
if (number > 0) {
if(number < lowest) {
lowest=number;
}
else if (number < lowest2) {
lowest2=number;
}
}
}
}
IO.outputIntAnswer(lowest);
IO.outputIntAnswer(lowest2);
}
The problem is with your logic flow of the program. Here's what the code is doing:
Read in one number, store in both lowest and lowest2.
Go through loop to read in more numbers
2a. If the number is positive, check against lowest.
2a1. If the read in value is lower than lowest, change lowest's value to the read in value.
2a2. Otherwise, if the read in value is lower than lowest2, change lowest2's value to the read in value. Only do this if lowest was not changed.
2b. If the read in value is -1, end the loop.
2c. If the read in value is negative but not -1, continue but don't add the number to lowest or lowest2.
Print out the values for lowest and lowest2.
If you see the error, it's in 2a2. This is linked to the fact that your setup before the while loop is formatted as you did: you made both lowest and lowest2 that first value.
This code would normally run correctly, except for one instance: what if that first value were to be the smallest positive value you entered, with all other values greater than it? lowest2 would be set to that value, and you're checking to see if any other values are smaller than it (which they're not, because they're all going to be greater than it).
Tips for when you're coding:
1) Attempt to develop a logical thinking mentality. Think through how you want to create algorithms for your program. Make sure you don't run into any situations where your program does not run the way you want it to, like in this case (this is called a logic error).
2) Run through your programs by hand when you're finished coding, or after you've run it and got an error. Step through every line of your code, and try to see where and why your code isn't working the way you want it to. Or have someone else see, like a fellow programmer. Sometimes, even the best eyes do not catch their own mistakes.
EDIT:
There are various ways to solve this particular problem. One way is to do what Seeker and Rick did:
1) Set both values to the largest possible Integer value, and thus all values entered will be lower than the first values.
2) Ask for the first two inputs at the beginning before the loop, and check them against each other to set the first two lowest values.
However, I believe there are certain things to watch out for when you're doing something like this. These should all be outlined before you code, of course.
1) What if the user is entering only one or zero valid values? Seeker's method wouldn't work, unless he checks that the first/second value is negative/-1. Rick's method wouldn't work either because at least one of the lowest/lowest2 values would still be that max Integer value.
2) What if there were no positive values entered before the -1? This is similar to number 1, and your ints would be null.
You can certainly use Seeker's and Rick's algorithms, but you should check for these conditions if you use them.
import java.util.Scanner;
public class Small {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Number");
int lowest = scanner.nextInt();
System.out.println("Enter Number");
int lowest2 = scanner.nextInt();
if (lowest > lowest2) {
int t = lowest;
lowest = lowest2;
lowest2 = t;
}
while (true) {
System.out.println("Enter Number");
int number = scanner.nextInt();
if (number == -1)
break;
if (number < lowest2 && number < lowest) {
lowest = number;
} else if (number < lowest2) {
lowest2 = number;
}
}
System.out.println("lowest:" + lowest);
System.out.println("lowest2:" + lowest2);
scanner.close();
}
}
private String twoDigits(int value) {
String result = "";
{
if ((mMinute >= 0) && (mMinute <= 9) && (mSecond >= 0) && (mSecond <= 9)) {
tempmin = ("0" + mMinute );
tempsec = ("0" + mSecond );
} else
tempmin = (mMinute + "");
tempsec = (mSecond + " ");
return tempin+tempsec;
This just doubles the output that I'm looking for and I was wondering, whether or not the issue was with the return statement or the actual method.
I need to call back to this method, twoDigits(mMinute)+":"+twoDigits(mSecond) to get the code to display the time, but instead of being able to display 10:09:08 I keep displaying 10:0908:0908
I was wondering how I should fix my code.
Since there are a lot of tiny mistakes in your code, I'll suggest a slightly different approach. Not sure if this method works, in what I assume is Java, but give it a shot:
private String twoDigits(int value)
{
return value <= 9 ? "0" + value : value;
}
This is actually an if/else abbreviation. Return the following: If value <= 9 then add a zero before the value, else the value.
If there's a risk of negative values being received, you could add this:
return (value >= 0 && value <= 9) ? "0" + value : value;
First, there's Paul's comment about the {} after else to encompass both rows. Then, you are not actually using the value received by the function but rather some global variables (mMinute and mSecond). You create but never use result. Furthermore, your if statement says that if both mMinute AND mSecond are between 0 and 9 then both should be fixed. Since you should use value you only have to check that variable's range and edit it accordingly. On the row tempsec = (mSecond + " "); you add a space.. mistake? Finally, you misspelled tempmin on the return row.
Good luck.
Note that your method has a value parameter. You should use this rather than directly access the fields in your class. Perhaps it might help for you to think about the purpose of the twoDigits() method. It seems to me that it is supposed to take an int value and pad it with a leading zero if the input is only a single digit. Note that my description in the previous sentence does not refer to the member variables that represent minutes and seconds; it only refers to the input value.
I am devoloping an application to find the minimum of all the numbers entered .It accepts the numbers from the dialog box and when the user enters 0 it displays the minimum of all the numbers.But i dont need the 0 but the minimum of the numbers that preceeded it.
My code is as Follows:
try {
int a, c = 0, d = 0;
do {
a = Integer.parseInt(jOptionPane1.showInputDialog(null, "please enter the number"));
c = Math.min(a, d);
if (a != 0) //since a=0 will be excecuted one time
{
d = c;
}
} while (a != 0);
lb2.setText("Minimum of the numbers is " + d);
} catch (Exception e) {
jOptionPane1.showMessageDialog(this, "Some thing went wrong");
}
I know that it gives me 0 because the minimim of the numbers entered is zero and if i enter a number less than 0 (ie a negative number)it gives me the correct answer .I think the problem is also due to the initialisation that c=0.
Now i need a method to find the minimum without using any arrays and it should be simple and easy.(most helpful if you use Math.min itself)
Any help Appreciated.
Just change your initialization to set d set to Integer.MAX_VALUE.
I have an advice for your code, that you should make every variable names make sense. Maybe your code is small, but it will affect your habit, and when you work in large project, your habit will affect you so much :)
You should change initialize part of d = 0 to d = Integer.MAX_VALUE. Here is a new code :
try {
int inputNumber = 0, min= Integer.MAX_VALUE;
// int c : you don't need this variable
do {
inputNumber = Integer.parseInt(jOptionPane1.showInputDialog(null, "please enter the number"));
if (inputNumber != 0) //since a=0 will be excecuted one time
{
min= inputNumber;
}
} while (inputNumber != 0);
lb2.setText("Minimum of the numbers is " + min);
} catch (Exception e) {
jOptionPane1.showMessageDialog(this, "Some thing went wrong");
}
This new code is make more sense ?
And, Why you Must change initialize to min= Integer.MAX_VALUE? For example, you initialize like this : min = 10;. And at first time when someone type 15, you program will see : Oh, 15>10, so this is not the min value. But in fact, 15 is the first value of input and it should be the min value. Your program will be wrong until someone type a number less than 10.
Compare to your code, because you initialize d=0. when you type d=1, ops, 1>0, this is not min value (like above example). And everything will true only when you type some numbers < 0.
Al the problem above happen, because although user types any number, the min is the initialize number. (the number that user doesn't type). And that why you set your min value to something REALLY REALLY big. So, the FIRST TIME you type some numbers, It's ALREADY the SMALLEST.
Because machine not like us, doesn't have "infinity", so we must set it the biggest value possible. And because d is an int, so the biggest value of int is Integer.MAX_VALUE. In fact, you can type number for d. I don't remember exactly, but the biggest value for integer in range 32000 (2^31).