I'm really new to Java programming and I have an assignment due for my AP Computer Programming class, so bear with me. I have to figure out how to multiply two fractions together. I was wondering if there was any way to declare a variable inside a method and use it outside that method (my while loop in the intro method). Thank you, hope that wasn't confusing!
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3 {
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args){
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for input
intro();
}
public static void intro(){
Scanner input = new Scanner(System.in);
String user= input.nextLine();
while (!user.equals("quit") & input.hasNextLine()){ //processes code when user input does not equal quit
StringTokenizer chunks = new StringTokenizer(user, " "); //parses by white space
String fraction1 = chunks.nextToken(); //first fraction
String operand = chunks.nextToken(); //operator
String fraction2 = chunks.nextToken(); //second fraction
System.out.println("Fraction 1: " + fraction1);
System.out.println("Operation: " + operand);
System.out.println("Fraction 2: " + fraction2);
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for more input
while (user.contains("*")){
parse(fraction1);
parse(fraction2);
System.out.println("hi");
int num = num1 * num2;
int denom = denom1 * denom2;
System.out.println(num + "/" + denom);
user = input.next();
}
}
}
public static void parse(String fraction) {
if (fraction.contains("_")){
StringTokenizer mixed = new StringTokenizer(fraction, "_");
int wholeNumber = Integer.parseInt(mixed.nextToken());
System.out.println(wholeNumber);
String frac = mixed.nextToken();
System.out.println(frac);
StringTokenizer parseFraction = new StringTokenizer(frac, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}
else if (!fraction.contains("_") && fraction.contains("/")){
StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}else{
StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
int num = Integer.parseInt(whiteSpace.nextToken());
System.out.println(num);
}
}}
This short answer is "no". Others have already explained why... but here's two possible alternatives. I don't know if you've learned these concepts yet, but the first alternative has to do with passing by reference vs. passing by value, and the second alternative has to do with object-oriented programming.
Alternative #1:
You can declare a variable outside a method, pass it to the method and use it, and then the variable is available outside the method because it was declared outside the method. I think an example will help make this more clear:
void foo () {
Integer a = 1;
Integer b = 2;
bar(a,b);
System.out.println("a = " + a + ", b = " + b);
}
void bar (Integer a, Integer b) {
a = 4;
b = 8;
}
And the result should be a = 4, b = 8. However, it's very important to note that this works because Integer (unlike int) is a class so its objects are passed by reference. If a and b were just ints, then they would be passed by value. That means that bar() would have it's own copy of a and b separate from foo()'s, and modifications to the variables within bar() would not affect foo()'s copies. For example:
void foo () {
int a = 1;
int b = 2;
bar(a,b);
System.out.println("a = " + a + ", b = " + b);
}
void bar (int a, int b) {
a = 4;
b = 8;
}
This would produce the result a = 1, b = 2.
I don't really like this method because it's pretty ugly and easy to make a mistake, but it is possible and will work if done correctly. Plus if you're not doing object-oriented code, your choices may be this or just don't use a function for that part (which is not usually good design). Although this kind of thing is much more common in languages like C and C++. But those languages are more explicit about pass by value or reference, and you have to manipulate pointers manually (whereas Java hides its pointers from the programmer), so it's harder to get confused about when something will be passed by value or reference (though easier to make other kinds of mistakes).
Alternative #2:
This would be my preference, given the choice, but only if you've learned some about object-oriented programming. If you haven't learned that yet, I'd go with another approach (but feel free to read on if you're curious).
I would create a fraction class that has member variables for the numerator and denomonator (and whole number part if you're required to support that - although personally I'd reduce fractions with whole number parts to just numerator and denomonator anyhow, because that's how I do math). Then I'd make a constructor that takes a String parameter, and the body of that constructor would work much like your parse() method. So that would let you do something like this...
String strFractionString = /* initialize the string, e.g., reading from input */
Fraction myFrac = new Fraction(strFractionString); // parses string and assigns num & denom
System.out.println("My Fraction: " + myFrac.numerator + "/" + myFrac.denominator);
Nope, the scope of the variable will be limited to the method you created it in.
You'll have to declare the variable outside of that method, if you want to use it outside that method.
Here's a helpful resource on variable scope.
Assuming that you want the function parse() to return both a numerator and a denominator, there are several ways to accomplish this.
The OO way is to define a class that has two fields, a numerator and a denominator, and have parse() return an instance of this type
class Fraction {
public int Numerator = 0;
public int Denominator = 1;
public Fraction(int numerator, int denominator) {
Numerator = numerator;
Denominator = denominator;
}
public static Fraction parse(String fractionString) {
int num, denom;
// Your parse code (without the int num and int denom declarations) goes here.
return new Fraction(num, denom);
}
}
Your calling code would look like this:
Fraction f1, f2;
f1= Fraction.parse(fraction1);
f2= Fraction.parse(fraction2);
int num = f1.Numerator * f2.Numerator;
int denom = f1.Denominator * f2.Denominator;
Variables declared inside a method are encapsulated as local variables and can't be used outside the method.
If you wanted to use say the String frac do this
public class javatest3 {
static String frac;
public static void main(String[] args){
// now you can use frac here
}
public static void parse(String fraction) {
if (fraction.contains("_")){
...
frac = mixed.nextToken();
}
}
}
Just declare the variable outside of any methods. Make sure and make the variable static. Then just initialize in the method. That way it can be used in any of the methods inside that class. Here's an example of how you'd do that.
package testPackage;
public class Test {
public static int waffle = 5;
public static void main(String[] args) {
method1();
method2();
}
public static void method1() {
System.out.println("Heyy Everyone");
System.out.println("Waffle is " + waffle); // Print waffle before change
waffle = waffle + 12 - 4; // Change waffle;
System.out.println("Method 1 set waffle to " + waffle); // Print waffle after change after
} // change in method2
public static void method2() {
System.out.println("Waffle is " + waffle); // Print waffle in method2 after method1's change
waffle = waffle * 3; // Change waffle
System.out.println("Waffle is now set to " + waffle);// Print waffle/ after change in method2
}
}
Your original code prints and separates the fractions and operands. The assignment we have right now in AP CS requires us to separate the fractions into a numerator, operand, and demoninator. It would look something like this.
StringTokenizer st= new StringTokenizer (input);
And then use your find(); method to call each part in
Here is my code to multiply the fraction. More simpl, hopefully will answer your question.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3
{
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args)
{
javatest3 javatest3 = new javatest3();
System.out.println("Enter an expression (or \"quit\"): "); // prompts
// user for
// input
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] array = null;
try {
array = in.readLine().trim().split(" ");
/*
* I get the array[0] and array[2], it because 2/3 * 3/4
* 2/3 is array[0], * is array[1] and 3/4 is array[2]
*/
String[] arrayX = array[0].split("/");
String[] arrayY = array[2].split("/");
String result = javatest3.multiplyFaction(
Integer.valueOf(arrayX[0]), Integer.valueOf(arrayY[0]),
Integer.valueOf(arrayX[1]), Integer.valueOf(arrayY[1]));
System.out.println("Result: " + result);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// intro();
}
private String multiplyFaction(int x1, int y1, int x2, int y2)
{
int mf1 = x1 * y1;
int mf2 = x2 * y2;
return String.valueOf(mf1) + "/" + String.valueOf(mf2);
}
// public static void intro()
// {
// Scanner input = new Scanner(System.in);
// String user = input.nextLine();
// while (!user.equals("quit") & input.hasNextLine()) { // processes code
// // when user
// // input does
// // not equal
// // quit
// StringTokenizer chunks = new StringTokenizer(user, " "); // parses
// // by
// // white
// // space
// String fraction1 = chunks.nextToken(); // first fraction
// String operand = chunks.nextToken(); // operator
// String fraction2 = chunks.nextToken(); // second fraction
// System.out.println("Fraction 1: " + fraction1);
// System.out.println("Operation: " + operand);
// System.out.println("Fraction 2: " + fraction2);
// System.out.println("Enter an expression (or \"quit\"): "); // prompts
// // user
// // for
// // more
// // input
//
// while (user.contains("*")) {
// parse(fraction1);
// parse(fraction2);
// System.out.println("hi");
// int num = num1 * num2;
// int denom = denom1 * denom2;
// System.out.println(num + "/" + denom);
// user = input.next();
//
// }
//
// }
// }
// public static void parse(String fraction)
// {
// if (fraction.contains("_")) {
// StringTokenizer mixed = new StringTokenizer(fraction, "_");
// int wholeNumber = Integer.parseInt(mixed.nextToken());
// System.out.println(wholeNumber);
// String frac = mixed.nextToken();
// System.out.println(frac);
// StringTokenizer parseFraction = new StringTokenizer(frac, "/"); // parses
// // by
// // forward
// // slash
// int num = Integer.parseInt(parseFraction.nextToken());
// System.out.println(num);
// int denom = Integer.parseInt(parseFraction.nextToken());
// System.out.println(denom);
//
// }
// else if (!fraction.contains("_") && fraction.contains("/")) {
// StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); // parses
// // by
// // forward
// // slash
// int num = Integer.parseInt(parseFraction.nextToken());
// System.out.println(num);
// int denom = Integer.parseInt(parseFraction.nextToken());
// System.out.println(denom);
//
// }
// else {
// StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
// int num = Integer.parseInt(whiteSpace.nextToken());
// System.out.println(num);
// }
// }
}
Related
In this Java program, I want to input values from the keyboard and check if the variable contains a certain digit.
I'm using contains method to find out if a variable contains a particular digit.
There is an error when I write the code. Can someone please explain the error and how to fix it?
The code:
package nested_package;
import java.util.Scanner;
public class Age_prog {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("a=" + a + "\n" + "b=" + b);
if (a.contains(1)) { // ERROR IN THIS LINE
System.out.println("true");
} else {
System.out.println("false");
}
}
}
String has contains method, you are trying to invoke contains on int type
that is causing compilation error
you can either change input type to string and check contains or get number and check if its digits has the digit you are looking for
String s = sc.nextLine(); // e.g "120";
s.contains("1");
If a is an Integer or int and you need to parse each digit of the number to see if there's a certain digit you should transform the number into a String and then parse it:
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("a=" + a + "\n" + "b=" + b);
String numberToString = String.valueOf(a);
if (numberToString.contains("1")) {
System.out.println("true");
} else {
System.out.println("false");
}
sc.close();
The reason why your compiler complains is -- int (and Integer) in Java doesn't have a method named contains(). That method belongs to the String class.
One approach is to convert your numbers to String and use the contains method.
Another approach -- you can write your contains method that gets two integers and return a boolean (I named it containsDigit to avoid confusion).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("a=" + a + "\n" + "b=" + b);
System.out.println(containsDigit(a, 1));
}
private static boolean containsDigit(int a, int b) {
while (a > 0) {
if (a % 10 == b) {
return true;
}
a /= 10;
}
return false;
}
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("a=" + a + "\n" + "b=" + b);
if (Integer.toString(a).contains(""+1)) { //
System.out.println("true");
} else {
System.out.println("false");
}
Integer.toString(a) converts a to a string
contains takes a string value of the digit
if you have a digit you can prepend "" to convert a string (as I did above), or specify as a string outright as "1".
So, I have coded everything, but return statement isn't returning or printing out anything in the output. The return statement is in my calAverage method. And the output should look like this https://gyazo.com/328bcfebfb08709edbc0e62a93ada7f8 but I have everything but the calAverage output. I don't get what I did wrong. I know I have to call the method like this: sc.calAverage(a, b, c); and then assign the return value to a variable and the print it out but I don't know how to do it with the calAverage method since it has three arguments.
import java.util.Scanner;
public class SecretCode
{
//no instance variables
public SecretCode(){
}
public double calAverage(int a, int b, int c){
double average = 0.0;
//your work - step 2
average = (a + b + c) / 3.0;
return average;
}
public void decodeMe(String s1){
//your work here step 4
//This method will take in a String and then process the string to produce output withe the following rules:
// The first 5 characters are needed but must be uppercase()
// The first integer will decrease by 121
// The last number only takes the last 2 decimals
// Print out 3 lines of data as followed:
// XXXXX
// XXX
// XX
String s = "Delta 230 ATA 23.75";
s1 = s.substring(0, 5);
String s2 = s1.toUpperCase();
int wholeNumber = Integer.parseInt(s.substring(6, 9));
int finalNumber = wholeNumber - 121;
int lastNumber = Integer.parseInt(s.substring(17,19));
System.out.println(s2 + "\n" + finalNumber + "\n" + lastNumber);
}
public static void main(String args[]){
int a, b, c;
String s;
SecretCode sc = new SecretCode();
Scanner myObj = new Scanner(System.in);
System.out.println("Enter 3 numbers separated by space ");
//your work step 3
// receive 3 integer values and call calAverage() method
// print out the average
a = myObj.nextInt();
b = myObj.nextInt();
c = myObj.nextInt();
sc.calAverage(a, b, c);
//
Scanner myObj1 = new Scanner(System.in);
System.out.println("Enter a secret code below ");
//Step enter the code: Delta 230 ATA 23.75
s = myObj1.nextLine();
sc.decodeMe(s);
//
}
}
You should change
sc.calAverage(a, b, c)
to
double avg = sc.calAverage(a, b, c)
System.out.println(avg);
in your main method if you want to print the value returned by the calAverage method.
Or print the average after calculating it in the method calAverage.
public double calAverage(int a, int b, int c) {
double average = 0.0;
//your work - step 2
average = (a + b + c) / 3.0;
System.out.println(average);
return average;
}
Save the response of the function in a variable:
double averageValue = sc.calcAverage(5, 3, 2);
This question already has an answer here:
What does "possible lossy conversion" mean and how do I fix it?
(1 answer)
Closed 3 years ago.
Help? I don't know why I am getting this error. I am getting at in line 39:
term[1] = differentiate(Coeff[1], exponent[1]);
How can I fix this issue?
Full code listing:
public class Calcprog {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numTerms = 7;
double[] Coeff = new double[6];
double[] exponent = new double[6];
String[] term = new String[6];
System.out.println("Enter the number of terms in your polynomial:");
numTerms = input.nextInt();
while (numTerms > 6) {
if (numTerms > 6) {
System.out.println("Please limit the number of terms to six.");
System.out.println("Enter the number of terms in your polynomial:");
numTerms = input.nextInt();
}
}
for (int i = 1; i < numTerms + 1; i++) {
System.out.println("Please enter the coefficient of term #" + i + " in decimal form:");
Coeff[i] = input.nextDouble();
System.out.println("Please enter the exponent of term #" + i + " in decimal form:");
exponent[i] = input.nextDouble();
}
term[1] = differentiate(Coeff[1], exponent[1]);
}
public String differentiate(int co, int exp) {
double newco, newexp;
String derivative;
newexp = exp - 1;
newco = co * exp;
derivative = Double.toString(newco) + "x" + Double.toString(newexp);
return derivative;
}
}
You are trying to pass double arguments to a method that accepts ints, which requires a casting that may result in loss of information.
You can make it work by an explicit cast :
term[1] = differentiate((int)Coeff[1], (int)exponent[1]);
Or you can change your differentiate method to accept double arguments, which would probably make more sense :
public String differentiate(double co, double exp)
your method is not static, and you calling in the main which is static, remember a non static method can be access direct in a static method, you have to create an instance of the class to access that method, and also the parameter you are passing is double and not int. Your method should be like that public static String differentiate(double co, double exp){
change the argument types of the differentiate method to double. This should then look as follows
public String differentiate(double co, double exp){
...
}
I have a question about multiple instances of a constructor in Java.
My assignment is to receive two fractions and then multiply and divide those fractions.
I am unsure as to how to go about having separate values for the instances of the class objects themselves.
Here is the sample code of where I am having the issue:
import java.util.Scanner;
public class TextLab05
{
static int num1, den1; // numerator and denominator of the 1st rational number
static int num2, den2; // numerator and denominator of the 2nd rational number
public static void main (String args[])
{
enterData();
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
}
}
class Rational
{
private int firstNum; // entered numerator
private int firstDen; // entered denominator
private int num; // reduced numerator
private int den; // reduced denominator
public Rational()
{
}
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
//Here specifically is where I am having comprehension issues. How can I include num2 and den2 if I only have int n and int d?
}
}
If this is hard to understand out of context, here is the entire starting code I was given:
import java.util.Scanner;
public class TextLab05
{
static int num1, den1; // numerator and denominator of the 1st rational number
static int num2, den2; // numerator and denominator of the 2nd rational number
public static void main (String args[])
{
enterData();
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
Rational r3 = new Rational();
r3.multiply(r1,r2);
System.out.println("\n\n" + r1.getOriginal() + " * " + r2.getOriginal() + " = " + r3.getRational());
r3.divide(r1,r2);
System.out.println("\n" + r1.getOriginal() + " / " + r2.getOriginal() + " = " + r3.getRational());
// 100 Point Version Only
// r3.add(r1,r2);
// System.out.println("\n" + r1.getOriginal() + " + " + r2.getOriginal() + " = " + r3.getRational());
// r3.subtract(r1,r2);
// System.out.println("\n" + r1.getOriginal() + " - " + r2.getOriginal() + " = " + r3.getRational());
System.out.println();
}
public static void enterData()
{
Scanner input = new Scanner(System.in);
System.out.print("\nEnter the 1st numerator ----> ");
num1 = input.nextInt();
System.out.print("\nEnter the 1st denominator --> ");
den1 = input.nextInt();
System.out.print("\nEnter the 2nd numerator ----> ");
num2 = input.nextInt();
System.out.print("\nEnter the 2nd denominator --> ");
den2 = input.nextInt();
}
}
class Rational
{
private int firstNum; // entered numerator
private int firstDen; // entered denominator
private int num; // reduced numerator
private int den; // reduced denominator
public Rational()
{
}
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
private int getGCF(int n1,int n2)
{
int rem = 0;
int gcf = 0;
do
{
rem = n1 % n2;
if (rem == 0)
gcf = n2;
else
{
n1 = n2;
n2 = rem;
}
}
while (rem != 0);
return gcf;
}
public int getNum()
{
return TextLab05.num1;
}
public int getDen()
{
return TextLab05.den1;
}
public double getDecimal()
{
return (double)TextLab05.num1 / TextLab05.den1;
}
public String getRational()
{
String rational = "" + TextLab05.num1 + "/" + TextLab05.den1;
return rational;
}
public String getOriginal()
{
String original = "" + TextLab05.num1 + "/" + TextLab05.den1;
return original;
}
public void reduce()
{
}
public void multiply(Rational r1, Rational r2)
{
}
public void divide(Rational r1, Rational r2)
{
}
public void add(Rational r1, Rational r2)
{
}
public void subtract(Rational r1, Rational r2)
{
}
}
When you call:
Rational r1 = new Rational(num1, den1);
Rational r2 = new Rational(num2, den2);
in the main method of your program you are creating two instances of the Rational class, one named r1 and one named r2. Because you are passing int values to the Rational constructors, the constructor that will be called is the constructor which requires two integer arguments:
public Rational(int n, int d)
{
...
}
The compiler knows this because it matches the name of the Constructor as well as the types of the arguments passed (known as matching the "signature" of the Constructor).
In the code you have provided, the Rational Constructor code doesn't really make sense - this code:
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
should probably look something like this:
public Rational(int n, int d)
{
this.firstNum = n;
this.firstDen = d;
}
The values n and d are passed to the constructor, and then in the body of the constructor the instance variables firstNum and firstDen (which are declared in the private part of the Rational class and effectively "belong" to the instance being created) would then be initialised to the values of n and d.
Everywhere within the body of the Rational class you should refer to the member variables firstNum and firstDen, rather than variables that do not "belong" to the class instance.
I assume the Rational class is supposed to represent a rational number. You say:
//Here specifically is where I am having comprehension issues. How can I include num2 and den2 if I only have int n and int d?
You don't need to store two numerators and two denominators in the Rational class. You just need to creat two Rational objects. One to store num1 and den1, the other to store num2 and den2. You are already doing this:
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
It does not make sense to store two numerators and two denominators in Rational. A rational number only has one of each.
In summary: r1 stores num1 and den1, while r2 stores the other two. When you create a new Rational, n and d refer to the numerator and denominator of that particular instance you are creating.
I am not sure if your implementation of Rational is what you intend, but the constructor is not limited to local varables, it can access any static variables from other classes it can access.
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
n and d are local variables, num1 and den1 are static variables in class TextLab05.
So you are assigning the local variables with the static values from the other class.
The code doesn't make sense, as you don't do anything with the values after assigning them to local variables that are disposed when the method ends.
The most important thing to do is understand the concept. You are going to store a rational number in your Rational class. When you do this:
Rational r1 = new Rational(num1,den1);
You are making a single instance of a Rational and naming it r1. r1 should now contain a numerator and a denominator (in this case num1 and den1).
Let's say you want to make the number one half, or 1/2. You could do this:
Rational oneHalf = new Rational(1,2);
Realize that new Rational(1,2) is calling the constructor of your Rational class. In your constructor you need to assign num and den to the passed values (in this case 1 and 2). So you would need something like this:
this.num = num1;
this.den = den1;
So if you want to have the ability to multiply one Rational with another Rational you would need a method or function to do that. In your Rational class, create a method called multiply(Rational anotherRational).
That function would do something like this:
this.num = this.num * anotherRational.num;
this.den = this.den * anotherRational.den;
I gave away half the answer, I'll let you do the rest. Don't just copy what you find here, think about what you're doing.
I am trying to use one file to create a menu in the command window. The user selects from those menu options. They are prompted to enter a number. The number is passed to two overloaded methods which determine if the number is an integer or a float. After the calculation is done the result is printed to the screen and the menu reappears. Here is the code from my two files.
MyMathOpsTest class:
import java.util.Scanner; // import Scanner class
public class MyMathOpsTest
{
//method to pause until a key is pressed
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}//end pause
public static void main( String args[] )
{
//variables to capture keyboard input
Scanner keyBd = new Scanner( System.in );
char selection;
//int selection;
do{//display menu
System.out.println( "1. Square a Number");
System.out.println( "2. Cube a Number");
System.out.println( "3. Raise a Number to a Power");
System.out.println( "4. Maximum of Three Numbers");
System.out.println( "5. Minimum of Three Numbers");
System.out.println( "6. Exit");
System.out.print( "Selection[1-6]: " );
//get menu selection
selection = keyBd.next().charAt(0);
//selection = keyBd.nextInt();
//process menu selection
switch (selection){
case '1':
MyMathOpsTest.squareTheNumber();
pause();
break;
case '2':
MyMathOpsTest.cubeTheNumber();
pause();
break;
case '3':
MyMathOpsTest.raiseTheNumber();
pause();
break;
case '4':
MyMathOpsTest.maximumNumber();
pause();
break;
case '5':
MyMathOpsTest.minimumNumber();
pause();
break;
case '6':
//recognize as valid selection but do nothing
break;
default :
System.out.printf("%c\n",7);
System.out.println("Invalid Selection");
}//end switch
}while( selection != '6');
} // end method main
public static void squareTheNumber()
{
}
public static void cubeTheNumber()
{
}
public static void raiseTheNumber()
{
}
public static void maximumNumber()
{
MyMathOps.maximum();
}
public static void minimumNumber()
{
}
} // end class MyMathOpsTest
MyMathOps class:
import java.util.Scanner;
public class MyMathOps
{
public static int square(x:Integer):Integer
{
}
public static double square(x:Double):Double
{
}
public static int cube(x:Integer):Integer
{
}
public static double cube(x:Double):Double
{
}
public static int maximum(x:Integer, y:Integer, z:Integer):Integer
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three integer values separated by spaces: ");
int numberl = input.nextInt();
// read first integer
int number2 = input.nextInt();
// read second double
int number3 = input.nextInt();
// read third double
// determine the maximum value
int result = maximum( numberl, number2, number3 );
// display maximum value
System.out.println( "Maximum is: " + result );
} // end method maximum
public static double maximum(x:Double, y:Double, z:Double):Double
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three floating-point values separated by spaces: ");
number1 = input.nextDouble();
// read first double double
number2 = input.nextDouble();
// read second double
double number3 = input.nextDouble();
// read third double
// determine the maximum value
double result = maximum( numberl, number2, number3 );
// display maximum value
System.out.println( "Maximum is: " + result );
} // end method maximum
public static int minimum(x:Integer, y:Integer, z:Integer):Integer
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three integer values separated by spaces: ");
int numberl = input.nextInt();
// read first integer
int number2 = input.nextInt();
// read second double
int number3 = input.nextInt();
// read third double
// determine the minimum value
int result = minimum( numberl, number2, number3 );
// display minimum value
System.out.println( "Minimum is: " + result );
} // end method minimum
public static double minimum(x:Double, y:Double, z:Double):Double
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
// obtain user input
System.out.print( "Enter three floating-point values separated by spaces: ");
number1 = input.nextDouble();
// read first double double
number2 = input.nextDouble();
// read second double
double number3 = input.nextDouble();
// read third double
// determine the minimum value
double result = minimum( numberl, number2, number3 );
// display minimum value
System.out.println( "Minimum is: " + result );
} // end method minimum
} // end class MyMathOps
This code is a combination of code I type myself and example code from my text book. This will not compile for me in jGRASP. I get these errors.
MyMathOps.java:10: <identifier> expected
public static int square(x:Integer):Integer
^
MyMathOps.java:96: ')' expected
} // end method minimum
^
2 errors
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
What am I doing wrong here? I have spent hours working on this and reading in my textbook. If I do not get this right. I will get a bad grade. I need to get a good grade in this class so I can get into a top notch Computer Science University. Thanks for your help.
In the unlikely event that my instructor or any administrator from Salt Lake Community College ever comes across this question, let me make my intentions clear. This question is posted in the greatest spirit of academic honesty. I ask this question to seek general advice and help in understanding the proper way to use the Java programming language. I in no way use the work of others and represent it as my own work. I use the answers provided here as a general aid in my understanding. I do all my own work and do not copy work provided by people answering my question.
The lines like this are not valid Java syntax:
public static int square(x:Integer):Integer
public static int maximum(x:Integer, y:Integer, z:Integer):Integer
...
This looks like a UML or pseudo-code syntax. "x:Integer" is "language-agnostic" notation that means that x is an Integer type (which maps to an int or Integer object in Java). The ":Integer" at the end means that the method returns an Integer type, which you are doing correctly already.
Try changing all your method declarations to look like this:
public static int square(int x) // Or "Integer x" if you want to use the Integer class, rather than the primitive int
public static int maximum(int x, int y, int z)
....
I am guessing that you are used to Pascal (or a derivative).
public static int square(x:Integer):Integer
in Java that is
public static int square(int x)
Also since the code is inside of "MyMathOpsTest" you do not need to prefix the method calls with "MyMathOpsTest.".
Also, why call it "MyMathOps" instead of "MathOperationsTest"? Of course it is yours - it doesn't be long to me or anyone else! Pick names that have meaning, try to avoid shorthands like "Ops", unless it is common for the field you are working in (URL is a good one, "Ops" isn't).
And now for the generl programming advice for a beginner:
write a single line of code
get that line of code to compile
once that line of code compiles work on the next one
get the next line of code to compile
keep doing that until the program is done.
There is no point in making the same mistakes over and over again - all you get good at is making mistakes, and that isn't much fun.
So to get you started...
Step 1:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
}
}
(compile the above code)
Step 2:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
final Scanner input;
}
}
(compile the above code)
Step 3:
public class MathOperations
{
public static int maximum(final int x, final int y, final int z)
{
final Scanner input;
intput = new Scanner(System.in);
}
}
(compile the above code)
and then keep going one line at a time. Once you get the hang of it you can do more than one line, but at the start, doing it one line at a time will show you immediately when you make a mistake. Make sure that you fix ALL of the mistakes before you move on to the next line.
Also, at the end of the first method pause(), you need another curly brace:
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}<-- this one is missing in yours
Hope this helps!
I don't know what the point of the exercise is - the math ops, the overloading, or the menu. But I'd recommend that you start over with these as your basis. At least they compile and run:
public class MyMathOps
{
public static int square(int x)
{
return x*x;
}
public static double square(double x)
{
return x*x;
}
public static int cube(int x)
{
return x*x*x;
}
public static double cube(double x)
{
return x*x*x;
}
public static int maximum(Integer... values)
{
Integer maxValue = Integer.MIN_VALUE;
for (Integer value : values)
{
if (value.compareTo(maxValue) > 0)
{
maxValue = value;
}
}
return maxValue;
}
public static double maximum(Double... values)
{
Double maxValue = Double.MIN_VALUE;
for (Double value : values)
{
if (value.compareTo(maxValue) > 0)
{
maxValue = value;
}
}
return maxValue;
}
public static int minimum(Integer... values)
{
Integer minValue = Integer.MAX_VALUE;
for (Integer value : values)
{
if (value.compareTo(minValue) < 0)
{
minValue = value;
}
}
return minValue;
}
public static double minimum(Double... values)
{
Double minValue = Double.MIN_VALUE;
for (Double value : values)
{
if (value.compareTo(minValue) < 0)
{
minValue = value;
}
}
return minValue;
}
}
and the test class (simplified):
public class MyMathOpsTest
{
public static void main(String args[])
{
Integer [] intValues = { 1, 2, 3, };
Double [] doubleValues = { 11.0, 14.0, -6.0 };
for (Integer value : intValues)
{
System.out.println("value : " + value);
System.out.println("squared: " + MyMathOps.square(value));
System.out.println("cubed : " + MyMathOps.cube(value));
System.out.println("min : " + MyMathOps.minimum(intValues));
System.out.println("max : " + MyMathOps.maximum(intValues));
}
for (Double value : doubleValues)
{
System.out.println("value : " + value);
System.out.println("squared: " + MyMathOps.square(value));
System.out.println("cubed : " + MyMathOps.cube(value));
System.out.println("min : " + MyMathOps.minimum(doubleValues));
System.out.println("max : " + MyMathOps.maximum(doubleValues));
}
}
}
When this is done running, you'll know that your methods are correct. Spare yourself the difficulties of reading in values on the first try.