Java swing - list.add issues - java

I'm creating a GUI for use in a judged sporting event. There are 6 judges and they each input their score into the GUI. They then hit calculate, and the program is meant to sort the numbers from low to high and then take the numbers from position 1 through 4 and give an average.
I have written the code for input via console and that works, but when I try my Gui the 'list.add' doesn't work. I don't know if I am meant to use something else.
btnCalculate = new JButton("Calculate");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
inGui = new Scanner (System.in);
double firstRun = getAverageOfRun(1);
double secondRun = getAverageOfRun(2);
double best;
if (firstRun > secondRun) {
best = firstRun;
} else {
best = secondRun;
}
textFieldRun1Score.setText(Double.toString(best));
}
private double getAverageOfRun (int runNumber) {
double total, avg;
int num1, num2, num3, num4, num5, num6;
List<Integer> list = new ArrayList<Integer>();
num1 = Integer.parseInt(textFieldRun1Score1.getText());
System.out.print(""+runNumber +": ");
list.add(textFieldRun1Score1.getText());
list.add(textFieldRun1Score2.getText());
list.add(textFieldRun1Score3.getText());
list.add(textFieldRun1Score4.getText());
list.add(textFieldRun1Score5.getText());
list.add(textFieldRun1Score6.getText());
Collections.sort(list);
total = list.get(1) + list.get(2) + list.get(3) + list.get(4);
avg = total / 4;
textFieldBestScore.setText(Double.toString(avg));
return avg;
}

This code won't compile for a simple reason: type mismatch.
Just split this line:
list.add(textFieldRun1Score1.getText());
up: list.add(...) expects an int as parameter (since it's templatetype is Integer), textFieldRun1Score1.getText() returns a String. Thus you'll have to convert from String to int first. Most common way to solve this is int value = Integer.parseInt(string);

list.add(textFieldRun1Score1.getText());
won't work because you try to add a String to a list of Integers
Parse the String to an Integer first:
list.add(Integer.parseInt(textFieldRun1Score1.getText()));
.
edit (not an answer to your question, but a general advice):
Instead of doing:
double best;
if (firstRun > secondRun) {
best = firstRun;
} else {
best = secondRun;
}
simply use: double best = Math.max(firstRun, secondRun);

Related

Take Average of an Array using Recursion

I'm trying to create a program that will take a user input, input that data into an dynamic array, and then recursively finds the average. The first part of my code works. This allows the newly created array to be passed to the method.
public static void main(String args[])
{
int i = 0;
int sum = 0;
double runningTotal = 0;
int classSize;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the class size: ");
classSize = keyboard.nextInt();
int newClassSize[] = new int[classSize];
for (i=0; i < newClassSize.length; i++)
{
System.out.println("Please enter the grade of the user at: " + (i + 1));
newClassSize[i] = keyboard.nextInt();
}
findAverage();
for (i=0; i < newClassSize.length; i++){
sum = sum + newClassSize[i];
}
System.out.println(Arrays.toString(newClassSize));
keyboard.close();
}
}
This is where I'm getting confused and confusing myself however. How would I pass the newly created array to the findAverage() method? I would then need to also have that be saved to an accumulator and then devided. Is there a better way to do this? This is my current findAverage() method but I'm confusing myself on my implementation.
public double findAverage(int classAverage, int baseCase, double runningAverage)
{
runningAverage = 0;
int sum = 0;
if (newClassSize.length - 1 > baseCase)
runningAverage = newClassSize.length;
return findAverage();
System.out.println("The class average is " + classAverage);
}
Hopefully I understood your question correctly but heres how to do it below.
The basic idea is that when the index reaches the length of the array in the
recursive function that's the base case. So all you have to do is add to the sum at each index point in the array, and just keep passing in the updated index and sum into the recursive function.
class Main {
public static void main(String[] args) {
int newClassSize[] = {1,2,3}; // User Input let say
double average = findAverage(newClassSize);
System.out.println(average);
}
public static double findAverage(int[] arr){
// Avoid division by zero error
if (arr.length==0){
return 0;
}
return findAverageHelper(arr,0,0);
}
public static double findAverageHelper(int[] arr, int index,int sum){
if (index==arr.length){ // Base Case
return (double) sum/arr.length;
}
// Increase index and add current value at index to sum
return findAverageHelper(arr,index+1,sum+=arr[index]);
}
}

Java Method isn't implementing what it is supposed to

Hey everyone very new to coding!
So I was trying to make a calculator program using object oriented programming in Java however when I try to call my method for addition it doesn't do the job entirely so what am I doing wrong here ?
Thanks in advance :)
import java.util.Scanner;
public class CalculatorOOP {
Scanner input = new Scanner(System.in);
public static double currentValue;
public double valueInput;
public CalculatorOOP(double valueTyped){
valueTyped = currentValue;
}
public double addToValue(){
System.out.println("Type the value you want to add:");
double valueToAdd = input.nextDouble();
double valueAfterAddition = CalculatorOOP.currentValue + valueToAdd;
return valueAfterAddition;
}
public double substractToValue(){
System.out.println("Type the value you want to substract:");
double valueToSubstract = input.nextDouble();
double valueAfterSubstraction =
CalculatorOOP.currentValue - valueToSubstract;
return valueAfterSubstraction;
}
public double multiplyValue(){
System.out.println("Type the factor value:");
double factor = input.nextDouble();
double valueAfterMultiplication = CalculatorOOP.currentValue * factor;
return valueAfterMultiplication;
}
public double divideValue(){
System.out.println("Type the divisor value:");
double divisor = input.nextDouble();
double valueAfterDivision = CalculatorOOP.currentValue / divisor;
return valueAfterDivision;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Type a value:");
double valueInput = input.nextDouble();
CalculatorOOP obj = new CalculatorOOP(valueInput);
System.out.println("Enter the calculation option (1, 2, 3, or 4):");
int optionEntered = input.nextInt();
switch (optionEntered){
case 1 : obj.addToValue();
}
}}
Here this is what I get when running the code however it is not performing the addition it is just asking for values
Type a value:
2
Enter the calculation option (1, 2, 3, or 4):
1
Type the value you want to add:
4
Process finished with exit code 0
Your addToValue method seems to perform the addition correctly and return the calculated sum. Where you call the method, you are not picking up the return value — so it just disappears, is discarded. I believe you want to assign it back into CalculatorOOP.currentValue and/or print it. Either from inside the method or from where you called it.

How to set integer range in Scanner? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am learning java and I want to create a command-line application that calculates exam percentages based on marks obtained. But the problem is I don't have the idea to set the range of marks obtained while the marks range is between 0 to 100.
Below is the code, I have tried: -
package com.company;
import java.util.*;
public class CbseCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of Physics");
float physics = sc.nextFloat();
System.out.println("Enter marks obtained of Chemistry");
float chemistry = sc.nextFloat();
System.out.println("Enter marks obtained of Math");
float math = sc.nextFloat();
System.out.println("Enter marks obtained of English");
float english = sc.nextFloat();
System.out.println("Enter marks obtained of Computer Science");
float computer = sc.nextFloat();
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained/total)*100;
System.out.println("The percentage obtained is: "+percentage);
sc.close();
}
}
It is not a good idea to try to get Scanner to do that1.
Instead, you should use Scanner to read an int and then test the result that it gives you to check that it is in the correct range. Something like this:
int number;
if (myScanner.hasNextInt()) {
number = myScanner.nextInt();
if (number < 0 || number > 100) {
// handle case where the number is out of range
}
} else {
// handle case where the input is not an integer
}
I will leave it to you to figure out how to map the above onto your application's requirements.
1 - The standard Scanner class doesn't provide a method that reads a number in a given range (and rejects numbers outside of that range). You could conceivably extend the Scanner class with this functionality, but it would be difficult. There are simpler solutions.
I would suggest you to write a function to get a valid input as below :-
public int getValidInput(Scanner in, int range) {
while (in.hasNext()) {
if (in.hasNextInt()) {
int val = in.nextInt();
if (val >= 0 && val < range) { // <-- from "0" to "range".
return val;
}
} else {
in.next();
}
}
return -1;
}
This function is ensuring that the input is given as an integer only and it lies in the range o to range. You can change it as per your requirement.
Consider this method:
static int getMark(String course){
int mark = 0;
boolean valid = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of " + course + ": ");
while(valid){
mark = sc.nextInt();
if(mark < 0 || mark > 100){
System.out.println("Mark must be between 0-100");
} else {
valid = true;
}
}
sc.close();
return mark;
}
This way you can get two birds with one stone, leaving the resulting code as this:
public static void main(String[] args){
int physics = getMark("Physics");
int chemistry = getMark("Chemistry");
int math = getMark("Math");
int english = getMark("English");
int computer = getMark("Computer Science");
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained / total) * 100;
System.out.println("The percentage obtained is: " + percentage);
}

how do i delete variables in order to reuse them in java

I am making a calculator that theoretically should be able to go over the normal integer limit right now I am prototyping a smaller test version of this thing. I often have to often carry a number like in multiplication but I use the same variable over and over again and I want to be able to clear those variables in order to reuse them in my calculator
import java.util.Scanner;
import java.util.LinkedList ;
public class mass_mulitplication_software {
public static void multiply () {
Scanner keyboard = new Scanner (System.in);
//multiplication#1
System.out.println("ones place");
double fnum1 = keyboard.nextDouble() ;
System.out.println("tens place");
double fnum2 = keyboard.nextDouble() ;
System.out.println("hundreds place");
double fnum3 = keyboard.nextDouble() ;
//multiplication#2
System.out.println("ones place");
double snum1 = keyboard.nextDouble() ;
System.out.println("tens place");
double snum2 = keyboard.nextDouble() ;
System.out.println("hundreds place");
double snum3 = keyboard.nextDouble() ;
tnum=fnum1*snum1;
mass_mulitplication_software.carry();
tnum=fnum1*snum2;
mass_mulitplication_software.carry();
tnum=fnum1*snum3;
mass_mulitplication_software.carry();
tnum=fnum2*snum1;
mass_mulitplication_software.carry();
tnum=fnum2*snum2;
mass_mulitplication_software.carry();
tnum=fnum2*snum3;
mass_mulitplication_software.carry();
tnum=fnum3*snum1;
mass_mulitplication_software.carry();
tnum=fnum3*snum2;
mass_mulitplication_software.carry();
tnum=fnum3*snum3;
}
public static double carry(){
if (tnum>10){
double mnum= tnum%10;
double mmnum = tnum- mnum ;
double cnum = mmnum/10 ;
return cnum;}
public static void main(String[] args) {
mass_mulitplication_software.multiply();
} }
also please consider I am a novice coder who has just begun coding and wished to improve upon my old calculator to take bigger numbers this a small version prototype for multiplying specifically do any of u guys know how to clear a double variable so it can be reused with a different #
As previous commentor's said consider using BigInteger or unsigned int. And put each input into its own variable, it will make your life a lot easier, and you wont need the carry() method.
Aside from that, a few things to point out, you call the carry() method, but do nothing with the double that it returns, also in this case, tnum will always equal fnum3 * snum3
You could always make a menu with an option to clear all numbers, and upon choosing that option, have a method that sets those variables to 0. This menu would go in the main method.
It seems like you might want to have a menu using a while loop regardless, so you can repeat this process over and over again with different values.
something like:
int menuChoice = -1;
while (menuChoice < 1 || menuChoice > 8) {
System.out.println();
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Power");
System.out.println("6. Logarithm");
System.out.println("7. Clear");
System.out.println("8. Quit");
System.out.println();
System.out.print("What would you like to do? ");
menuChoice = input.nextInt();
if (menuChoice < 1 || menuChoice > 8) {
System.out.println(menuChoice + " wasn't one of the options");
}
}
return menuChoice;
}
This is the menu from a calculator I'm working on. You can use if statements to perform appropriate functions based on what the user enters. So you could have a menu option to multiply, and have the user enter values into each variable for your numbers.
You don't actually have to clear variables--after a function is performed, the menu would simply display again after the operation is performed, since menuChoice is initialized to -1 before the while loop. The user would just choose an option and enter new values into those variables which would replace the old ones.
You might simply want to use unsigned long long int as your variable type, since it's range is from 0 to 18,446,744,073,709,551,615. The method you're using seems overly complicated.
You might consider using an array to store the digits of your variables, rather than trying to hold all the digits in individual variables. This will make it easier for you to iterate over them when you do your carry() and borrow() operations, since those may need to move values up and down the length of your digits.
You could then, say, do multiplication and division the way you would long-hand, using an array to store intermediate values. Consider:
public class Digits {
List<Integer> digits;
public Digits() {
digits = new ArrayList<>();
}
public Digits(Digits other) {
digits = other.getDigits();
}
public List<Integer> getDigits() {
return digits;
}
public Digits times(Digits other) {
List<Integer> newDigits = new ArrayList<>();
for (int i=0; i<other.getDigits().size(); i++) {
for (int j=0; j< digits.size(); j++) {
Integer temp;
try {
temp = newDigits.get(i+j);
} catch (IndexOutOfBoundsException ioobe) {
temp = 0;
}
newDigits.set(i+j, temp + other.getDigits().get(i) * digits.get(j));
}
carry();
}
}
private void carry() {
for (int i=0; i<digits.size(); i++) {
while (digits.get(i) >= 10) {
digits.set(i, digits.get(i) - 10);
digits.set(i+1, digits.get(i+1) + 1);
}
}
}
}

Looping with different variables?

Before this the user inputs an int for numOfTimes. Say it's 5. This will ask the question 5 times. But each time through it will erase the previous value in hrs1. It needs to be a separate variable. So if numOfTimes=5 Then I should get 5 different doubles for "Hour " and 5 different doubles for "Minute ". (assuming the user inputs different times) but they all need to be stored in different variables. How should I do this?
Thank you my question has been answered!
use an array ..
int a[] = new int[5];
for(int i =0;i<5;i++){
a[i] = //your value
}
You just need to put your "calculate average" code outside the for loop. I am not sure exactly how you want to calculate the average. But here are two simple ways.
Method one - keep track of the totals and calculate the basic average.
public class AvgTime {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
System.out.println("\n");
double hrTotal = 0;
double minTotal = 0;
for (int i = 1; i <= numOfTimes; i++){
System.out.println("What Time (military time): ");
System.out.print("Hour ");
double hrs1 = in.nextDouble();
System.out.print("Minute ");
double min1 = in.nextDouble();
hrTotal += hrs1;
minTotal += min1;
}
//calculate average
double avdHr1 = hrTotal/numOfTimes;
double timeMin1 = minTotal/numOfTimes;
System.out.println(avgHr1+":"+timeMin1 + " P.M");
}
}
Method 2 - Use lists and iterate twice
public class AvgTime {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
System.out.println("\n");
ArrayList<Double> hours = new ArrayList<>();
ArrayList<Double> minutes = new ArrayList<>();
double minTotal = 0;
for (int i = 1; i <= numOfTimes; i++){
System.out.println("What Time (military time): ");
System.out.print("Hour ");
double hrs1 = in.nextDouble();
System.out.print("Minute ");
double min1 = in.nextDouble();
hours.add(hrs1);
minutes.add(min1);
}
//calculate average
double avgHr1 = 0;
double timeMin1 = 0:
for (int i = 0; i < hours.size(); i++) {
double hour = hours.get(i);
double minute = minutes.get(i);
//ToDo: calculate average so far
}
System.out.println(avgHr1+":"+timeMin1 + " P.M");
}
You can use arrays to store the information the user has input. Before the loop, make an array using the new keyword, e.g. double[] hrs=new double[numOfTimes]. In the loop, write to different locations in the array for each input, hrs[i]=in.nextDouble(). You can later read from a position on the array using the syntax 'name[index]', such as 'hrs[2]'. Note that for java and many other languages, arrays start at 0. This means for an array [1,2,3] named arr, arr[1] equals 2 instead of 1. This means it would be best if your for loop was changed from for(int i=1;i<=numofTimes;i++) to 'for(int i=0;i
<SOAPBOX,RANT,HIGHHORSE>
This is more of a code review than a straight answer, but something has been bugging me about newbie questions that I've observed on stackoverrflow.
When developing, I avoid keyboard input like the plague. It is such drudgery, especially with a loop such as in this program. So many newbie questions have user-keyboard input. Why?! It makes development so much more difficult!
I've rewritten your program to add the ability for testing data, completely avoiding the need for user-input during development. When testing is over, just switch the test/live comments around.
I'm sure there's a more elegant way, but this style has worked well for me, and I recommend it.
</SOAPBOX,RANT,HIGHHORSE>
import java.util.*;
import static java.lang.Math.abs;
public class AverageTimeWTestingData {
public static void main(String[] args) {
HourMin24[] ahm = null;
//EXACTLY ONE of the following lines must be commented out
//Test only:
ahm = getTestData();
//Live only:
// ahm = getDataFromUserInput();
double dTotalHours = 0.0;
for (HourMin24 hm : ahm){
System.out.println("Time: " + hm.iHour + ":" + hm.iMin);
dTotalHours += hm.iHour + (hm.iMin / 60);
}
System.out.println("Average time (" + ahm.length + "): " + (dTotalHours / ahm.length));
}
private static final HourMin24[] getDataFromUserInput() {
Scanner in = new Scanner(System.in);
System.out.print("How many times? ");
int numOfTimes = in.nextInt();
ArrayList<HourMin24> al24 = new ArrayList<HourMin24>(numOfTimes);
while(numOfTimes < 0) {
System.out.println("What Time (military time): ");
System.out.print("Hour ");
int iHour = in.nextInt();
System.out.print("Minute ");
int iMin = in.nextInt();
al24.add(new HourMin24(iHour, iMin));
numOfTimes--;
}
return al24.toArray(new HourMin24[al24.size()]);
}
private static final HourMin24[] getTestData() {
System.out.println("TEST MODE ON");
return new HourMin24[] {
new HourMin24(13, 1),
new HourMin24(23, 19),
new HourMin24(0, 59),
new HourMin24(16, 16),
};
}
}
class HourMin24 {
public int iHour;
public int iMin;
public HourMin24(int i_hour, int i_min) {
iHour = i_hour;
iMin = i_min;
}
}
Output:
[C:\java_code\]java AverageTimeWTestingData
TEST MODE ON
Time: 13:1
Time: 23:19
Time: 0:59
Time: 16:16
Average time (4): 13.0

Categories

Resources