solve through a loop in java - java

I have a text box(having name b) and one submit button in index.jsp. I will enter something in text box then after clicking submit i get that value by in server side find.jsp. In find.jsp i get the value by request.getParameter("b"); In find.jsp calaculation is done as shown below:
double c=0;
double d=0;
7800.0/12 and 2640.0/12 are fixed.
if request.getParameter("b")=1 then
c=7800.0/12*5;// 5 is multiplied with above number(in first one)
d=2640.0/12*5;// 5 is multiplied with above number(in second one)
if request.getParameter("b")=2 then
c=7800.0/12*8;// here 5 gets incremented by 3 and became 8(in first one)
d=2640.0/12*8;// same also here( in second one)
Similarly if i will enter 20 then accordingly c and d will be calculated.
I cannot use if-else as any value can be entered in client side and accordingly c and d will be calculated in server side.
How can i implement it in a loop? Many thanks

try
double devide=2.0
devide = Integer.parseInt(request.getParameter("b"))*3+devide
c=7800.0/(12*devide);
d=2640.0/(12*devide);

You can use for any value to count below one logic.
int value = Integer.parseInt(request.getParameter("b"));
double x=2.0;
double valueForDevide = (value*3)+x;
c=7800.0/(12*valueForDevide );
d=2640.0/(12*valueForDevide );

Related

Java: How to apply filters to set?

In my program I've different scenarios
In the beginning set will be empty like this:
[]
User can add values in the set dynamically let say user enter start and end integers as 2 and 6, set will be like this:
[2,3,4,5,6]
A) What user can do:
After user can do like this let say user enter 1 and 2, set will be like this:
[1,2,3,4,5,6]
User can also do like this let say user enter 6 and 8, set will be like this:
[1,2,3,4,5,6,7,8]
B) What user cannot do is this:
Let say user enter 2 and 6 as 2,3,4,5,6 is already present in the set, so program should output error message to the user.
User also cannot do, let say user enter 0 and 10 as 0,1,2,3,4,5,6,7,8,9,10 bold integers are already present in set, so program should output error message to the user.
C) Final Result:
In the end set should be like this [1,2,3,4,5,6,7,8]
Update:
User can also do like this, say in the beginning set is empty like this:
[]
User enter 1 and 3, set will be like this:
[1,2,3]
Afterwords user enter 5 and 7, set will be like this:
[1,2,3,5,6,7]
After user enter 3 and 5, set will be like this
[1,2,3,4,5,6,7]
How can I achieve this, any help would be greatly appreciated.
What I've tried so far is not working:
Scanner reader = new Scanner(System.in);
System.out.println("Enter a start: ");
int s = reader.nextInt();
System.out.println("Enter a end: ");
int e = reader.nextInt();
Set<Double> filterSet = new TreeSet<>();
for (int i = s; i <= n; i++) {
if(filterSet.stream().allMatch(x -> x>=s && x<=e)){
System.out.println("Error");
}
else{
filterSet.add(i);
}
}
The reason your stream expression is not working is because your definition of a range is not consistent. This inconsistency creates many edge-cases that you must test when deciding whether or not the result is valid. Some examples (from your update):
Starting with an empty set, Ø, union it with [1,3] (note that this is a closed set from mathematics) giving the result {1,2,3}
Union the previous result with [5,7] (another closed set) resulting in {1,2,3,5,6,7}
Union that result with (3,5) (notice that this is an open set) resulting in {1,2,3,4,5,6,7}
If we stopped here, you could create a coherent rule where the computation is considered successful if the cardinality of the result is greater than the cardinality of the original set, |currentValue| > |previousValue|. However, you provided an example in your original post where you computed the union of [0,10] with [1,8] where this rule fails (i.e., values {0,9,10} were added to the set). Even though the cardinality of the result, 11, is greater than the cardinality of the previous value, 8, the computation is considered a failure.
You could even be generous and consider all new inputs to be open sets, [1,8] ∪ (0,10) ⇔ [1,8] ∪ [1,9] (notice the change from open to closed sets), but this would still result in one change that you were not expecting (9 was added to the set), hence the need for testing edge cases.
A similar case exists where you start with the set [2,6] (i.e., {2,3,4,5,6}) and union it with [1,2) (notice the partially open set) that results in [1,6] (i.e., {1,2,3,4,5,6}), which is considered a success even though it results in a single change like the previous example. In this case, the element 1 is added to the set rather the element 9.
In one case, I've added an element to the end of the sequence and in the other case, I've add the element at the beginning of the sequence. Why should these be treated differently?
You should not expect a quality answer to your question until you provide a consistent way to determine whether the result is valid.
See: notation
I achieved what I wanted by using Google Guava’s RangeSet interface. Thanks to #shmosel who pointed this out to me.
Scanner reader = new Scanner(System.in);
System.out.println("Enter a start: ");
int s = reader.nextInt();
System.out.println("Enter a end: ");
int e = reader.nextInt();
RangeSet<Integer> rangeSet= TreeRangeSet.create();
if(rangeSet.isEmpty()){
System.out.println("1 Empty");
rangeSet.add(Range.closed(s, e));
}else {
System.out.println("1 Not Empty");
if(!rangeSet.encloses(Range.closed(s, e)) && !rangeSet.intersects(Range.open(s, e))){
System.out.println("2 Yes");
rangeSet.add(Range.closed(s, e));
}else{
System.out.println("2 No");
}
}
System.out.println("Range: " + rangeSet)

Need to draw a path using points in an arraylist

I've developed an android Travelling Salesman Problem (TSP) game application in which the user makes a path and plays against the computer, which uses the TSP algorithm to make a full path every time the user clicks to join two points with a line. Currently my method for the computer's path being draw is called whenever the user makes their move. However, my code is only allowing the first two points in the computer's path (stored in the arraylist called 'test') to be joined up.
public void CompDrawLine(List<Point> test) {
int d = 0;
int i;
test.add(test.get(0));
Point c = test.get(d);
for (i=0;i<test.size();i++)
{
cPath.moveTo(c.x,c.y);
c = test.get(d+1);
cPath.lineTo(c.x,c.y);
mCanvas.drawPath(cPath,cPaint);
// String testIndex = "this is iteration" + i;
// Toast.makeText(mContext, testIndex, LENGTH_SHORT).show();
}
cPath.reset();
}
How do I get the complete path drawn whenever the method is called??
I think your error is in the second line of your for loop. The variable d is never being incremented, so you are always using points 0 and 1. Personally, I would get rid of the d variable and just use i like this:
c = test.get(i+1);
However, another option would be to use d and increment it each time:
c = test.get(++d);
It must be a pre-increment though, or else you will be going from point 0 to point 0, and then point 1 to point 1, etc. instead of point 0 to 1, since d is initialized to 0.

How to initialize a variable in a do while loop without passing the value until the loop has closed?

I've been writing a program that requires the input of a number between 1 and 4. In order to prevent input of numbers outside the range. However the variable keeps passing to another piece of code and causing the program to fail.
This is the do while loop:
do
{
System.out.println("Please enter a quarter number 1-4: ");
quarter = scanIn.nextInt();
}while((quarter > 5 ) && (quarter < 0));
This is the piece of code that runs the variable:
for (int n = ((quarter * 3)-3); n < (quarter*3); n++)
{
String sum = fmt.format(monthSales[n]);
System.out.printf("Sales for month %d: %s\n", n+1, sum);
}
This is the error that returns when incorrect input is entered:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -6
at lab4.Lab4.main(Lab4.java:57)
I have tried limiting the scope of "quarter" to only within the loop but then the while clause does not function. How can I prevent the variable from passing until the loop has closed?
p.s. This problem is part of an assignment and therefore I must use a do while loop.
I see one thing in your code:
The "do/while" condition seems to be wrong. If your intention is, as I understood, keep asking the user until s/he informs a valid quarter between 1 and 4, the condition should be something like
do {
// ...
} while (quarterNum < 1 || quarterNum > 4);
If I suppose that quarter receives the value of quarterNum in some code in between, the second part seems to be correct and the exception should only occurs if quarter is not a valid value (-1 to be exact). Fixing the do/while condition it will not be possible any more.
I don't see where limiting variable scopes could have anything with your issue. (and I don't even see what you mean by "prevent[ing] the variable from passing until the loop has closed").
I hope I could help you.

states and capitals 2d array, java

here are my requirements:
Create (hard coded) the 50 states and their capital cities, using a 2
dimension array.
In the dialog box: ask the user either to enter the State or a City.
If the state is entered, find its capital city. If a city is entered,
find its State.
If not, found, issue an error message.
This should be in a Loop, until the user does not want to play
anymore.
I really don't know where to start, all I have done so far is create the array, I don't really get how to search the array, and spit out the corresponding state/capital.
Any help would be greatly appreciated.
Here is the code I have written so far.
import java.util.Scanner;
public class GuessStates {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
String[][] statesAndCapitols = {
{"Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"},
{"Montgomery","Juneau","Phoenix","Little Rock","Sacramento","Denver","Hartford","Dover","Tallahassee","Atlanta","Honolulu","Boise","Springfield","Indianapolis","Des Moines","Topeka","Frankfort","Baton Rouge","Augusta","Annapolis","Boston","Lansing","St. Paul","Jackson","Jefferson City","Helena","Lincoln","Carson City","Concord","Trenton","Santa Fe","Albany","Raleigh","Bismarck","Columbus","Oklahoma City","Salem","Harrisburg","Providence","Columbia","Pierre","Nashville","Austin","Salt Lake City","Montpelier","Richmond","Olympia","Charleston","Madison","Cheyenne"}};
System.out.println("Please enter a State or a capitol city.");
String userInput = input.nextLine();
}
}
thanks again!
try searching through the array with a for loop.
Using a for loop it keeps track and updates your current position of traversing the array.
Once you find the correct state or capital (by checking if userInput.equalsIgnoreCase(statesAndCapitols[x][y]), then take the current position you are at and retrieve the information needed.
I.E.
for(int x = 0; x < 2; ++x) //loop through states the first time, capitols the second
for(int y = 0; y < 50; ++y) //always 50, unless new states get added (obviously not a problem in this example, but useful to think about in future problems - YOUR DATA WILL ALMOST ALWAYS CHANGE.
if(userInput.equalsIgnoreCase(statesAndCapitols[x][y])
System.out.println(statesAndCapitols[x == 1 ? 0 : 1][y]);
In the array, I did x == 1 ? 0 : 1. That's a ternary operator, what it's saying is if x is equal to 1, use the value 0, otherwise use the value 1.
That's one way to go about this problem.
Another way would be to create your own Class/Datatype for the cities and states, that way you don't need to keep your arrays in sync, meaning you don't need to update 2 items for one change (like add another city/state combo).
Hope this helps a bit! :)
String entered_state=input.nextLine();
for(int i=0;i<50;i++){
if(statesAndCapitols[0][i].equals(entered_state)){
String searched_city=statesAndCapitols[1][i];
//print the city name
break;
}
}
if(i==50)
//print error
Same thing for searching state from entered city.

Create A Method In Java

Hello I am trying to create a method in Java that Accepts an integer from the user. Calculate and display how many occurences of the integer are in the array(i'm Creating a random array) as well as what percentage of the array values is the entered integer.
This is how i create my Array:
public void fillVector ( )
{
int myarray[] = new int [10];
for (int i = 0 ; i < 10 ; i++)
{
myarray [i] = (int) (Math.random () * 10);
}
}
Any sugestions how can i do to accomplish this ?
This seems like a homework to you so I am not gonna give you the full solution but I will break down the steps of what you need to do in order to solve your problem. You have to find out how to code those steps yourself, or at least provide some code and your specific problem because your question is too vague right now.
Ask the user to input the number.
Store that number somewhere.
Check each cell of the array for that number. If you find one appearance
increase the counter and continue until the end of your index.
Print out the appearances of the given number.
Print out the percentage of the cells containing the given value to the total amount of cells.
As I can see from your code (if it's yours) you are capable to pull this off on your own. It shouldn't be too hard.

Categories