I've just jumped to the programming field. Please help me to find a reasonable solution to one of my educational projects. In case of incorrect input (for example 'z' in place of a figure) my program starts an infinite loop. I'm looking for the alternative to the infinite loop and catch use. At least, maybe someone could suggest how to empty the tray (the methods available on this site don't work with my Win7, NetBeans IDE 7.4).
OBJECTIVE
Develop a program that allows the determination of a specific number of metrics obtained in a survey.
Data
A company sponsors you for the realization of a survey system to a target prospects. According to data collected on individuals during the day, we can calculate metrics that can help the company to better target customers.
The questions used for the survey are:
Question 1: Did you like to use our product?
Question 2: If the answer to question 1 is yes, you will continue to use our product?
Question 3: Do you plan to use a product of our competitor?
Question 4: On a scale of 1 to 3 (1: bad, 2 neutral, 3 good), how do you consider the reputation of our company?
The specific task is to determine the percentages for each question. For questions 1 to 3, percentages of YES and NO are required. For question 4 the percentages of each possible choice are needed.
The data is stored in a single memory structure during the course of the program. By late afternoon, an agent terminates the program after outputting data. Therefore, we will not persist on files or databases for the moment.
Data or metrics will be posted later in the day in a clear format.
So, the purpose is to realize the capture and storage of data and to calculate metrics.
Here you are my Java code:
package surveyproject;
import java.util.Scanner;
import java.util.ArrayList;
public class SurveyProject {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList TotalSurvey = new ArrayList();
do {
try
{
System.out.println("Welcome to survey !");
System.out.println("1 - New survey");
System.out.println("2 - Publish survey results");
System.out.println("3 - Leave the program");
int new_or_printing_results_or_exit = sc.nextInt();
if (new_or_printing_results_or_exit == 1)
{
// ============== Questions 1 and 2 ================ //
System.out.println("Do you use our product? 1-yes 0-no");
int Q1_using_product = sc.nextInt();
int Q2_using_product_in_future = -1;
if (Q1_using_product == 1)
{
System.out.println("Thanks to use our product. Will you "
+ "continue to use it? 1-yes 0-no");
Q2_using_product_in_future = sc.nextInt();
}
else
{
System.out.println("That's a pity you do not use your product.");
}
// =====///====== Question 1 and 2 ================ //
// ============== Question 3 ================ //
System.out.println("Do you use the products of our competitors? 1-yes 0-no");
int Q3_using_competitor_product = sc.nextInt();
// =====///====== Question 3 ================ //
// ============== Question 4 ================ //
System.out.println("Evaluate our company.");
System.out.println("1 - Bad");
System.out.println("2 - Neutral");
System.out.println("3 - Good");
int Q4_company_reputation_rate = sc.nextInt();
// =====///====== Question 4 ================ //
System.out.println("Thank you for the participation!");
// =========== Save current Survey =========== //
Survey objSurvey = new Survey(Q1_using_product,
Q2_using_product_in_future,
Q3_using_competitor_product,
Q4_company_reputation_rate);
TotalSurvey.add(objSurvey);
// =====///=== Save current Survey =========== //
}
else if (new_or_printing_results_or_exit == 2)
{
PrintSurveyResult(TotalSurvey);
}
else if (new_or_printing_results_or_exit == 3)
{
System.out.println("Thank you to use our system!");
System.exit(0);
}
}
catch(Exception except)
{
System.out.println("You entered incorrect answer. Please,"
+ "try again the survey." );
System.out.println("Total answers: " + total_answers);
System.out.println("Question 1: ");
System.out.println("Yes answered: " + Q1_answer_yes + "(" + (double)Q1_answer_yes/total_answers * 100.0 + "%)");
System.out.println("No answered: " + Q1_answer_no + "(" + (double)Q1_answer_no/total_answers * 100.0 + "%)");
System.out.println("Question 2: ");
System.out.println("Yes answered: " + Q2_answer_yes + "(" + (double)Q2_answer_yes/total_answers * 100.0 + "%)");
System.out.println("No answered: " + Q2_answer_no + "(" + (double)Q2_answer_no/total_answers * 100.0 + "%)");
System.out.println("Question 3: ");
System.out.println("Yes answered: " + Q3_answer_yes + "(" + (double)Q3_answer_yes/total_answers * 100.0 + "%)");
System.out.println("No answered: " + Q3_answer_no + "(" + (double)Q3_answer_no/total_answers * 100.0 + "%)");
System.out.println("Question 4: ");
System.out.println("Bad answered: " + Q4_answer_bad + "(" + (double)Q4_answer_bad/total_answers * 100.0 + "%)");
System.out.println("Neutral answered: " + Q4_answer_neutral + "(" + (double)Q4_answer_neutral/total_answers * 100.0 + "%)");
System.out.println("Good answered: " + Q4_answer_good + "(" + (double)Q4_answer_good/total_answers * 100.0 + "%)");
}
}
package surveyproject;
public class Survey {
int Q1_using_product;
int Q2_using_product_in_future;
int Q3_using_competitor_product;
int Q4_company_reputation_rate;
public Survey (int Q1, int Q2, int Q3, int Q4)
{
Q1_using_product = Q1;
Q2_using_product_in_future = Q2;
Q3_using_competitor_product = Q3;
Q4_company_reputation_rate = Q4;
}
public int getQ1_using_product()
{
return Q1_using_product;
}
public int getQ2_using_product_in_future()
{
return Q2_using_product_in_future;
}
public int getQ3_using_competitor_product()
{
return Q3_using_competitor_product;
}
public int getQ4_company_reputation_rate()
{
return Q4_company_reputation_rate;
}
}
Related
I'm trying to traverse the graph with an interval. Each edge has a property("interval") storing the intervals. I'm using withSack to propagate the intersections of the intervals to the next step. If there's no intersection the traversal should stop.
For example:
V1 e1 V2 e2 V3 e3 V4
O----------------------O----------------------O----------------------O
^
[[1,3],[5,7]] [[4,6]] [[7,9]]
e1.interval e2.interval e3.interval
If I start traversal from V1 with interval [2,8], I want it to return
V1: [[2,3],[5,7]]
V2: [[5,6]]
Notice that V3 and V4 is not included since the intersected interval on e2 stops at 6.
I'm using Tinkerpop Java API and for this purpose, I defined a method that returns the intersections of the intervals and tried to use withSack(Lambda.biFunction(...)). The function has while loop with curly braces({}) and I think it causes a problem on the gremlin server's script engine. The exception I'm getting is this:
Script28.groovy: 1: expecting '}', found 'return' # line 1, column 520.
get(j).get(1)) i++; else j++;}return int
I'm passing the function as a string to (Lambda.biFunction(...)) like this:
"x, y -> " +
"List<List<Long>> intersections = new ArrayList();" +
"if (x.isEmpty() || y.isEmpty()) return new ArrayList<>();" +
"int i = 0, j = 0;" +
"while (i < x.size() && j < y.size()) {" +
"long low = Math.max(x.get(i).get(0), y.get(j).get(0));" +
"long high = Math.min(x.get(i).get(1), y.get(j).get(1));" +
"if (low <= high) intersections.add(Arrays.asList(low, high));" +
"if (x.get(i).get(1) < y.get(j).get(1)) i++; else j++;" +
"}" +
"return intersections;";
For the readability I'm also putting the original function:
public List<List<Long>> intersections(List<List<Long>> x, List<List<Long>> y) {
List<List<Long>> intersections = new ArrayList();
if (x.isEmpty() || y.isEmpty()) {
return new ArrayList<>();
}
int i = 0, j = 0;
while (i < x.size() && j < y.size()) {
long low = Math.max(x.get(i).get(0), y.get(j).get(0));
long high = Math.min(x.get(i).get(1), y.get(j).get(1));
if (low <= high) {
intersections.add(Arrays.asList(low, high));
}
if (x.get(i).get(1) < y.get(j).get(1)) {
i++;
} else {
j++;
}
}
return intersections;
}
I have 2 questions:
How to pass a complex lambda function like this to gremlin server?
Is there a better way to accomplish this?
The string of your lambda needs to match a Groovy closure form. For your multiline and multi-argument script you need to wrap some curly braces around it:
withSack(Lambda.biFunction(
"{ x, y -> " +
" intersections = []\n" +
" if (x.isEmpty() || y.isEmpty()) return []\n" +
" i = 0\n" +
" j = 0\n" +
" while (i < x.size() && j < y.size()) {\n" +
" def low = Math.max(x[i][0], y[j][0])\n" +
" def high = Math.min(x[i][1], y[j][1])\n" +
" if (low <= high) intersections.add(Arrays.asList(low, high))\n" +
" if (x[i][1] < y[j][1]) i++; else j++\n" +
" }\n" +
" return intersections\n" +
"}"))
I also converted your Java to Groovy (hopefully correctly) which ends up being a little more succinct but that part should be unnecessary.
I'm trying to do a school quiz again. I'm trying to match if my result is equal to number "x". I wrote a recursive function, I always get the value 0, not the one I used to call the function (such as 153). What should I change ?
public static boolean isArmstrong(int x, Armstrong s) {
while (a != true) {
while (x != 0) {
int number = x / 10;
int remain = x % 10;
s.push(remain);
return isArmstrong(number, s);
}
a = true;
}
if (getResult() == x) {
System.out.println("True , result is : " + getResult());
} else {
System.out.println("False , x is : " + x + " result is : " + getResult());
//x always prints out 0 which ends the while loop.But i need to get the x value when i call the function
}
return true;
}
}
You've supplied incomplete information, no definition for the method getResult() nor for the type Armstrong s, but there are still some issues we can address. First, your boolean method isArmstrong() never returns false, only true, so we can't expect it to detect non Armstrong numbers. Second, you're doing too much in your recursive method, both the test for an Armstrong number and the announcing of the result -- these might best be handled by separate methods.
Below's a rework that changes isArmstrong() from a boolean method to one that returns its calculation as an integer. An input value of zero breaks the recursion causing a result to be returned. We use a separate function to compare the argument to isArmstrong() against the returned value to announce success or failure:
public class Armstrong
{
public static int isArmstrong(int x, int power) {
if (x != 0) {
int quotient = x / 10;
int remainder = x % 10;
return (int)Math.pow(remainder, power) + isArmstrong(quotient, power);
}
return 0;
}
public static void main(String args[]) {
int number = 0, power = 0;
if (args.length > 0) {
try {
power = args[0].length();
number = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument " + args[0] + " must be an integer.");
System.exit(1);
}
}
int result = isArmstrong(number, power);
if (result == number) {
System.out.println("True, result is: " + result);
} else {
System.out.println("False, number is: " + number + " but result is: " + result);
}
}
}
OUTPUT
> java Armstrong 153
True, result is: 153
> java Armstrong 123
False, number is: 123 but result is: 36
> java Armstrong 1634
True, result is: 1634
> java Armstrong 1635
False, number is: 1635 but result is: 2003
>
I'm using an android device to retrieve data from the accelerometer and light sensors. I'm writing the data to an OutputStream which sends the data to an Arduino over Bluetooth. I want to create a string like the one below-
"X Value(Accelerometer), Y Value(Accelerometer),Light-Sensor value"
But the problem is I can't get two value arrays from the same SensorEvent. It only seems to contain accelerometer values. This is what I have till now...
#Override
public void onSensorChanged(SensorEvent event) {
actualTime = System.currentTimeMillis();
if(event.sensor.getType() == Sensor.TYPE_GRAVITY) {
int x = (int) event.values[0];
int y = (int) event.values[1];
String grav = x + "," + y;
if (mConnectedThread != null) {
if(actualTime - lastUpdate > 500) {
mConnectedThread.write(grav.getBytes());
lastUpdate = actualTime;
}
}
}
else if(event.sensor.getType() == Sensor.TYPE_LIGHT) {
actualTime = System.currentTimeMillis();
float value = event.values[0];
if(mConnectedThread != null) {
if(actualTime - lastUpdate > 500) {
String val = "" + value;
mConnectedThread.write("click".getBytes());
lastUpdate = actualTime;
}
}
}
In the If you are just sending the x and y values from your Sensor.TYPE_GRAVITY event.
In the Else you are sending the word "click" encoded as bytes when the Sensor.TYPE_LIGHT event occurs. It does not seem likely that this is what you want
As you are triggering on 2 different events it's difficult to see how you could send all the data at once unless you store events, combine them later and then send.
I need to port an excel spreadsheet that uses the solver plugin to an ASP.NET c# site, I'm using the Solver Foundation 3.1 to no avail.
The equation is iterative, and two conditions need to be met in order to determine the two decision values.
The two decision values on the spreadsheet are set to 1
Ng = 1
Nv = 1
Then the goal is to find the MAX of Formula1 when the following conditions are met:
Decision 1: Formula1 = _na
Decision 2: Formula2 = Formula3
All formulas use Ng and Nv, hitting solve changes Ng and Nv to satisfy each equation, it takes and average of 22 iterations on the spreadsheet.
I've implemented it in c# as follows:
public class FluxSolver
{
public FluxSolver(double _na, double _ygo, double _k, double _alpha, double _inletVoidFraction)
{
var solver = SolverContext.GetContext();
solver.ClearModel();
var model = solver.CreateModel();
var decisionNG = new Decision(Domain.RealNonnegative, "NG");
var decisionNV = new Decision(Domain.RealNonnegative, "NV");
model.AddDecision(decisionNG);
model.AddDecision(decisionNV);
Term formula1 = (_ygo * decisionNG) + ((1 - _ygo) * decisionNV);
model.AddGoal("Goal", GoalKind.Maximize, formula1);
model.AddConstraint("Constraint1", ((_inletVoidFraction / _k) * (1 / decisionNG)) == (_alpha * ((1 / decisionNV) - 1)));
model.AddConstraint("Constraint2", ( _ygo * decisionNG) + ((1 - _ygo) * decisionNV) == _na);
var solution = solver.Solve();
NV = decisionNV.GetDouble();
NG = decisionNG.GetDouble();
Quality = solution.Quality.ToString();
}
public double NG { get; set; }
public double NV { get; set; }
public string Quality { get; set; }
}
I've been at it for 3 days now and still not making any progress, the solver just loads and and disappears, never times out, doesn't return the values etc. Is there something fundamentally wrong in my code?
Any help appreciated!
I am creating a Sudoku Puzzle in asp and I'm having trouble with some classes. When I create a function to display all the numbers in the text box, I get this error: Object reference not set to an instance of an object. I know that it means that my object is null, but here is my code. The line that I am getting the error on is the line that says: stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
private SudokuTextBox stb;
private Puzzle puzzle;
private Box box;
private Number stbNumber;
public void displayAll(object sender,EventArgs e)
{
puzzle = new Puzzle();
for (int i = 0; i < 3; i++)
{
for (int k = 0; k < 3; k++)
{
box = new Box();
for (int m = 0; m < 3; m++)
{
for (int n = 0; n < 3; n++)
{
stbNumber = new Number();
stb = new SudokuTextBox();
stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
stb.setTextBoxValue(stbNumber);
stb.setVisibility(true);
box.setItem(stb, m, n);
}// end forth for
}//end third for
puzzle.setItem(box, i, k);
}//end second for
}//end first for
generateBoxes();
}
I have initialized stbNumber at the very top of my code, and I have made sure that currentSolution is not null or empty. I'm therefore unsure as to what I am doing wrong. I also should mention that I have this exact code elsewhere to generate new puzzles and it works just fine, but this section of code specifically gets called when I click a button.
you essentially have 3 possibilities:
stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
stbNumber could be null
currentSolution could be null
the element you are trying to index could be null--just because currentSolution is not null does not mean the item is at that index is not null--so new one up or take appropriate action
since you new up an instance of stbNumber, it is unlikely to be the culprit (but it could be)
you say you are checking currentSolution is null, I don't see the code for that and from the code you did post it is most likely the culprit here. what you COULD do is add a check for null before you access it, and if your test fails writing an error message somewhere:
stbNumber = new Number();
stb = new SudokuTextBox();
if ( currentSolution != null )
{
// if the item does not exist, new it up
if ( currentSolution[3 * i + m, 3 * k + n] == null ) currentSolution[3 * i + m, 3 * k + n] = new someObject()
stbNumber.setNumber(currentSolution[3 * i + m, 3 * k + n]);
stb.setTextBoxValue(stbNumber);
}
else
{
WriteSomeErrorMessage("currentSolution is null");
}