Averaging Grades Program Throwing Exception With Negative Numbers
Nov 17, 2014
So I have re-written the code but it is still not running correctly. Any number i type in it throws an exception, also i need the program to add the totals that i type in and then once i type -1 into the prompt button list all the number i typed in and give me the average.
import java.awt.*;
import java.awt.event.*;
import javax.swing .*;
import javax.swing.text.*;
public class Averages extends JFrame
{
//construct components
JLabel sortPrompt = new JLabel("Sort By:");
I do now have the problem where i have to insert the numbers 1 to 100 individually in order to allow the program to accept a grade as high as 100%.
Also as soon as i type in a negative number the system crashes and shows me a error as attached.
/* Averaging grades To use the Java Swing interface to calculate the average of up to 50 grades.Average is calculated once -1 is entered as a value. The grades are then sorted from lowest to highest and displayed in a content pane which also displays the average. */
import java.awt.*; import java.awt.event.*; import javax.swing .*; import javax.swing.text.*; public class Averages extends JFrame { //construct components JLabel sortPrompt = new JLabel("Sort By:");
Ok so I have my program working for the most part. In this program I am supposed to take input from the user until they enter a negative number and that works, the problem is that it doesn't work if I enter a negative number on the first prompt. For example if I enter a 100 it would prompt me again and if I enter a negative number it would quit and give me the average, but if I enter a negative number the first time I am prompted the program just gives me an error. How do I fix that?
import java.util.List; import java.util.ArrayList; import java.util.Scanner; public class Application { public static void main(String [] args){ Scanner input = new Scanner(System.in); List<Integer> grades;
Write a Swing program that declares an empty array of grades with a maximum length of 50. Implement a JOptionPane input box within a while loop to allow the user to enter grades. When the user enters the sentinel value of -1, that will signal the end of the data input loop.
After the grades are entered, a content pane should display the grades sorted from lowest to highest. Write a loop that goes through the array looking for elements that are greater than zero (0). Keep a running count of those items, and also accumulate them into a grand total. Divide the grand total by the number of grades entered to find an average, and display the average at the end of the sorted list of grades. Use the DecimalFormat method to display the average to 2 decimal places.
In my cs class, we have to write a program that throws an exception if the user enters a negative number, the program should prompt the user to enter only positive numbers and then let them retype the number. But everytime I throw an exception, my program gets suspended.
What am I doing wrong, or is there no way to continue a program if an exception is thrown? Does the program automatically get suspended when an exception is thrown?
try{ do { N = kb.nextDouble(); if(N<0) { throw new NegativeArraySizeException(); } else j++; } while(j==0); fill.size(N); } catch(NegativeArraySizeException e) { System.out.println("The number you entered must be positive. Please try again."); }
Right, so I got this program. It takes input from the user and assigns it to fields on an object. But, it's meant to check the users input. If the user enters bad input, it's supposed to throw this exception. For each of these exceptions, theres a class specifically for it.
public class PayrollDemo { public static void main(String[] args) { Payroll pr = new Payroll ("Test Name", 234); System.out.println("Current Employee Information. "); System.out.println("Name: " + pr.getName()); System.out.println("ID: " + pr.getID()); System.out.println("Hourly Pay Rate: " + pr.getHourlyPayRate());
[Code] ....
And this is the exception class.
public class InvalidNameException extends Exception { /** No-arg constructor */ public InvalidNameException() { super("Invalid name"); } }
PayrollDemo.java:43: error: cannot find symbol InvalidNameException.InvalidNameException(); ^ symbol: method InvalidNameException() location: class InvalidNameException 1 error
It's just meant to tell the user that they entered an invalid value, which would mean if they entered an empty string instead of a name.
Overloaded methods CAN declare new or broader checked exceptions. We know that FileNotFoundException is a subclass of IOException and according to the above statement an overloaded method cannot throw a narrower exception. But the below code does not throw a compiler error. How?
Animal.java
Java Code:
package pack1;
import java.io.FileNotFoundException; import java.io.IOException; public class Animal{ public void drink(int s) throws IOException {
I came across a code where the exceptions can be thrown from catch and finally block too. I never gave a thought on what scenarios that can be required. Some practical examples when/where it can be required to throw the exception from catch and finally blocks.
I have a enum class which contains some string which i am comparing to a string i get from a user
Java Code:
public enum Compare { a, b, c, d, e, f } class SomeClass { String method(String letter){ Compare word= Compare.valueOf(letter); } } mh_sh_highlight_all('java');
Everything works fine but when I added a new word to it like "g" it throws the IllegalArgumentException ?
If I put the highlighted text in try/catch block it is throwing NullPointerException , if I am using command line arguments then also it is showing the same exception.
I've come across an interesting problem when using a Jcombobox as a custom cell editor(and renderer) in a jtable. I was hoping to add a keybinding in order to display the dropdown of the combobox instead of having to click on it however, when I make a call to showPopup() I get:
Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location Which is strange as my jtable is visible and the editor/renderer seems to be working fine.
Here's the cell editor + renderer I'm using:
class MyComboBoxRenderer extends JComboBox implements TableCellRenderer { public MyComboBoxRenderer(String[] items) { super(items); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { setForeground(table.getSelectionForeground());
This is a simple project that i was using to test my current java knowledge (kinda like revision) and for that i used two classes to make a simple averaging program. i know i0m making it more difficult but like i said i'm testing myself but i come up with an unexpected error. Here's the code:
- 1st Class
import java.util.Scanner; public class Main { public static int num; public static int total = 0; public static int average;
[Code].....
Now the problem is after inputing the numbers it doesn't give me the average but the value of 0.
Create an integer array with 10 numbers, initialize the array to make sure there are both positive and negative integers. Write a program to generate two arrays out of the original array, one array with all positive numbers and another one with all negative numbers. Print out the number of elements and the detailed elements in each array.
public class problem3 { public static void main(String[]args){ int[] numbers = {1, 2, 3, 4, 5, -1, -2, -3, -4, -5}; for (int i = 0; i<numbers.length;){ if(i>0){ System.out.println(numbers); } else System.out.println(numbers); } } }
I am very new to Java. I have been working for a couple months on a program for school. It has not gone well. I finally was able to scrap together a working program, but i left something out that needs to be. I have to include input validation to check for negative values, prompting users to re-enter values if negative. I have included my current code, the program works perfectly, but what to do about the negative numbers.
Java Code:
package gradplanner; import java.util.Scanner; public class GradPlanner { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numofclasses = 0; int totalCUs = 0;
I am very new to Java. I have been working on a program. It has not gone well. I finally was able to scrap together a working program, but i left something out that needs to be. I have to include input validation to check for negative values, prompting users to re-enter values if negative.I have included my current code, the program works perfectly, but what to do about the negative numbers.
package gradplanner; import java.util.Scanner; public class GradPlanner { public static void main(String[] args) { Scanner input = new Scanner(System.in); int numofclasses = 0;
My verify method also always returns false. So I'm given three classes to begin with. Calculator, Expression, and InfixExpression and they are listed below.
The goal is to create a class called PostfixExpression that extends Expression and can read and calculate postfix expressions.
My evaluate() method works for most calculations but when it needs to return a negative value it just returns the positive equivalent.
Also, my verify method always returns false and I can't pinpoint why.
Here's my current code. Some things are commented out for debugging purposes.
import java.util.Scanner; /** * Simple calculator that reads infix expressions and evaluates them. */ public class Calculator { public static void main(String[] args) { Scanner input = new Scanner(System.in);
I'm having some issues getting this code to reject negative numbers. What I'm doing wrong.
import java.util.Random; import java.util.Scanner; public class ForLoop { public static void main (String [] args) { Random randomNumber = new Random();
I've been writing a fraction class code below that does a number of arithmetic calcs and when I run it these are the results I get. My gcd doesn't work when it comes to negative fractions and I'm not quite sure how to print.out the boolean methods ((greaterthan)), ((equals))and ((negative)). I'm also not sure if I have implemented those 3 methods properly. I'm still learning how to do unit testing.
Enter numerator; then denominator. -5 10 -5/10 Enter numerator; then denominator. 3 9 1/3 Sum: -5/30 -0.16666666666666666 Product: -5/30 -0.16666666666666666 Devide: -15/30 -0.5 subtract: -45/90 -0.5 negative: 1/6 0.16666666666666666 Lessthan: 1/6 0.16666666666666666 greaterthan: 1/6 0.16666666666666666
FRACTION CLASS
import java.util.Scanner; public class Fraction { private int numerator; //numerator private int denominator; //denominator
You are to design a Java application to carry out additions and subtractions for numbers of any length. A number is represented as an object which includes a sign and two strings for the whole and decimal parts of the number. And, the operations must be done by adding or subtracting characters directly. You are not allowed to convert these strings to numbers before the operation.
The program must use a "Number" class which includes at least the following methods:
Number ( ); Number (double n); Number add (Number RHS); Number subtract (Number RHS); String toString ( );
This is what i have but it only adds positive numbers and it doesn't subtract problems like 7.05-8.96. Also some of it was what our teacher gave us like alignwhole method
import java.util.Scanner; public class Number{ private String whole; private String decimal; private String sign; public static void main (String[] args){ System.out.println("Enter two numbers");
You are to design a Java application to carry out additions and subtractions for numbers of any length. A number is represented as an object which includes a sign and two strings for the whole and decimal parts of the number. And, the operations must be done by adding or subtracting characters directly. You are not allowed to convert these strings to numbers before the operation.
The program must use a "Number" class which includes at least the following methods:
Number ( ); Number (double n); Number add (Number RHS); Number subtract (Number RHS); String toString ( );
The below code is what our teacher gave us to start with, but it needs to add and subtract positive or negative numbers of any length. This code only adds positive numbers. Need to write code for subtraction .
Java Code:
import java.util.Scanner; public class Number{ private String whole; private String decimal; private String sign;
where to create the array of chars that hold the letter grade. I am assuming that would be in the main with the other arrays. Passing it into an object creating a method in the record.java. Then displaying it in my main.
Take the Grades program and make a class. An object that hold 5 student names, an array of 5 chars that hold the letter grades, 5 arrays of four doubles each to hold the set of test scores. The class should have methods that return a specific student's name, average test score and a letter grade based on the average. Demonstrate the class in a program that allows the user to enter each student's name and their 4 tests scores. It should then display each student's average and letter grade.This is my main program:
import java.util.Scanner; public class GradeBook{ public static void main(String[] args){ Scanner input = new Scanner(System.in); Record[] students = {new Record(), new Record(), new Record(), new Record(), new Record()}; for(int j=0; j < 5; j++){