OK so i have been working on a calculator with classes(To play with classes but a function) and when ever I run it all i get back is zero no matter what I type in or say to use for the operator. Here is my code:
Main class:
import java.util.Scanner;
//numof = number of numbers in array
// numarrays = the array for user input
// finial = finial number aka the answer
public class Calculator {
public static double finial;
/**
* #return the finial
*/
public static double getFinial() {
return finial;
}
/**
* #param numof the finial to set
*/
public static void setFinial(double finial) {
finial = numof;
}
public static int numof;
/**
* #return the numof
*/
public static int getNumof() {
return numof;
}
/**
* #param numof the numof to set
*/
public static void setNumof(int numof) {
numof = numof;
}
public static double[] numarrays;
/**
* #return the numarrays
*/
public static double[] getNumarrays() {
return numarrays;
}
/**
* #param numarrays the numarrays to set
*/
public static void setNumarrays(double[] numarrays) {
numarrays = numarrays;
}
#SuppressWarnings("resource")
public static void main (String[] args) {
System.out.println("Hello and welcome to my calculator, in this calculator you can add, subtract or multiply");
System.out.println("For the next step I need to know how many numbers you would like to input? ");
int numof;
Scanner numofnums= new Scanner(System.in);
numof = numofnums.nextInt();
Calculator.setNumof(numof);
System.out.println("So next you are going to input the numbers");
double[] numarrays = new double[numof];
for (int k=0; k < numof; k++){
System.out.println("Please enter number");
Scanner input = new Scanner(System.in);
numarrays[k] = input.nextDouble();
}
Calculator.setNumarrays(numarrays);
System.out.println("Please enter what you would like to do with these numbers add,subtract,avg,multiply");
Scanner OP = new Scanner(System.in);
String OPerator= OP.next();
if (OPerator.equals ("add")){
Add.adding();
}
else if (OPerator.equals ("subtract")){
subtract.subtracting();
}
else if (OPerator.equals ("multiply")){
multiply.multiplying();
}
else if (OPerator.equals ("avg")){
avg.avging();
}
System.out.println("The answer is " + Calculator.getFinial());
}
}
here is the add class:
public class Add extends Calculator {
public static void adding() {
double finial = 0;
for (int h = 0; h < Calculator.getNumof(); h++){
finial = finial + Calculator.getNumarrays()[h];
}
Calculator.setFinial(finial);
}
}
I do have three more classes but it is just operator classes let me know if you need them
Just a quick look shows some significant basic issues. For example, in a basic setter, like:
public static void setFinial(double finial) {
finial = numof;
}
from your code, what you most likely intended was
public static void setFinial(double paramFinial) {
finial = paramFinial;
}
If your static variable and your parameter have the same name, you can't access both. The compiler will think you're talking about the parameter. Also, be careful that your setter is using the parameter paramFinial instead of the probably unintentional reference to numof.
It would be a lot easier to read the rest of your code if you would comment what finial, numof, and your other variables represent.
Related
This question already has answers here:
Java error: constructor in class cannot be applied to given types
(3 answers)
Closed 4 years ago.
I have a three classes, one to demo and another to extend the first. Everything compiles when in the demo is gives me this error:
EssayDemo.java:11: error: constructor Essay in class Essay cannot be applied to given types;
Essay termPaper = new Essay();
^
required: int,int,int,int
The four ints are Grammar, Spelling, Length, and Content. I set them up but they don't construct an object properly.
This might have been easier if it weren't for the fact that I have to use two classes that I didn't write. Here are the two specific pieces of code. Here's the essayDemo.java:
/**
This program demonstrates a solution to
the Essay Class programming challenge.
*/
public class EssayDemo
{
public static void main(String[] args)
{
// Create an Essay object.
Essay termPaper = new Essay();
// Assign scores to the object.
// Grammer = 25 points, Spelling = 18 points,
// Length = 20 points, and Content = 25 points.
termPaper.setScore(25.0, 18.0, 20.0, 25.0);
// Display the score details.
System.out.println("Term paper:");
System.out.println("Grammar points: " + termPaper.getGrammar());
System.out.println("Spelling points: " + termPaper.getSpelling());
System.out.println("Length points: " + termPaper.getCorrectLength());
System.out.println("Content points: " + termPaper.getContent());
System.out.println("Total points: " + termPaper.getScore());
System.out.println("Grade: " + termPaper.getGrade());
}
}
And here's the gradedActivity.java:
/**
The GradedActivity class stores data about a graded
activity for the Essay Class programming challenge.
*/
public class GradedActivity
{
private double score; // Numeric score
/**
The setScore method sets the score field.
#param s The value to store in score.
*/
public void setScore(double s)
{
score = s;
}
/**
The getScore method returns the score.
#return The value stored in the score field.
*/
public double getScore()
{
return score;
}
/**
The getGrade method returns a letter grade
determined from the score field.
#return The letter grade.
*/
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
}
}
Here's the code I've written to extend it:
public class Essay extends GradedActivity
{
private final int grammarPossible = 30;
private final int spellingPossible = 20;
private final int lengthPossible = 20;
private final int contentPossible = 30;
private final int overallPossible = 100;
private int grammarGrade;
private int spellingGrade;
private int lengthGrade;
private int contentGrade;
private int overallGrade;
public Essay(int grammar, int spelling, int length, int content){
setGrammarGrade(grammar);
setSpellingGrade(spelling);
setLengthGrade(length);
setContentGrade(content);
setOverallGrade();
setScore(getOverallGrade());
}
public int getGrammarGrade(){
return grammarGrade;
}
public void setGrammarGrade(int grammarGrade){
this.grammarGrade = grammarGrade;
}
public int getSpellingGrade(){
return spellingGrade;
}
public void setSpellingGrade(int spellingGrade){
this.spellingGrade = spellingGrade;
}
public int getLengthGrade(){
return lengthGrade;
}
public void setLengthGrade(int lengthGrade){
this.lengthGrade = lengthGrade;
}
public int getContentGrade(){
return contentGrade;
}
public void setContentGrade(int contentGrade){
this.contentGrade = contentGrade;
}
public int getOverallGrade(){
return overallGrade;
}
public void setOverallGrade(){
int grades = grammarGrade + spellingGrade + lengthGrade + contentGrade;
this.overallGrade = grades;
}
public int getGrammarPossible(){
return grammarPossible;
}
public int getSpellingPossible(){
return spellingPossible;
}
public int getLengthPossible(){
return lengthPossible;
}
public int getContentPossible(){
return contentPossible;
}
public int getOverallPossible(){
return overallPossible;
}
}
I have four ints in the essay method but they aren't excepted in the constructor. Everything compiles.
required: int,int,int,int
The error is telling you that your constructor requires arguments (public Essay(int grammar, int spelling, int length, int content)). Right now you are trying to construct an Essay , but are not passing any arguments to it.
You need to provide those arguments, or provide a no args constructor:
public Essay(){}
Or if you wanted to initialize them all to zero and initialize the variables later:
Essay termPaper = new Essay(0,0,0,0);
How can I read-in an integer in this following program? It doesn't work. It doesn't compile at the moment.
/**
* Main class of the Java program.
*
*/
import java.util.Scanner;
//...
class Scanner{
Scanner in = new Scanner(System.in);
int num = in.nextInt();
}
public class Main {
public static void main(String[] args) {
// we print a heading and make it bigger using HTML formatting
System.out.println("<h4>-- Binaere Suche --</h4>");
int anzahl = 0; int zahl;
}
}
import java.util.Scanner;
// This will print what you want but will not make it look bigger as it
// will get printed in console
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
// we print a heading and make it bigger using HTML formatting
System.out.println("<h4>--"+num+" --</h4>");
}
}
I have to create JUnit test cases for this class. One of the tests is to test the constructor of the ShannonsTheorem class. Are there ways to test a constructor that does not have any parameters?
There is another class named ShannonsModel that also needs to have its constructor tested. According to the UML we were provided there are no parameters on that constructor either.
Thanks!
package network;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ShannonsTheorem {
ShannonsModel model = new ShannonsModel();
Scanner kb = new Scanner(System.in);
/**
* default constructor for ShannonsTheorem class.
*
*/
public ShannonsTheorem()
{
}
/**
* Method to return the value in bandwidth variable.
* #return
*/
public double getBandwidth()
{
return model.getBandwidth();
}
/**
* getSignalToNoise method to return the signalToNoise value in variable signalToNoise
* #return
*/
public double getSignalToNoise()
{
return model.getSignalToNoise();
}
/**
* main method for ShannonsTheorem
* #param args
* while loop to handle user input to continue or end program
*/
public static void main(String[] args)
{
try {
Scanner kb = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
boolean stop = false;
while(!stop) {
ShannonsTheorem ST = new ShannonsTheorem();
System.out.println("Enter bandwidth in hertz:");
ST.setBandwidth(kb.nextDouble());
System.out.println("Enter signalToNoise:");
ST.setSignalToNoise(kb.nextDouble());
System.out.println("Values are:");
System.out.println("Bandwidth");
System.out.println(ST.getBandwidth());
System.out.println("SignalToNoise:");
System.out.println(ST.getSignalToNoise());
System.out.println(ST.maxiumumDataRate());
System.out.println("Press any key to make another calculation. Type N or n to Quit");
String s = scan.nextLine();
if(s.equals("n") || s.equals("N")) {
stop = true;
} // end of if
} // end of while loop
}catch (InputMismatchException e){
System.out.println("Input Exception was caught, restart program");
}catch(NumberFormatException e){
System.out.println("Format Exception was caught, restart program");
}
}
/**
* public method to retrieve the maximum data rate. This method makes a call to the private method
* under the same name.
* #return
*/
public double maxiumumDataRate()
{
// calling to the private method maxiumumDataRate. Storing the return value from said method into variable result
// when this public method is called it will return the result from the private method,
double result = model.maxiumumDataRate();
System.out.print(model.toString());
return result;
}
/**
* setBandwidth method to set the bandwidth value in hertz
* #param h
*/
public void setBandwidth(double h)
{
model.setBandwidth(h);
}
/**
* setSignalToNoise method to set the signalToNoise variable
* #param snr
*/
public void setSignalToNoise(double snr)
{
model.setSignalToNoise(snr);
}
}
Why do you need to test the constructor ?
You could test that without any modification, the default constructor has some specific fields :
#Test
public void shouldCreateADefaultShannonTheorem() {
ShannonsTheorem shannonsTheorem = new ShannonsTheorem();
Object expectedModel = new ShannonsModel();
assertEquals(expectedModel , shannonsTheorem.model);
Object expectedKb = new Scanner(System.in);
assertEquals(expectedKb , shannonsTheorem.kb);
}
or you could test that without any change, the default constructor gives you some results :
ShannonsTheorem shannonsTheorem = new ShannonsTheorem();
double expectedbandwith = 0.0;
assertEquals(expectedbandwith , shannonsTheorem.getBandwidth(), 0);
int expectedSignalToNoise = 0;
assertEquals(expectedSignalToNoise , shannonsTheorem.getSignalToNoise(), 0);
int expectedMaximumDataRate = 0;
assertEquals(expectedMaximumDataRate , shannonsTheorem.maxiumumDataRate(), 0);
// ...
that's why it is usefull to do TDD (test first) :
what your application should do ? write the test. // here is the thinking
write the code. // no thinking here !
refactor
I want to run a method that returns an array. Code such as this:
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println(
"Please input the integer for position " + (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
I have researched that you can make a variable like so int[] data = getArray();
How would I make it so that data can be accessible to other methods in the same class so I could do something like
public static int linearSearch(data) {
}
without having to constantly be re-entering the values for the array?
You can try out to introduce private variable of int[] and provide a lazy initialization for it, something like this:
class aClass {
int[] data; // default to the null
private int[] getArray() {
if (data == null) {
// your console logic for initialization
}
return data;
}
public static int linearSearch() {
int[] localData = getArray();
}
}
But in this case you can change the contents of data field in your methods across the class.
This can be done two ways:
- Either declaring the variable as class-level variable
- Or declaring it as local variable inside main method
public class ReturnIntArraysSO {
/**
* #param args
*/
public static void main(String[] args) {
int[] data = getArray();
for(int i : data){
System.out.print(i+" ");
}
linearSearch(data);
}
/**
*
* #return
*/
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Please input the integer for position "
+ (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
/**
*
* #param data
* #return
*/
public static void linearSearch(int[] data) {
for(int a : data){
if(a == 5){
System.out.println("\nFound 5!!");
}
}
}
}
You need to declare i your array like this:
public YourClass {
public static int[] square = new int[5];
}
This way you can access this array from any other class and it will remain with the exact array (that's what static for). Example:
From Class1 - YourClass.square
From Class2 - YourClass.square
Both are the same array instance
import java.util.Scanner;
/**
* #(#)wefeqwrf.java
*
* wefeqwrf application
*
* #author
* #version 1.00 2013/11/15
*/
public class wefeqwrf {
public static void main(String[] args) {
// TODO, add your application code
Scanner scan= new Scanner(System.in);
String number = "000";
String a;
int count=0;
for(int i=0;a!="-1";i++)
{
for(int k=0;k<3;k++){
a=scan.next();
a.charAt(0)= number.charAt(k);
if(number.equals("110"))
{
System.out.print("Tebrikler!=110");
count++;
}
else
{
System.out.print("Maalesef olmadı:" + number);
}
}
}
}
}
It gives the error:
error: unexpected type at this code: `a.charAt(0)= number.charAt(k);`
how can I assign the content of a to the specified index of number?
and when I changed the string a to the char a scan.next() does not work why and what can I do is there a any scanner method for char?
You should do it this way:
a = number.charAt(k) + a.substring(1);
You can't assign something to a method. Methods only return something.