Homework assignment with error with sentinel loops - sentinel

Ok, so I am working on this class assignment where I have to write a program that uses a sentinel value controlled loop to input student scores and displays the count of students and the average of all scores when a -1 is entered. A title is to be displayed when the program first begins. Valid score values are from 0 to 100. When a value in excess of 100 is entered, it is not to be included in the total and the number of students is not to be incremented. When a value of -1 is entered, the list is ended and the program displays the number of valid scores entered and the average score. If a -1 is entered as the first input, no error is to be reported and a message is to be displayed that no scores were entered.
Now, I was originally able to get the program to give me an output where it allowed me to enter the grades but what I realized was that when I entered "999" or "-1" the program didn't stop and average the grades I inputted from the keyboard and so I've been trying to fix it and now I'm at a stump and don't have a clue on how to fix it. I'm a beginner at this Java Programming and using NetBeans software. Honestly, I have to constantly look up what the errors mean because I don't have a clue. I could really get some help since my professor had to evacuate last week he hasn't been able to have access to his computers so I'm at this alone.
The errors I'm getting right now are:
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:38: error: unclosed character literal
else (studentCount == '999');{
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:38: error: not a statement
else (studentCount == '999');{
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:38: error: 'else' without 'if'
else (studentCount == '999');{
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:38: error: unclosed character literal
else (studentCount == '999');{
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:40: error: class expected
studentCount = int.next();
C:\Users\sjccuser\Documents\NetBeansProjects\StudentsScoreReport\src\studentsscorereport\StudentsScoreReport.java:40: error: ';' expected
studentCount = int.next();
6 errors
HOW DO I FIX THIS LOL? please help me, I'm so behind in my class because I haven't been able to get this project done. Below is my entire code.
public class StudentsScoreReport {
public static final int SCORE_COUNT = 5;
public static void main(String[] args) {
// Define Constants
double studentCount= 0; //students inital grade
double totalScore = 0; // students grades combined
double averageScore; // average score from the number of students
int scoreCount = 0; // output score from the calculated average score
// create the Scanner object.
Scanner stdin = new Scanner(System.in);
// INPUT: Title at the top of the out
System.out.println ("Kristina Rosado's Students Score Report");
System.out.println ("Enter a students score, 0 - 100, 999 to quit"); //input score from keyboard
// PROCESS: Read the scores for the first city
// NOTE: the program's score starts at 0, but people count from 1
if (studentCount == 0 && totalScore == 0 ){
averageScore = (totalScore / studentCount);
} // users input -1 at the first time
else {
averageScore = totalScore / studentCount;
System.out.printf ("%d student scores were entered\n", studentCount);
System.out.printf ("\nThe average of score of %d students is %.2f", studentCount, averageScore);
else (studentCount == '999');{
System.out.println ("Thank you for your entries");
studentCount = int.next();
}
}
while (studentCount != -1){
if (studentCount < -1) {
System.out.print("Please try again");
System.out.printf ("Enter the score for the next student #%d: ", scoreCount+1);
// input the next score
studentCount = stdin.nextDouble();
} else if (studentCount > 100) {
System.out.print("Please try again");
System.out.printf ("Enter the score for the next student #%d: ", scoreCount+1);
// input the next score
studentCount = stdin.nextDouble();
} // end of for loop
// end of for loop
}
System.out.println ("Illegal entry for score");{
System.out.println("There is no student score entered ");
averageScore = totalScore / scoreCount;
System.out.printf("\nThe average score for %d students is %8.2f\n", scoreCount, averageScore);
}
}// end of public static void main(String[] args);
} // end of public class StudentsScoreReport;enter code here

Can I just ask what language this is in. I can see multiple syntax errors but I just want to put it through an IDE first.

Related

Expert Advisor timefilter doesn't work (mql5)?

I can't figure out why my timefilter doesn't work. Let's say I would like to only enter to positions between 7:35-11:30 and 14:30-22:30 and I don't want to enter a position on Friday.
The time filter only works when I create a simple EA with only a trade.Buy function and no other conditions.
The more complex EA should only enter a position when the vaule of the Supertrend indicator becomes higher/lower than the price and only in the given time intervals.
It should close the position at the next sell/buy signal (if it was a buy position then the position should be closed at the next 'sell' signal' ). When closing positions the time interval shouldn't matter it should only mater when entering a new position.
The 'TradingIsAllowed' variable should be 'true' when the current time is in the allowed time intervals but it always returns false for some reason and I can't figure out why.
It works perfectly fine when I don't use the supertrend and close trades with a simple tp/sl.
Could you please help me?
#include <Trade\Trade.mqh>
CTrade trade;
ulong posTicket;
input double Lots=0.1;
int stHandle;
int totalBars;
input ENUM_TIMEFRAMES Timeframe = PERIOD_CURRENT;
input int Periods =12;
input double Multiplier = 3.0;
//for the timefilter
input string StartTradingTime="07:35";
input string StopTradingTime="11:30";
input string StartTradingTime2="14:35";
input string StopTradingTime2="22:30";
string CurrentTime;
bool TradingIsAllowed=false;
bool TradingIsAllowed2=false;
int OnInit(){
totalBars=iBars(_Symbol,Timeframe);
stHandle = iCustom(_Symbol, Timeframe, "Supertrend.ex5", Periods, Multiplier);
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason){
}
void OnTick(){
//for the timefilter
datetime LocalTime=TimeLocal();
string HoursAndMinutes=TimeToString(LocalTime,TIME_MINUTES);
string YearAndDate=TimeToString(LocalTime, TIME_DATE);
MqlDateTime DateTimeStructure;
TimeToStruct(LocalTime, DateTimeStructure);
int DayOfWeek=DateTimeStructure.day_of_week;
datetime time = TimeLocal();
CurrentTime=TimeToString(time,TIME_MINUTES);
//this should only run if there is a new bar
int bars=iBars(_Symbol, Timeframe);
if(totalBars !=bars){
totalBars=bars;
double st[];
CopyBuffer(stHandle,0,0,3,st);
double close1 = iClose(_Symbol, Timeframe, 1);
double close2 = iClose(_Symbol, Timeframe, 2);
//BUY CONDITION
if(close1 > st[1] && close2 < st[0]){
if(posTicket > 0 ){
if(PositionSelectByTicket(posTicket)){
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL){
if (trade.PositionClose(posTicket)){
Print(__FUNCTION__," > Pos ", posTicket, "was closed..");
}
}
}
}
if(CheckTradingTime()==true || CheckTradingTime2()==true){
if(PositionsTotal()==0 && DayOfWeek!=5){
Print(__FUNCTION__, " > BOUGHT");
if(trade.Buy(Lots, _Symbol)){
if(trade.ResultRetcode() == TRADE_RETCODE_DONE){
posTicket= trade.ResultOrder();
}
}
}
}
}
else if(close1 < st[1] && close2 > st[0]){
if(posTicket > 0 ){
if(PositionSelectByTicket(posTicket)){
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY){
if (trade.PositionClose(posTicket)) {
Print(__FUNCTION__," > Pos ", posTicket, "was closed..");
}
}
}
}
if(CheckTradingTime()==true || CheckTradingTime2()==true){
if(PositionsTotal()==0 && DayOfWeek!=5){
Print(__FUNCTION__, " > SOLD");
if(trade.Sell(Lots, _Symbol)){
if(trade.ResultRetcode() == TRADE_RETCODE_DONE){
posTicket= trade.ResultOrder();
}
}
}
}
}
}
Comment (
"TradingIsAllowed", TradingIsAllowed, TradingIsAllowed2, "\n", //TradingIsAllowed always returns false..
"Current Time=", CurrentTime,"\n",
"Trading Session1=", StartTradingTime,"-" ,StopTradingTime, "\n",
"Trading Session2=", StartTradingTime2, "-", StopTradingTime2,"\n",
"Day of Week", DayOfWeek
);
}
//trading session 1
bool CheckTradingTime()
{
if(StringSubstr(CurrentTime,0,5)==StartTradingTime)
TradingIsAllowed=true;
if(StringSubstr(CurrentTime,0,5)==StopTradingTime)
TradingIsAllowed=false;
return TradingIsAllowed;
}
//trading session 2
bool CheckTradingTime2()
{
if(StringSubstr(CurrentTime,0,5)==StartTradingTime2)
TradingIsAllowed2=true;
if(StringSubstr(CurrentTime,0,5)==StopTradingTime2)
TradingIsAllowed2=false;
return TradingIsAllowed2;
}
you dont neet to write "(StringSubstr(CurrentTime,0,5)==StartTradingTime)"
you can write only "CurrentTime == StartTradingTime"

Filtering return on serial port

I have a CO2 sensor on my Arduino Mega and sometimes randomly when I'm reading the CO2 measurement, the sensor will return a "?". The question mark causes my program to crash and return "input string was not in a correct format".
I haven't tried anything because I don't know what approach would be the best for this. The CO2 sensor returns the measurement in the form of "Z 00000" but when this question mark appears it shows that all that returned was a "\n". Currently, I have the program just reading the 5 digits after the Z.
if (returnString != "")
{
val = Convert.ToDouble(returnString.Substring(returnString.LastIndexOf('Z')+ 1));
}
What I expect to return is the digits after Z which works but every so often I will get a random line return which crashes everything.
According to the C# documentation the ToDouble method throws FormatException whenever the input string is invalid. You should catch the exception to avoid further issues.
try {
val = Convert.ToDouble(returnString.Substring(returnString.LastIndexOf('Z')+ 1));
}
catch(FormatException e) {
//If you want to do anything in case of an error
//Otherwise you can leave it blank
}
Also I'd recommend using some sort of statemachine for parsing the data in your case, that could discard all invalid characters. Something like this:
bool z_received = false;
int digits = 0;
int value = 0;
//Called whenever you receive a byte from the serial port
void onCharacter(char input) {
if(input == 'Z') {
z_received = true;
}
else if(z_received && input <= '9' && input >= '0') {
value *= 10;
value += (input - '0');
digits++;
if(digits == 5) {
onData(value);
value = 0;
z_received = false;
digits = 0;
}
}
else {
value = 0;
z_received = false;
digits = 0;
}
}
void onData(int data) {
//do something with the data
}
This is just a mock-up, should work in your case if you can direct the COM port's byte stream into the onCharacter function.

Distance edit array output

I am doing an edit distance with the user input. I am storing my values in array. then the edit distance will compare the user input with my array of strings. I am doing a loop that if the edit distance is more than 2 it will display invalid else valid.
The only problem I've got is that although the program is working out fine, the output is the result of all the '28' strings that I have in my array. I would like to display only invalid or valid once.
Test is my array of strings and user is - String user - the user input.
void testingLD()
{
for (int i=0; i<test.length; i++)
{
if(getLevenshteinDistance(test[i],user) > 2)
{
println ("Invalid re-input");
}
else
{
println ("Valid");
}
}
}
You have your print line functions inside your loop so they get printed once per iteration.
Try this.
void testingLD()
{
boolean isValid = true; // assume true, check each and update
// begin loop
for (int i=0; i<test.length; i++)
{
if(getLevenshteinDistance(test[i],user) > 2)
{
isValid = false;
break; // don't need to test the rest of the loop if we already found a false
}
}
// end loop
if(isValid){
println("Valid");
}else{
println("Invalid re-input");
}
}
Similarly you could count the number of valid int validCount = 0; validCount++ and then display stats about how many were valid, the percentage etc. Or keep an array of the invalid strings and display those as the ones that fail etc!
Wrap up:
When you want to check an entire collection or array for some condition and output one answer make sure to have your output outside of the loop!

C++ srand function looping

I have the following method as part of a password generating program to generate a random password which is then validated.
My problem is that the srand function never meets the validation requirements and keeps looping back to create a new password.
Im posting the code below to ask if anyone has a more efficient way to create the random password so that it will meet validation requirements instead of looping back continously.Thanks.
static bool verifyThat(bool condition, const char* error) {
if(!condition) printf("%s", error);
return !condition;
}
//method to generate a random password for user following password guidelines.
void generatePass()
{
FILE *fptr;//file pointer
int iChar,iUpper,iLower,iSymbol,iNumber,iTotal;
printf("\n\n\t\tGenerate Password selected ");
get_user_password:
printf("\n\n\t\tPassword creation in progress... ");
int i,iResult,iCount;
char password[10 + 1];
char strLower[59+1] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRTUVWXYZ!£$%^&*";
srand(time (0));
for(i = 0; i < 10;i++)
{
password[i] = strLower[(rand() % 52)];
}
password[i] = '\0';
iChar = countLetters(password,&iUpper,&iLower,&iSymbol,&iNumber,&iTotal);
//folowing statements used to validate password
iChar = countLetters(password,&iUpper,&iLower,&iSymbol,&iNumber,&iTotal);
iUpper = countLetters(password,&iUpper,&iLower,&iSymbol,&iNumber,&iTotal);
iLower =countLetters(password,&iUpper,&iLower,&iSymbol,&iNumber,&iTotal);
iSymbol =countLetters(password,&iUpper,&iLower,&iSymbol,&iNumber,&iTotal);
iNumber = countLetters(password,&iUpper,&iLower,&iSymbol,&iNumber,&iTotal);
iTotal = countLetters(password,&iUpper,&iLower,&iSymbol,&iNumber,&iTotal);
if(verifyThat(iUpper >= 2, "Not enough uppercase letters!!!\n")
|| verifyThat(iLower >= 2, "Not enough lowercase letters!!!\n")
|| verifyThat(iSymbol >= 1, "Not enough symbols!!!\n")
|| verifyThat(iNumber >= 2, "Not enough numbers!!!\n")
|| verifyThat(iTotal >= 9, "Not enough characters!!!\n")
|| verifyThat(iTotal <= 15, "Too many characters!!!\n"))
goto get_user_password;
iResult = checkWordInFile("dictionary.txt", password);
if(verifyThat(iResult != gC_FOUND, "Password contains small common 3 letter word/s."))
goto get_user_password;
iResult = checkWordInFile("passHistory.txt",password);
if(verifyThat(iResult != gC_FOUND, "Password contains previously used password."))
goto get_user_password;
printf("\n\n\n Your new password is verified ");
printf(password);
//writing password to passHistroy file.
fptr = fopen("passHistory.txt", "w"); // create or open the file
for( iCount = 0; iCount < 8; iCount++)
{
fprintf(fptr, "%s\n", password[iCount]);
}
fclose(fptr);
printf("\n\n\n");
system("pause");
}//end of generatePass method.
I looked at your code at glance and I think I have found the reasons inspite of which validation requirements aren`t meet.
I suggest you to pay attention to the following parts of your code:
1) char strLower[59+1] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRTUVWXYZ!£$%^&*";
here you should add numbers 0..9, this is one of the reasons why requirements could not be met, because how number can be picked if it isn`t in the set of numbers from which you pick?!
replace it for ex. with:
char strLower[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRTUVWXYZ!£$%^&*0123456789";
2) password[i] = strLower[(rand() % 52)]; - and in this part of the code, replace 52 with total number of symbols in string from which you randomly pick numbers.
I recommend you to replace it with the following code:
password[i] = strLower[(rand() % (sizeof(strLower) / sizeof(char) - 1))];
you could alter your algorithm.
choose at random a number of Upper characeters that is above 2.
choose at random a number of Lower character that is above 2.
choose at random a number of Sybmol character that is above 1.
choose at random a number of Number characters that is above 2.
and then recompose your password with the random items, re-ordered at random. Fill with whatever character you want to pas the verifyThat predicates: >=9 and <= 15.
And please: don't use goto. Make function calls instead.

Trouble With Java Program using parameters and methods [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am stuck here with one programming code: Here are the instructions: http://my.fit.edu/~akhademzadeh2011/courses/cse1001/f2012/ass/ass04.pdf
And, this is my code:
import java.util.*;
public class PantherSolver {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String input;
String p = "0| |";
int signcontrol = 1;
input = GUI(p);
int firstnumber = inputmethod(input);
int firstsign = sign(input,signcontrol);
String secondp = p1(firstsign,firstnumber,p);
String input2 = GUI(secondp);
}
public static String p1(int firstsign,int firstnumber, String p) {
if (firstsign>0) {
p = "0| "+ firstnumber +" |";
}
else {
p = "0| -"+ firstnumber +" |";
}
return p;
}
public static String GUI1(String secondp) {
Scanner kb = new Scanner(System.in);
String newinput = kb.nextLine();
System.out.println(" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
System.out.println(" ========================================");
System.out.println(secondp);
System.out.println("1|--------------------------------------|");
System.out.println("2| OFF +/- AC |");
System.out.println("3| 1 2 3 4 5 , |");
System.out.println("4| 6 7 8 9 0 SOLVE |");
System.out.println(" ========================================");
System.out.println(" Key: " + newinput +"");
return newinput;
}
public static String GUI(String p) {
Scanner kb = new Scanner(System.in);
System.out.println(" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
System.out.println(" ========================================");
System.out.println(p);
System.out.println("1|--------------------------------------|");
System.out.println("2| OFF +/- AC |");
System.out.println("3| 1 2 3 4 5 , |");
System.out.println("4| 6 7 8 9 0 SOLVE |");
System.out.println(" ========================================");
String input1=kb.nextLine();
System.out.println(" Key: " + input1 +"");
return input1;
}
public static int inputmethod(String input) {
Scanner kb = new Scanner(System.in);
int a = 0;
if (input.length()==2) {
if((input.charAt(0)=='0')||(input.charAt(0)=='1')) {
;
}
else if((input.charAt(0)=='2') && !((input.charAt(1)==('0'))||(input.charAt(1)==('1'))||(input.charAt(1)==('2'))||(input.charAt(1)==('S'))||(input.charAt(1)==('T'))||(input.charAt(1)==('U'))||(input.charAt(1)==('V'))||(input.charAt(1)==('W'))||(input.charAt(1)==('X'))||(input.charAt(1)==('Y'))||(input.charAt(1)==('Z')))) {
;
}
else if((input.charAt(0)=='3') && !((input.charAt(1)==('0'))||(input.charAt(1)==('2'))||(input.charAt(1)==('4'))||(input.charAt(1)==('6'))||(input.charAt(1)==('8'))||(input.charAt(1)==('T'))||(input.charAt(1)==('U')))) {
;
}
else if((input.charAt(0)=='4') && !((input.charAt(1)==('0'))||(input.charAt(1)==('2'))||(input.charAt(1)==('4'))||(input.charAt(1)==('6'))||(input.charAt(1)==('8'))||(input.charAt(1)==('U'))||(input.charAt(1)==('V'))||(input.charAt(1)==('W'))||(input.charAt(1)==('X'))||(input.charAt(1)==('Y'))||(input.charAt(1)==('Z')))) {
;
}
else if ((input.equals("20")) || (input.equals("21")) ||(input.equals("22")) ||(input.equals("2S")) ||(input.equals("2T")) ||(input.equals("2U")) ||(input.equals("2V")) ||(input.equals("2X")) ||(input.equals("2Y")) ||(input.equals("2Z")) ||(input.equals("30")) ||(input.equals("32")) ||(input.equals("34")) ||(input.equals("36")) ||(input.equals("38")) ||(input.equals("40")) ||(input.equals("42")) ||(input.equals("44")) ||(input.equals("46")) ||(input.equals("48")) ||(input.equals("4U")) ||(input.equals("4V")) ||(input.equals("4W")) ||(input.equals("4X")) ||(input.equals("4Y")) ||(input.equals("4Z"))) {
switch(input) {
case "20":
case "21":
case "22":
OFF();
break;
case "2X":
case "2Y":
case "2Z":
main(null);
break;
case "30":
a = 1;
break;
case "32":
a = 2;
break;
case "34":
a = 3;
break;
case "36":
a = 4;
break;
case "38":
a = 5;
break;
case "40":
a = 6;
break;
case "42":
a = 7;
break;
case "44":
a = 8;
break;
case "46":
a = 9;
break;
case "48":
a = 0;
break;
case "4U":
case "4V":
case "4W":
case "4X":
case "4Y":
case "4Z":
solve();
break;
}
}
else {
System.out.println("Invalid key.");
System.out.println(" Key: " + input+"");
inputmethod(input);
}
}
else {
System.out.println("Invalid key.");
System.out.println(" Key: " + input +"");
inputmethod(input);
}
return a;
}
public static int sign (String input, int signcontrol) {
int sign1 = signcontrol;
if ((input.equals("2S")) ||(input.equals("2T")) ||(input.equals("2U")) ||(input.equals("2V"))) {
sign1 = sign1 * -1;
}
else {
sign1=1;
}
return sign1;
}
public static void OFF() {
System.exit(0);
}
public static void solve() {
}
}
Where do I go from here? I'm stuck in many places. Can someone guide me? First, I'm having problems with the methods. I used a couple of methods to display the "Panther Solver" and get the input.
The assignment asks to display the "Panther Solve", then the user picks what digits he/she wants. IE "32" means 2. This is very tricky though. If the user selects the +/- sign before a digit, it changes the value that he/she is about the input to a negative. It however does NOT display the negative sign right away, but only after he/she selects the digits.
Each time you select the digit and press enter, the screen pretty much reloads itself, and in the answer key, it displays what you typed. In the "0", row, it also displays what you just selected.
If you select the +/- sign after a digit is selected, nothing will happen. If you select any valid key that does not correlate to an input, nothing should happen. Just like the quadratic equation, with a,b,c, you type in your first response (a), then input comma, then go to b, then comma, then c, then solve. Each time you input, the input is evaluated.
In the input, all letters must be capitalized, if required, or else you would return and "Invalid Key". Also, for the equation, if a=0, return "Error".
I also have to formulate a solution for imaginary numbers, using i.
I am stuck in all parts. My questions are, where do I go from here in my code.
My first problem is getting the "Panther Solver" to display first, then accept the input. The next one is evaluated the negative/positive sign, and if it comes after or before the number. If it comes after, do nothing. If before, change the value to negative.
The other one is trying to make a loop for all of this in the main statement. Because for "a" in the quadratic equation, the user could want to enter "100". So I have to loop that.
Last, on the "0" row, I have to display the previous user input, just like an actual calculator. I'm having trouble getting that, and making it fit. For example, "a" starts at two spaces from the enter. Obviously as much input is entered, "a" moves to the left.
Thanks
Like all beginners, you're making the problem too difficult by failing to decompose it into small enough chunks.
Forget about user input and interfaces. Get the base solver algorithm working with hard wired inputs that you know the answer to. Write it, test it, and put it aside. Then start developing another class that deals only with getting input values and passing them to the class that actually does the work.
When you find yourself overwhelmed by too much detail, simplify the problem into smaller parts that you can deal with. Then knit them together to solve your larger problem.
It's call decomposition. It's the basis for all problem solving, especially programming and computer science.
For goodness' sake, it's solving a quadratic equation. Panther? Unnecessarily confusing.
Don't be fooled by the name. Forget about all that fancy output and get the base solver working. There are special cases you'll need to concern yourself with:
Two real roots.
One zero root, one real root.
Two complex conjugate roots.

Resources