Springboot- How to pass the score to an entity class - spring-boot

I am trying to create a program that collects the score at the end and assigns it a grade but it is assigning the grade for every score printed. In layman's terms the system should go through each method and deduct points based on whether the condition is met. Its for a website so I would need to display the scores so I need to use an entity class with getters and setters from what I have read. I am quite lost about how to go about this
public class Review {
public static void main(String[] args) { //getWordLength() { // Checking word length. Less than 6 means reviewer can't weigh out positives and negatives
// TODO Auto-generated method stub
int ReviewScore = 30;
String Review = "me I me, pizza Montreal";
String[] words = Review.split("\\s+");
System.out.println("Word Count is: "+words.length);
int wordlength = Integer.valueOf(words.length);
if (wordlength< 6) {
ReviewScore -=4; // deducts 4pts if review less than 6 words
System.out.println("Score is "+ ReviewScore);
}
verbCount( ReviewScore,Review );
}
public static void verbCount (int ReviewScore, String Review) { //Count verbs 'I' or 'me'
for (String s : Review.split ("\\s+") ) { // splits review into separate words
if (s.contains("me" )){ // Checks for 'me' or 'I'
ReviewScore -= 1;
System.out.println("Score is "+ ReviewScore);
// deducts by 2 pts for each time 'I' is mentioned
}
if ( s.contains ("I")) {
ReviewScore -= 1;
System.out.println("Score is "+ ReviewScore); //deducts by 2 pts for each time 'me' is mentioned
}
WordBucket (ReviewScore, s);
}
}
public static void WordBucket ( int ReviewScore, String s) {
for (String word : Analyser.FREQWORDS) {
if(s.contains(word)) {
System.out.println("Score is "+ ReviewScore);
break;
}
else {
ReviewScore -=5;
System.out.println("Score is "+ ReviewScore);
break;
}
}
Grade (ReviewScore) ;
}
public static void Grade (int ReviewScore) {
int Finalscore= ReviewScore;
if (Finalscore >=20 && Finalscore <=25) {
System.out.println ("a");
} else if (Finalscore >=14 && Finalscore <=19) {
System.out.println ("b");
} else if (Finalscore >=7 && Finalscore <=13 ) {
System.out.println ("c");
} else if ( Finalscore <6)
System.out.println ("d");
else {
System.out.println ("an error has occured") ;
}
}
}

I Believe this is the solution for your query. I understand that you want to print/pass the final Score as well as grade to entity class so in this way we can do where
a) instead of passing each and every word to subsequent function, you are passing the String array itself.
b) returning the score value from each functional call so that the corresponding scores can be saved and passed to other function call.
Also try to avoid using system Print out since it is just for printing to console purpose. You need to return the value from each and every call. If you run this program , the output you are going to get is below
Word Count is: 5
Final Score is 18
Final Grade is b
the lines below
int finalScore = verbCount(ReviewScore, words);
String finalGrade = Grade(finalScore);
Can help you pass the finalScore and finalGrade to entity class which needs to consume these values.
Please note I am using the String array ArrayAnlyser here which I believe you are using as an enum as a part of your program.
public class Review {
public static void main(String[] args) {
int ReviewScore = 30;
String Review = "me I me, pizza Montreal";
String[] words = Review.split("\\s+");
System.out.println("Word Count is: " + words.length);
int wordlength = Integer.valueOf(words.length);
if (wordlength < 6) {
ReviewScore -= 4;
}
int finalScore = verbCount(ReviewScore, words);
System.out.println("Final Score is " + finalScore);
String finalGrade = Grade(finalScore);
System.out.println("Final Grade is " + finalGrade);
}
public static int verbCount(int ReviewScore, String[] words) { //Count verbs 'I' or 'me'
for (String s : words) { // splits review into separate words
if (s.contains("me")) { // Checks for 'me' or 'I'
ReviewScore -= 1;
// System.out.println("Score is "+ ReviewScore);
// deducts by 2 pts for each time 'I' is mentioned
}
if (s.contains("I")) {
ReviewScore -= 1;
// System.out.println("Score is "+ ReviewScore); //deducts by 2 pts for each time 'me' is mentioned
}
}
int RevisedScore = WordBucket(ReviewScore, words);
return RevisedScore;
}
public static int WordBucket(int ReviewScore, String[] words) {
String[] ArrayAnlyser = {"me", "I", "pizza", "Montreal"};
boolean flag = false;
for (String word : words) {
flag = false;
for (String analyWord : ArrayAnlyser) {
if (analyWord.contains(word)) {
// System.out.println("Score is "+ ReviewScore);
flag = true;
break;
}
}
if (!flag) {
ReviewScore -= 5;
// System.out.println("Score is "+ ReviewScore);
}
}
return ReviewScore;
// Grade (ReviewScore) ;
}
public static String Grade(int ReviewScore) {
int Finalscore = ReviewScore;
String grade = "";
if (Finalscore >= 20 && Finalscore <= 25) {
// System.out.println ("a");
grade = "a";
} else if (Finalscore >= 14 && Finalscore <= 19) {
grade = "b";
// System.out.println ("b");
} else if (Finalscore >= 7 && Finalscore <= 13) {
grade = "c";
// System.out.println ("c");
} else if (Finalscore < 6) {
grade = "d";
// System.out.println ("d");
} else {
grade = "error occured";
// System.out.println ("an error has occured") ;
}
return grade;
}
}

Related

For Loop Returning A Range

my BlueJ project has 2 classes: StateProvince and Country. Below is the StateProvince class first, then the Country class where I'm at. I'm stuck on a method: "public int howManyHaveThisPopulation(int min, int max)" which takes the population in millions(e.g. 4, 6) and returns how many StateProvinces there are with populations in that range(e.g. 4-6 million, inclusive). I am not able to set it up and return the right answer. I would like help on how I can do this please. With how my method is now, the error message is that I'm missing a return statement. I know my method isn't correct. I have listed the class below and my progress on the method:
public class StateProvince
{
private String name; //e.g. "British Columbia" or "California"
private String capital; //e.g. "Victoria or "Sacramento"
private int populationInMillions; //e.g. 4 or 38
private final static int DEFAULT_POPULATION_MILLIONS = 4;
private final static String DEFAULT_STATE_PROVINCE = "British Columbia";
private final static String DEFAULT_CAPITAL = "Victoria";
public StateProvince()
{
}
/**
* constructor that takes in all 3 parameters and assigns them if they follow the rules:
* name: must be one of the 50 Unites States or 10 Canadian Provinces
* capital: must be the name of the capital city
* populationInMillions: must be between 0 and 38
*/
public StateProvince(String name, String capital, int populationInMillions)
{
if(isValidPopulation(populationInMillions) && (isValidStateProvince(name) &&
(isValidCapitalCity(capital))))
{
this.populationInMillions = populationInMillions;
this.name = name;
this.capital = capital;
}else
{
this.populationInMillions = DEFAULT_POPULATION_MILLIONS; //
this.name = DEFAULT_STATE_PROVINCE; //"British Columbia"
this.capital = DEFAULT_CAPITAL; //"Victoria"
}
}
//StateProvince p1 = new StateProvince("British Columbia", "Victoria", 5);
private boolean isValidStateProvince(String name)
{
String[] provinces = new String[10];
provinces[0] = "British Columbia";
provinces[1] = "Alberta";
provinces[2] = "Saskatchewan";
provinces[3] = "Manitoba";
provinces[4] = "Ontario";
provinces[5] = "Quebec";
provinces[6] = "PEI";
provinces[7] = "Newfoundland";
provinces[8] = "New Brunswick";
provinces[9] = "Nova Scotia";
for(int index = 0; index < provinces.length; index++)
{
if(provinces[index].equalsIgnoreCase(name))
{
return true;
}
index++;
}
return false;
}
private boolean isValidCapitalCity(String capital)
{
String[] capitals = new String[10];
capitals[0] = "Victoria";
capitals[1] = "Edmonton";
capitals[2] = "Regina";
capitals[3] = "Winnipeg";
capitals[4] = "Toronto";
capitals[5] = "Quebec City";
capitals[6] = "Charlottetown";
capitals[7] = "St. John's";
capitals[8] = "Fredericton";
capitals[9] = "Halifax";
for(int index = 0; index < capitals.length; index++)
{
if(capitals[index].equalsIgnoreCase(capital))
{
return true;
}
index++;
}
return false;
}
private boolean isValidPopulation(int populationInMillions)
{
if(populationInMillions >= 4 || populationInMillions <= 38)
{
return true;
}else
{
return false;
}
}
public void setName()
{
this.name = name;
}
public void setCapital()
{
this.capital = capital;
}
public String getName()
{
return name;
}
public String getCapital()
{
return capital;
}
public int getPopulationInMillions()
{
return populationInMillions;
}
public String getDetails()
{
return ("The capital of " + getName() + " (pop. " + populationInMillions + " million) is " + getCapital());
}
}
public class Country
{
private String country;
private StateProvince[] Canada;
public Country()
{
Canada = new StateProvince[10];
Canada[0] = new StateProvince("British Columbia", "Victoria", 4);
Canada[1] = new StateProvince("Alberta", "Edmonton", 3);
Canada[2] = new StateProvince("Saskatchewan", "Regina", 1);
Canada[3] = new StateProvince("Manitoba", "Winnipeg", 1);
Canada[4] = new StateProvince("Ontario", "Toronto", 13);
Canada[5] = new StateProvince("Quebec", "Quebec City", 8);
Canada[6] = new StateProvince("PEI", "Charlottetown", 0);
Canada[7] = new StateProvince("Newfoundland", "St. John's", 0);
Canada[8] = new StateProvince("New Brunswick", "Fredericton", 1);
Canada[9] = new StateProvince("Nova Scotia", "Halifax", 1);
}
public void displayAllStates()
{
for(int index = 0; index < Canada.length; index++)
{
if(Canada[0] != null)
{
System.out.println(Canada[index].getDetails());
}
index++;
}
}
public void addStateProvince(StateProvince stateProvince)
{
if(Canada != null)
{
for(int i = 0; i < Canada.length; i++)
{
if(Canada[i] == null)
{
Canada[i] = stateProvince;
return;
}
}
}
}
public int howManyHaveThisPopulation(int min, int max)
{
for(int i = 0; i < Canada.length; i++)
{
if(i > min && i < max)
{
return Canada[i].getPopulationInMillions();
}
}
}

Unity pause text display in between stanzas wait for user input

I have a script that currently displays dialogue text letter by letter. Currently it rolls through each string of text in my _stanzas array without pausing. I would like to change this script so that it requires the user to press "Z" on their keyboard before the script begins to print the next block of text from _stanzas. I cant seem to figure it out...here is my code.
using UnityEngine;
using System.Collections;
public class Text : MonoBehaviour {
public float LetterPause = 0.1f;
public GameObject text;
public GameObject box;
public GameObject name;
private bool _textFinished;
private int _textIndex;
private string[] _stanzas;
int tracker;
public void Start()
{
if (Application.loadedLevel == 1) {
_stanzas = new [] {
" It’s Terrence’s hat... ",
"He always was one to lose track of the" + "\n" + "material objects in life," + "\n" + "but to hold onto the immaterial forever.",
"I’ll carry it for him" + "\n" + "until I find him. "
};
}
_textFinished = true;
_textIndex = -1;
tracker = _textIndex;
}
public void Update()
{
if (_textFinished)
{
if (_textIndex++ >= (_stanzas.Length - 1))
{
_textFinished = false;
text.SetActive(false);
box.SetActive(false);
name.SetActive(false);
}
if (_textFinished){
SetText(_stanzas[_textIndex]);}
}
}
private IEnumerator TypeText(float waitTime, string text)
{
_textFinished = false;
guiText.text = "";
foreach (var letter in text)
{
guiText.text += letter;
yield return new WaitForSeconds (waitTime);
}
_textFinished = true;
}
private void SetText(string text)
{
StartCoroutine(TypeText(LetterPause, text));
}
}
change
if (_textFinished)
to
if (_textFinished && (Input.GetKeyDown(KeyCode.Z) || _textIndex < 0))

Schedule Crime Case After lunch

Working on Consultant Appointment System. There are many ad-hoc appointments booked online with out specifying the visiting time, but duration. However the consultant will visit customer on Saturday and Sunday between 9 A.M - 1 P.M and 2 P.M to 5 P.M.
The online ad hoc request will specify Reason and Duration. I need to write a code for scheduling these requests, so Consultant can login and see the scheduled items and send it to clients
The problem is if i found any request duration that exceeds the lunch,
i need to ignore in loop and check for next request with small
duration. I am not sure how can i skip for time being and process next
time(After noon schedule).
John Divorce problem 60min
Kumar land issue 100min
Discussion with Ram 60 min
Crime case 45min
Local settlement 15min
In the below code i need to skip Crime case as it exceeds lunch time and schedule Local settlement. Still i need to schedule Crime case after lunch. How can i make this?
public class OnlineRequest
{
public string Reason { get; set; }
public short Duration { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
public static string LUNCH_TIME = "1:00 P.M";
public static string END_OF_DAY = "6:00 P.M";
public static Dictionary<String, List<String>>
GetSchedules(List<OnlineRequest> requests)
{
List<string> schedules = new List<string>();
DateTime visitStartTime = DateTime.MinValue.Date.AddHours(9);
int day = 1;
List<String> eventTimeStr = new List<String>();
Dictionary<String, List<String>> consultantData
= new Dictionary<String, List<String>>();
//Here is the problem
DateTime eventTime = visitStartTime;
foreach (OnlineRequest req in requests)
{
req.StartTime = eventTime;
string flag = getTimeDiff(req);
if (flag.Equals(LUNCH_TIME))
{
eventTimeStr.Add(flag + ": LUNCH");
eventTime = eventTime.AddMinutes(60);
}
else if (flag.Equals(END_OF_DAY))
{
eventTimeStr.Add(flag + ": GO HOME EOD");
consultantData.Add(("Day_" + day), eventTimeStr);
eventTimeStr = new List<String>();
eventTime = visitStartTime;
++day;
}
else
{
eventTimeStr.Add(eventTime.ToString("h:mm tt") + ": " + req.Reason);
eventTime = req.EndTime;
}
}
consultantData.Add(("Day_" + day), eventTimeStr);
return consultantData;
}
private static String getTimeDiff(OnlineRequest req)
{
DateTime startEventTime = req.StartTime;
DateTime finishEventTime = req.StartTime.AddMinutes(req.Duration);
DateTime visitEndTime = DateTime.MinValue.Date.AddHours(17);
DateTime visitLunchStartTime = DateTime.MinValue.Date.AddHours(12);
if (finishEventTime.CompareTo(visitLunchStartTime) == 0 &&
startEventTime.CompareTo(visitLunchStartTime) > 0)
{
return LUNCH_TIME;
}
else if (startEventTime.CompareTo(visitLunchStartTime) == 0 &&
finishEventTime.CompareTo(visitLunchStartTime) > 0)
{
return LUNCH_TIME;
}
else if (startEventTime.CompareTo(visitLunchStartTime) < 0 &&
finishEventTime.CompareTo(visitLunchStartTime) > 0)
{
return LUNCH_TIME;
}
if (visitEndTime.CompareTo(finishEventTime) < 0)
{
return END_OF_DAY;
}
req.EndTime = finishEventTime;
return "";
}
I would do something like this (very crappy pseudo-code):
morning = new Block(3*60, 9);
foreach (OnlineRequest req) {
if (req.Duration < morning.getFreeTime()) {
morning.add(req);
}
}
afternoon = new Block(3*60, 13);
foreach (OnlineRequest req not in morning.requests) {
if (req.Duration < afternoon.getFreeTime()) {
afternoon.add(req);
}
}
foreach (OnlineRequest req in morning.requests ) {
print(morning.getStartTime(req))
}
foreach (OnlineRequest req in afternoon.requests ) {
print(afternoon.getStartTime(req))
}
class Block {
List requests;
int blockSize; //minutes
int blockStartTime;
Block(int bS, int bst ) {
blockSize = bs;
blockStartTime = bst;
}
add(OnlineRequest req) {
requests.add(req);
}
getFreeTime() {
sum = 0;
foreach (OnlineRequest req in requests) {
sum += req.Duration;
}
return blockSize - sum;
}
getStartTime(OnlineRequest or) {
sum = 0;
foreach (OnlineRequest req in requests) {
if ( req = or ) {
return sum + blockStartTime;
}
sum += req.Duration;
}
return null;
}
}

Invoking boolean methods

I'm trying to figure out how to invoke a Boolean method as true or false. Here is what I have thus far:
import java.util.Scanner;
import java.text.DecimalFormat;
public class AssignmentThree {
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the length of Edge 1: ");
double edge1 = scan.nextDouble();
System.out.print("Enter the length of Edge 2: ");
double edge2 = scan.nextDouble();
System.out.print("Enter the length of Edge 3: ");
double edge3 = scan.nextDouble();
scan.close();
DecimalFormat Dec = new DecimalFormat("###,###,##0.00");
if(isValid (edge1, edge2, edge3) == true) {
System.out.println("The area of the triangle is " + Dec.format(area(edge1, edge2, edge3)));
}
if(isValid (edge1, edge2, edge3) == false) {
System.out.println("This is not a valid traingle");
}
}
public static boolean isValid(double side1, double side2, double side3) {
//testing to see if the triangle is real
if(side1+side2>side3 || side1+side3>side2 || side2+side3>side1) {
return true;
} else {
return false;
}
}
I'm not sure if the problem is in my method or not but when the program is ran it simply prints the area, and never if its valid or not.

Lossless hierarchical run length encoding

I want to summarize rather than compress in a similar manner to run length encoding but in a nested sense.
For instance, I want : ABCBCABCBCDEEF to become: (2A(2BC))D(2E)F
I am not concerned that an option is picked between two identical possible nestings E.g.
ABBABBABBABA could be (3ABB)ABA or A(3BBA)BA which are of the same compressed length, despite having different structures.
However I do want the choice to be MOST greedy. For instance:
ABCDABCDCDCDCD would pick (2ABCD)(3CD) - of length six in original symbols which is less than ABCDAB(4CD) which is length 8 in original symbols.
In terms of background I have some repeating patterns that I want to summarize. So that the data is more digestible. I don't want to disrupt the logical order of the data as it is important. but I do want to summarize it , by saying, symbol A times 3 occurrences, followed by symbols XYZ for 20 occurrences etc. and this can be displayed in a nested sense visually.
Welcome ideas.
I'm pretty sure this isn't the best approach, and depending on the length of the patterns, might have a running time and memory usage that won't work, but here's some code.
You can paste the following code into LINQPad and run it, and it should produce the following output:
ABCBCABCBCDEEF = (2A(2BC))D(2E)F
ABBABBABBABA = (3A(2B))ABA
ABCDABCDCDCDCD = (2ABCD)(3CD)
As you can see, the middle example encoded ABB as A(2B) instead of ABB, you would have to make that judgment yourself, if single-symbol sequences like that should be encoded as a repeated symbol or not, or if a specific threshold (like 3 or more) should be used.
Basically, the code runs like this:
For each position in the sequence, try to find the longest match (actually, it doesn't, it takes the first 2+ match it finds, I left the rest as an exercise for you since I have to leave my computer for a few hours now)
It then tries to encode that sequence, the one that repeats, recursively, and spits out a X*seq type of object
If it can't find a repeating sequence, it spits out the single symbol at that location
It then skips what it encoded, and continues from #1
Anyway, here's the code:
void Main()
{
string[] examples = new[]
{
"ABCBCABCBCDEEF",
"ABBABBABBABA",
"ABCDABCDCDCDCD",
};
foreach (string example in examples)
{
StringBuilder sb = new StringBuilder();
foreach (var r in Encode(example))
sb.Append(r.ToString());
Debug.WriteLine(example + " = " + sb.ToString());
}
}
public static IEnumerable<Repeat<T>> Encode<T>(IEnumerable<T> values)
{
return Encode<T>(values, EqualityComparer<T>.Default);
}
public static IEnumerable<Repeat<T>> Encode<T>(IEnumerable<T> values, IEqualityComparer<T> comparer)
{
List<T> sequence = new List<T>(values);
int index = 0;
while (index < sequence.Count)
{
var bestSequence = FindBestSequence<T>(sequence, index, comparer);
if (bestSequence == null || bestSequence.Length < 1)
throw new InvalidOperationException("Unable to find sequence at position " + index);
yield return bestSequence;
index += bestSequence.Length;
}
}
private static Repeat<T> FindBestSequence<T>(IList<T> sequence, int startIndex, IEqualityComparer<T> comparer)
{
int sequenceLength = 1;
while (startIndex + sequenceLength * 2 <= sequence.Count)
{
if (comparer.Equals(sequence[startIndex], sequence[startIndex + sequenceLength]))
{
bool atLeast2Repeats = true;
for (int index = 0; index < sequenceLength; index++)
{
if (!comparer.Equals(sequence[startIndex + index], sequence[startIndex + sequenceLength + index]))
{
atLeast2Repeats = false;
break;
}
}
if (atLeast2Repeats)
{
int count = 2;
while (startIndex + sequenceLength * (count + 1) <= sequence.Count)
{
bool anotherRepeat = true;
for (int index = 0; index < sequenceLength; index++)
{
if (!comparer.Equals(sequence[startIndex + index], sequence[startIndex + sequenceLength * count + index]))
{
anotherRepeat = false;
break;
}
}
if (anotherRepeat)
count++;
else
break;
}
List<T> oneSequence = Enumerable.Range(0, sequenceLength).Select(i => sequence[startIndex + i]).ToList();
var repeatedSequence = Encode<T>(oneSequence, comparer).ToArray();
return new SequenceRepeat<T>(count, repeatedSequence);
}
}
sequenceLength++;
}
// fall back, we could not find anything that repeated at all
return new SingleSymbol<T>(sequence[startIndex]);
}
public abstract class Repeat<T>
{
public int Count { get; private set; }
protected Repeat(int count)
{
Count = count;
}
public abstract int Length
{
get;
}
}
public class SingleSymbol<T> : Repeat<T>
{
public T Value { get; private set; }
public SingleSymbol(T value)
: base(1)
{
Value = value;
}
public override string ToString()
{
return string.Format("{0}", Value);
}
public override int Length
{
get
{
return Count;
}
}
}
public class SequenceRepeat<T> : Repeat<T>
{
public Repeat<T>[] Values { get; private set; }
public SequenceRepeat(int count, Repeat<T>[] values)
: base(count)
{
Values = values;
}
public override string ToString()
{
return string.Format("({0}{1})", Count, string.Join("", Values.Select(v => v.ToString())));
}
public override int Length
{
get
{
int oneLength = 0;
foreach (var value in Values)
oneLength += value.Length;
return Count * oneLength;
}
}
}
public class GroupRepeat<T> : Repeat<T>
{
public Repeat<T> Group { get; private set; }
public GroupRepeat(int count, Repeat<T> group)
: base(count)
{
Group = group;
}
public override string ToString()
{
return string.Format("({0}{1})", Count, Group);
}
public override int Length
{
get
{
return Count * Group.Length;
}
}
}
Looking at the problem theoretically, it seems similar to the problem of finding the smallest context free grammar which generates (only) the string, except in this case the non-terminals can only be used in direct sequence after each other, so e.g.
ABCBCABCBCDEEF
s->ttDuuF
t->Avv
v->BC
u->E
ABABCDABABCD
s->ABtt
t->ABCD
Of course, this depends on how you define "smallest", but if you count terminals on the right side of rules, it should be the same as the "length in original symbols" after doing the nested run-length encoding.
The problem of the smallest grammar is known to be hard, and is a well-studied problem. I don't know how much the "direct sequence" part adds to or subtracts from the complexity.

Resources