How to call method properly - java

So I have this method for mean, my goal is to have the user enter one grade at a time, and the dialog box pops up after each grade is entered, after they are finished they hit okay with nothing or cancel and it populates the mean text field. I am having trouble figuring out how to put in the correct parameters for this method, as I need to parse the string they enter into a double array so that the method can properly calculate.
This is the method below:
public double getAverage (double [] gradeArray, int numElem) {
double sum = 0;
for (int i = 0;i < numElem; i++){
sum = sum + gradeArray[i];
}
return (sum / numElem);
}
Here is my code attempting to take the string and put it into the method. Clearly wrong, but I am having trouble wrapping my head around the whole thing. I am not sure how to get my numElem argument to be the correct number, as it changes depending on how many grades the user inputs.
This is my code for the button pushed to calculate:
private void btnGradesActionPerformed(java.awt.event.ActionEvent evt) {
int numElem = 0;
String s = "";
double[] gradesArray;
gradesArray = new double[25];
int i;
do {
s = (String)JOptionPane.showInputDialog(this, "Enter grades:", "Enter grades", JOptionPane.PLAIN_MESSAGE);
if (s == null || s.equals("")) {
if (s == null)
{
s = "";
}
String total2 = String.valueOf(avg);
txtMean.setText(total2);
} else {
for(i=0; i<25; i++)
{
gradesArray[i] = Double.parseDouble (s);
numElem++;
}
avg = getAverage (gradesArray, numElem);
}
} // end Do
while (!s.equals(""));
}

Keep track of how many grades the student has entered. You can do this with a variable that starts at 0 and gets incremented every time the student enters a grade correctly. You can then pass that value as numElem.

I think something like this is what you'd want to do:
s = ... //ask user to input number of grades here
numElem = Int.parseInt (s)
for(i=0; i<numElem; i++)
{
s = ... //prompt for next grade
gradesArray[i] = Double.parseDouble (s);
}
You can initialize gradesArray to be bigger as well to account for more possibilities, maybe 100 or something. Just make sure the numElem input isn't greater than the initialized size.

Related

User input never enters if statement

The point of the program is to have a user input an amount of integers endlessly (until they enter something other than an integer), and for each integer the user inputs, it should check if the integer is greater than or less than the value entered.
The problem: When the program runs, everything is fine until reaching
number = scanner.nextInt();
At this point, the user inputs their integer, but never makes it inside the following if statements. I would love a hint instead of an answer, but I'll take what I can get.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
} while (true);
scanner.close();
}
}
Your minNumber and maxNumber declarations should be out side of the loop. Also, you need to initialize the values as below to get correct min and max comparison with the entered values only:
int minNumber = Integer.MAX_VALUE;
int maxNumber = Integer.MIN_VALUE;
In print statement instead of minNumber you are printing number!
It's not reaching the if statements, because if it did, the user input would update to the value entered I would think. It doesn't. It outputs the values initially declared.
You're not getting the right output and you have a hypothesis that the cause is the code not entering the if statements. Following the scientific method, the next step is to test your hypothesis.
If you put printouts inside the if statements you'll see that they are indeed running. That's not it. The mistake must be elsewhere. You should collect more evidence and develop a new hypothesis.
Hint: Try printing out the values of your variables at the beginning and end of each iteration. I've marked the places below. Are they what you expect them to be? You're going to see an anomaly that should point you in the right direction.
do {
System.out.println("Enter number: ");
int number = 0;
int minNumber = 0;
int maxNumber = 0;
// Print number, minNumber, and maxNumber.
boolean hasInt = scanner.hasNextInt();
if (hasInt) {
number = scanner.nextInt();
if (maxNumber < number) {
maxNumber = number;
}
if (minNumber > number) {
minNumber = number;
}
} else {
System.out.println("Your minimum number: " + number);
System.out.println("Your maximum number: " + maxNumber);
break;
}
// Print number, minNumber, and maxNumber.
} while (true);

How to sum integer inputs in Java, and display the results in an array at the end of the program?

I am trying to create a "calculator", except it needs to print each element that was used to compose the sum total. This printing of the array elements needs to happen at the end of the program, when the user inputs 0 twice in a row.
Upon entering an input, the integer values will be stored in an array. Once the end of the program has been reached, the contents of this array will be printed. However, if the end of the program has not been reached, the program continues while the user adds consecutive inputs.
Currently, the program will only print one element at a time, instead of every element that was used to calculate the total. I've spent hours trying to debug, and any guidance would be greatly appreciated!
import java.util.*;
public class AddingMachine {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean justStarting = true;
int total = 0;
int subtotal = 0;
int input;
int last = 1;
int MAXIMUM_NUMBER_OF_INPUTS = 100;
while (true) {
input = scanner.nextInt();
if (input == 0) {
if (last == 0) {
System.out.println("total " + total);
return;
}
System.out.println("subtotal " + subtotal);
total += subtotal;
subtotal = 0;
}
subtotal += input;
last = input;
int[] numbers = new int[args.length];
for (int i = 0; i < args.length; i++) {
numbers[i] = last;
}
System.out.println(Arrays.toString(numbers));
}
}
When summing the input in your loop, you could store the users input into a List of integers. Once you need to reprint them, you can iterate over the List and print the elements you stored.
Example:
List<Integer> storedUserInput = new ArrayList<>();
while (true) {
input = scanner.nextInt();
storedUserInput.add(input);
if (input == 0) {
if (last == 0) {
for(Integer i : storedUserInput){
System.out.print(i + " + ");
}
System.out.println("total " + total);
return;
}
System.out.println("subtotal " + subtotal);
total += subtotal;
subtotal = 0;
}
}
Within the while loop, the array is re-initialized each time:
int[] numbers = new int[args.length];
so any previously entered value is lost. Also, the purpose of the for loop within the while is not clear.
Also, unless using an array is a requirement, you really don't need an array. You could just use a StringBuffer and append the entered values.

Taking in user input as a string and converting it to a double to place in a 2 dimensional array

This is my code:
Scanner scan = new Scanner(System.in);
String userInput = scan.nextLine();
String nameArray[] = new String[20];
double gradeArray[][] = new double[20][5];
double avgArray[] = new double[20];
double average;
// iterate through all 20 students
for (int i = 0; i < 21; i++)
{
// ask for user input for grade
System.out.println("Please enter 5 of the student's grade(s): ");
average = 0;
nameArray[i] = userInput;
for (int j = 0; j < 5; j++)
{
gradeArray[i][j] = Double.parseDouble(userInput);
average +=Double.parseDouble(userInput);
System.out.println("/n");
}
avgArray[i] = average;
}
I keep running into an error on the line that converts userInput to a double and sets i equal to it within my gradeArray gradeArray[i][j] = Double.parseDouble(userInput);. I'm not sure what the proper method would be for taking in userInput and then inserting it into the gradeArray as a double.
I think the problem is that you have misunderstood how to assign a value from a function. The scan.nextLine() is a function that will wait until the user has done his/her input and then pressed "enter". You need to call this every time you expect input from the user. I hope that will solve your issues. Another important thing is that the inputed text needs to be on the right format for a double. So 1.2 will work, but not 1,2. Good luck!

How to check if an int contains a letter

I am trying to validate my code by error checking. I want to make sure the integer people enter does not contain a letter or more.
Here is my code. I am supposed to solve this problem using a one dimensional array. I got the code working but I am having problems with adding the error checking in.
Any help would be appreciated. Thanks
public void getNumbers() {
Scanner keyboard = new Scanner(System.in);
int array[] = new int[5];
int count = 0;
int entered = 0;
int k = -1;
while (entered < array.length) {
System.out.print("Enter a number ");
int number = keyboard.nextInt();
if (10 <= number && number <= 100) {
boolean containsNumber = false;
entered++;
for (int i = 0; i < count; i++) {
if (number == array[i]) // i Or j
{
containsNumber = true;
}
}
if (!containsNumber) {
array[count] = number;
count++;
} else {
System.out.println(number + " has already been entered");
}
} else {
System.out.println("number must be between 10 and 100");
}
//what does %d do?
for (int j = 0; j < count; j++) {
System.out.printf("%d ", array[j]);
}
System.out.println();
}
}
}
I'm assuming that you would want your program to ask the user to re-enter a number if they do not input a number the first time. In this scenario you might want to try something along the lines of this:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
while(!sc.hasNextInt()) {
//print some error statement
sc.nextLine();
}
int number = sc.nextInt();
System.out.println("Number is: " + number); // to show the value of number
// continue using number however you wish
Since hasNextInt() returns a boolean determining whether or not the input is an Integer, the program will never leave the while-loop until the program can confirm that the user has entered an integer.
keyboard.nextInt() will throw a InputMismatchException if you input a String.
If you want to check whether Scanner has an integer to read, you can use keyboard.hasNextInt().
Alternatively, you can read the input as
String s = keyboard.next() which will take the input as a String, and then use s.matches(".*\\d+.*") to detect whether or not it is an integer.
UPDATE: To answer questions -
keyboard.hasNextInt() will return a boolean. So for example, after System.out.print("Enter a number"), you could have an if statement checking to see if keyboard can receive numerical input, ie. if(keyboard.hasNextInt). If this is true, that means the user has entered numerical input, and you could continue with sayingint number = keyboard.nextInt(). If it is false, you would know that the user input is non-numerical.

Trying to take the max and min values out of a user input and displaying them in Java Eclipse

OK thanks so now the code can find the word in the string array but now I need to get the most positive word from the user input and the most negative word from the user input. So if I plug in dreadful zone, dreadful is 1.25 and zone is 2.66, so dreadful is the most negative word and zone is the most positive word but how the code is set up I don't know how to keep track of those values then make sure that it can print out the correct word as the most positive and the word as the post negative. So the average of the user input is printed. I tried doing parallel arrays but I want to avoid those. The other issues are being able to take multiple inputs from the user until they use the keys ctrl z or ctrl d. (I was told they are part of Eclipse but I have no idea how to use them.)
Thank you for any suggestions on how to proceed.
Output:
Please type one line of review and when you are done press either Ctr D or Ctr Z
dreadful zone
dreadful zone
The average is negative at 1.9583333333333333
Incomplete assignment
public class MovieReviewSentimentAnalysis {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
// TODO: complete me
//make own arrays to pass by value
//movieReviewComments = the text
String[] movieReviewComments = new String[8529];
//movieReviewScores = numeric values, avoid lit. values
int[] movieReviewScores = new int[8529];
String userComment = "";
MovieReviewReader.readMovieReviews("movie_reviews.txt", movieReviewComments, movieReviewScores); //string, string array, and int array
System.out.println("Please type one line of review and when you are done press either Ctr D or Ctr Z");
userComment = userInput.nextLine();
System.out.println(userComment);
// String[] words = userComment.split("\\s+");
String[] words2 = userComment.split("[\\W]"); //splits at "\W", or non-word characters
double singularUserWordTotal = 0;
double wordTotal = 0;
double totalSumOfUserCommentWords = 0;
double highestWordScore = 20;
double lowestWordScoreTotal = 0;
int locationOfWordInUserInput = 0;
String userInputWord = "";
// int itemCount = words.length;
for (int i = 0; i < words2.length; i++)
{
userInputWord = words2[i];
singularUserWordTotal = wordCount(userInputWord, movieReviewComments, movieReviewScores);
wordTotal += singularUserWordTotal;
totalSumOfUserCommentWords = wordTotal / words2.length;
// locationOfWordInUserInput = i;
// if(singularUserWordTotal > highestWordScore)
// {
// singularUserWordTotal = highestWordScore;
// }
// if(singularUserWordTotal < highestWordScore)
// {
// singularUserWordTotal = highestWordScore;
// lowestWordScoreTotal = singularUserWordTotal;
// }
}
displayScores(totalSumOfUserCommentWords);
// System.out.println(reviewFile);
System.out.println("Incomplete assignment");
userInput.close();
}
public static double wordCount(String userInputWord, String[] movieReviewComments, int[] movieReviewScores)
{
double storeScore = 0;
double totalSumOfReviewScores = 0;
double numOfTimesWordAppears = 0;
for (int i=0; i < (movieReviewComments.length); i++)
{
if (movieReviewComments[i].contains(userInputWord))
//PUNCTUATION IS A PROBLEM (if it's at the end of the user input then it's fine though)
{
storeScore = movieReviewScores[i];
totalSumOfReviewScores += storeScore;
numOfTimesWordAppears++;
//System.out.println("Found");
//What if the word doesn't appear in the text file?????
}else if (!movieReviewComments[i].contains(userInputWord))
{
numOfTimesWordAppears += 0;
}
// else
// System.out.println("You dun goofed"); //delete after fixing problem
}
double wordScoreAverage = totalSumOfReviewScores / numOfTimesWordAppears;
return wordScoreAverage;
}
public static double displayScores(double userCommentTotal)
{
if(userCommentTotal > 2.01)
{
System.out.println("The average is positive at " + userCommentTotal);
}else if(userCommentTotal < 2.01 && userCommentTotal > 1.99)
{
System.out.println("The average is neutral at " + userCommentTotal);
}else
System.out.println("The average is negative at " + userCommentTotal);
return userCommentTotal;
}
You can try to use HashMap for this:
Map<String,Integer> h = new HashMap<String,Integer>();
h.put(word,word_score);
//get word score
int score = h.get(word)

Categories