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;
}
}
It's the first time I'm doing this so I didn't want to be lengthy. I'm building a cross reference from reading a java program. I'm to exclude java keywords, commented words and words in quotations. I got through with excluding the java keywords and the commented words but I'm having problems excluding those in quotes.
public class CrossReference {
static Scanner in;
static PrintWriter out;
static int currentLine = 0;
public static void main(String[] args) throws IOException {
in = new Scanner (new FileReader("keywords.txt"));
out = new PrintWriter (new FileWriter("crossreference.out"));
LinkedList keywords = new LinkedList();
while (in.hasNextLine()) {
String word = in.nextLine();
keywords.addTail(new NodeData(word));
}
in = new Scanner (new FileReader("program.txt"));
BinaryTree bst = new BinaryTree();
while(in.hasNextLine()){
String line = in.nextLine();
out.printf("%3d. %s\n", ++currentLine,line);
getWordsOnLine(line,bst,keywords);
}
out.printf("\nWords LineNumber\n\n");
bst.inOrder();
out.close();
}
public static void getWordsOnLine(String inputLine, BinaryTree bst, LinkedList keywords){
Scanner inLine = new Scanner(inputLine);
inLine.useDelimiter("[^a-zA-Z//\"*]+");
boolean b = true;
while(inLine.hasNext() && b){
String word = inLine.next().toLowerCase();
if (word.contains("/") || word.contains("\"") || word.contains("*")) {
b = false;
} //this works for the commented words but not so well for the ones in quotes as it also excludes words after those in quotes
else {
boolean key = false;
Node curr = keywords.head;
while (curr != null) {
if (curr.data.str.equals(word)) key = true;
curr = curr.next;
}
if (key == false) {
TreeNode node = bst.findOrInsert(new TreeNodeData(word));
ListNode p = new ListNode(currentLine);
p.next = node.data.firstLine;
node.data.firstLine = p;
}
}
}
}
}
Split your string by space into an array.
Iterate through the array, checking which elements start with quotes and are words
Sum it
So the code would look like:
public class HelloWorld
{
public static void main(String[] args)
{
String a = "COPY PASTE ORIGINAL HERE";
String[] arr = a.split(" ");
int count = 0;
for(String each: arr){
if(each.charAt(0) != '\"' && each.charAt(0) < '0' || each.charAt(0) > '9'){
count++;
}
}
System.out.println("words="+count);
}
}
(source, destination) and it's type (tree, back, forward, cross)?
Here you go. Code in Java
import java.util.ArrayList;
import java.util.List;
class Node {
public String name;
public List<Node> connections = new ArrayList<>();
boolean visited = false;
Node(String name) {
this.name = name;
}
}
class DFS {
// Main part.
public static void search(Node root) {
if (root == null) {
return;
}
root.visited = true;
for (Node node : root.connections) {
if (!node.visited) {
// Print result.
System.out.println(root.name + "->" + node.name);
search(node);
}
}
}
}
public class App {
public static void main(String[] args) {
Node a = new Node("a");
Node b = new Node("b");
Node c = new Node("c");
Node d = new Node("d");
Node e = new Node("e");
a.connections.add(b);
b.connections.add(a);
b.connections.add(c);
b.connections.add(d);
c.connections.add(b);
c.connections.add(d);
d.connections.add(b);
d.connections.add(c);
d.connections.add(e);
DFS.search(d);
}
}
Nice question.
This is the solution based on the source you posted as comment.
IMPORTANT: There is an error on the start/end table, third row third column should be "end[u] < end[v]" instead of "end[u] > end[v]"
void main(G, s){
for each node v in G{
explored[v]=false
parent[v]=null
start[v]=end[v]=null
}
Global clock = 0
DFS(G, s, s)
}
void DFS(G, s, parent){
explored[s] = true;
parent[s] = parent
start[s]=clock
clock++
for each u=(s,v){
if(explored[v] == false){
DFS(G, v)
}
print (s + "-->" + v +"type: " + getType(s,v))
}
end[s]=clock
clock++
}
String getType(s, v){
if(start[s]<start[v]){
if(end[s]>end[v]) return "Tree edge"
else return "Forward edge"
else{
if(end[s]<end[v]) return "Back edge"
else return "Cross edge"
}
}
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))
I'm making a program in java that essentially knows a variety of ocean animals, asks the user to think of an animal, and then asks the user questions until it is ready to make a guess. I used a binary tree to do this. here is my code as of right now:
import java.util.Scanner;
public class TwentyQuestions
{
private static Scanner stdin = new Scanner(System.in);
public static void main(String[ ] args)
{
BTNode<String> root;
instruct( );
root = beginningTree( );
do
play(root);
while (query("Shall we play again?"));
System.out.println("Thanks for teaching me a thing or two.");
System.out.println ("Here is the tree:");
root.print(1);
}
public static void instruct( )
{
System.out.println("Please think of an ocean animal.");
System.out.println("I will ask some yes/no questions to try to figure out which animal you're thinking of.");
}
public static void play(BTNode<String> current)
{
while (!current.isLeaf( ))
{
if (query(current.getData( )))
current = current.getLeft( );
else
current = current.getRight( );
}
System.out.print("My guess is " + current.getData( ) + ". ");
if (!query("Am I right?"))
learn(current);
else
System.out.println("I knew it all along!");
}
public static BTNode<String> beginningTree( )
{
BTNode<String> root;
BTNode<String> child;
BTNode<String> child1;
BTNode<String> child2;
BTNode<String> child3;
BTNode<String> child4;
BTNode<String> child5;
BTNode<String> child6;
BTNode<String> child7;
BTNode<String> child8;
BTNode<String> child9;
BTNode<String> child10;
BTNode<String> child11;
BTNode<String> child12;
BTNode<String> child13;
BTNode<String> child14;
final String ROOT_QUESTION = "Is it a mammal?";
final String LEFT_QUESTION = "Is it able to move on land?";
final String LEFT_QUESTION2 = "Is it a solitary animal?";
final String RIGHT_QUESTION2 = "Is it larger than a truck?";
final String RIGHT_QUESTION3 = "Does it have tusks?";
final String RIGHT_QUESTION = "Does it have any limbs/tentacles?";
final String LEFT_QUESTION4 = "Does it have more than four limbs/tentacles?";
final String LEFT_QUESTION5 = "Does it have an exoskeleton?";
final String LEFT_QUESTION6 = "Does it have claws?";
final String LEFT_QUESTION7 = "Does it have a long tail?";
final String RIGHT_QUESTION7 = "Does it have 8 arms?";
final String RIGHT_QUESTION5 = "Does it have a shell?";
final String RIGHT_QUESTION4 = "Can it sting?";
final String LEFT_QUESTION8 = "Is it long and snakelike?";
final String RIGHT_QUESTION8 = "Is it generally smaller than a car?";
final String ANIMAL1 = "Seal";
final String ANIMAL2 = "Sea Lion";
final String ANIMAL3 = "Walrus";
final String ANIMAL4 = "Whale";
final String ANIMAL5 = "Dolphin";
final String ANIMAL6 = "Shrimp";
final String ANIMAL7 = "Lobster";
final String ANIMAL8 = "Crab";
final String ANIMAL9 = "Jellyfish";
final String ANIMAL10 = "Octopus";
final String ANIMAL11 = "Squid";
final String ANIMAL12 = "Turtle";
final String ANIMAL13 = "Alligator";
final String ANIMAL14 = "Eel";
final String ANIMAL15 = "Stingray";
final String ANIMAL16 = "Shark";
final String ANIMAL17 = "Fish";
// Create the root node with the question “Are you a mammal?”
root = new BTNode<String>(ROOT_QUESTION, null, null);
child = new BTNode<String>(LEFT_QUESTION, child2, child14);
root.setLeft(child);
child2 = new BTNode<String>(LEFT_QUESTION2,null,child3);
child2.setLeft(new BTNode<String>(ANIMAL1, null, null));
child.setLeft(child2);
child14 = new BTNode<String>(RIGHT_QUESTION2,null,null);
child14.setLeft(new BTNode<String>(ANIMAL4,null,null));
child14.setRight(new BTNode<String>(ANIMAL5,null,null));
child.setRight(child14);
child3 = new BTNode<String>(RIGHT_QUESTION3, null, null);
child3.setLeft(new BTNode<String>(ANIMAL3, null, null));
child3.setRight(new BTNode<String>(ANIMAL2, null, null));
child.setRight(child3);
child1 = new BTNode<String>(RIGHT_QUESTION, child4, child8);
root.setRight(child1);
child4 = new BTNode<String>(LEFT_QUESTION4,child5,child10);
child1.setLeft(child4);
child5 = new BTNode<String>(LEFT_QUESTION5,child6,child8);
child4.setLeft(child5);
child6 = new BTNode<String>(LEFT_QUESTION6,child7, null);
child6.setRight(new BTNode<String>(ANIMAL6,null,null));
child5.setLeft(child6);
child7 = new BTNode<String>(LEFT_QUESTION7, null, null);
child7.setLeft(new BTNode<String>(ANIMAL7,null,null));
child7.setRight(new BTNode<String>(ANIMAL8,null,null));
child6.setLeft(child7);
child8 = new BTNode<String>(RIGHT_QUESTION4,null,child9);
child8.setLeft(new BTNode<String>(ANIMAL9,null,null));
child5.setRight(child8);
child9 = new BTNode<String>(RIGHT_QUESTION7,null,null);
child9.setLeft(new BTNode<String>(ANIMAL10,null,null));
child9.setRight(new BTNode<String>(ANIMAL11,null,null));
child8.setRight(child9);
child10 = new BTNode<String>(RIGHT_QUESTION5,null,null);
child10.setLeft(new BTNode<String>(ANIMAL12,null,null));
child10.setRight(new BTNode<String>(ANIMAL13,null,null));
child4.setRight(child10);
child11 = new BTNode<String>(RIGHT_QUESTION4,child12,child13);
child1.setRight(child11);
child12 = new BTNode<String>(LEFT_QUESTION8,null,null);
child12.setLeft(new BTNode<String>(ANIMAL14,null,null));
child12.setRight(new BTNode<String>(ANIMAL15,null,null));
child11.setLeft(child12);
child13 = new BTNode<String>(RIGHT_QUESTION8,null,null);
child13.setLeft(new BTNode<String>(ANIMAL17,null,null));
child13.setRight(new BTNode<String>(ANIMAL16,null,null));
child11.setRight(child13);
return root;
}
public static void learn(BTNode<String> current)
{
String guessAnimal; // The animal that was just guessed
String correctAnimal; // The animal that the user was thinking of
String newQuestion; // A question to distinguish the two animals
// Set Strings for the guessed animal, correct animal and a new question.
guessAnimal = current.getData( );
System.out.println("I give up. What are you? ");
correctAnimal = stdin.nextLine( );
System.out.println("Please type a yes/no question that will distinguish a");
System.out.println(correctAnimal + " from a " + guessAnimal + ".");
newQuestion = stdin.nextLine( );
// Put the new question in the current node, and add two new children.
current.setData(newQuestion);
System.out.println("As a " + correctAnimal + ", " + newQuestion);
if (query("Please answer"))
{
current.setLeft(new BTNode<String>(correctAnimal, null, null));
current.setRight(new BTNode<String>(guessAnimal, null, null));
}
else
{
current.setLeft(new BTNode<String>(guessAnimal, null, null));
current.setRight(new BTNode<String>(correctAnimal, null, null));
}
}
public static boolean query(String prompt)
{
String answer;
System.out.print(prompt + " [Y or N]: ");
answer = stdin.nextLine( ).toUpperCase( );
while (!answer.startsWith("Y") && !answer.startsWith("N"))
{
System.out.print("Invalid response. Please type Y or N: ");
answer = stdin.nextLine( ).toUpperCase( );
}
return answer.startsWith("Y");
}
}
The error that keeps coming up is that the "variable child(+whatever number) may have not been inititalized." how do I fix this?
Oh, and here is the code for the BTNode:
public class BTNode<E>
{
private E data;
private BTNode<E> left, right;
public BTNode(E initialData, BTNode<E> initialLeft, BTNode<E> initialRight)
{
data = initialData;
left = initialLeft;
right = initialRight;
}
public E getData( )
{
return data;
}
public BTNode<E> getLeft( )
{
return left;
}
public E getLeftmostData( )
{
if (left == null)
return data;
else
return left.getLeftmostData( );
}
public BTNode<E> getRight( )
{
return right;
}
public E getRightmostData( )
{
if (left == null)
return data;
else
return left.getRightmostData( );
}
public void inorderPrint( )
{
if (left != null)
left.inorderPrint( );
System.out.println(data);
if (right != null)
right.inorderPrint( );
}
public boolean isLeaf( )
{
return (left == null) && (right == null);
}
public void preorderPrint( )
{
System.out.println(data);
if (left != null)
left.preorderPrint( );
if (right != null)
right.preorderPrint( );
}
public void postorderPrint( )
{
if (left != null)
left.postorderPrint( );
if (right != null)
right.postorderPrint( );
System.out.println(data);
}
public void print(int depth)
{
int i;
// Print the indentation and the data from the current node:
for (i = 1; i <= depth; i++)
System.out.print(" ");
System.out.println(data);
if (left != null)
left.print(depth+1);
else if (right != null)
{
for (i = 1; i <= depth+1; i++)
System.out.print(" ");
System.out.println("--");
}
if (right != null)
right.print(depth+1);
else if (left != null)
{
for (i = 1; i <= depth+1; i++)
System.out.print(" ");
System.out.println("--");
}
}
public BTNode<E> removeLeftmost( )
{
if (left == null)
return right;
else
{
left = left.removeLeftmost( );
return this;
}
}
public BTNode<E> removeRightmost( )
{
if (right == null)
return left;
else
{
right = right.removeRightmost( );
return this;
}
}
public void setData(E newData)
{
data = newData;
}
public void setLeft(BTNode<E> newLeft)
{
left = newLeft;
}
public void setRight(BTNode<E> newRight)
{
right = newRight;
}
public static <E> BTNode<E> treeCopy(BTNode<E> source)
{
BTNode<E> leftCopy, rightCopy;
if (source == null)
return null;
else
{
leftCopy = treeCopy(source.left);
rightCopy = treeCopy(source.right);
return new BTNode<E>(source.data, leftCopy, rightCopy);
}
}
public static <E> long treeSize(BTNode<E> root)
{
if (root == null)
return 0;
else
return 1 + treeSize(root.left) + treeSize(root.right);
}
}
When you declare your variables, make sure you also initialize them before using them. That is, instead of writing
BTNode<String> root;
BTNode<String> child;
BTNode<String> child1;
...
write
BTNode<String> root = null;
BTNode<String> child = null;
...
This is because when you later go on and write the statement
child = new BTNode<String>(LEFT_QUESTION, child2, child14);
child2 and child14 would have been initialized (Whereas in your case, they have only been declared, not initialized)