How can I use get methods in an Array? - java

This assignment is comprised of creating a program to read up to (but not more) 25 test grades, then report the number of grades entered; and compute the arithmetic mean (average) and standard deviation of the grades. I don't understand how to use the get methods I have created so I can implement it in my program. Here is my code so far
package my.meancalculator;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class MeanCalcUI extends javax.swing.JFrame {
private double average;
private double stdDeviation;
public double[] gradeArray;
public int numElem;
public double sum;
public int i;
public double numGrades;
public MeanCalcUI() {
initComponents();
}
public double getAverage(double[] gradeArray, int numElem) {
double sum = 0;
for (int i = 0; i < numElem; i++) {
sum = sum + gradeArray[i];
}
return (sum / numElem);
}
public double getStdDev(double[] gradeArray, int numElem, double average) {
double sum = 0;
for (int i = 0; i < numElem; i++) {
sum = sum + Math.pow((gradeArray[i] - average), 2);
}
return Math.sqrt(sum / numElem);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void btnEnterGradesActionPerformed(java.awt.event.ActionEvent evt) {
gradeArray = new double[25];
JFrame frame = new JFrame();
boolean enterGrades = true;
while (enterGrades) {
try {
String gradeInput = JOptionPane.showInputDialog(frame,
"Enter Grade",
"Enter Grade",
JOptionPane.PLAIN_MESSAGE);
if ((gradeInput != null) && (gradeInput.length() > 0)) {
gradeArray[i] = Double.parseDouble(gradeInput);
average = getAverage;
numElem = numGrades + 1; //right here I know it doesn't work but i have no idea on how to make it the total of the grades entered. numElem is what the sum is getting divided by to find the average
txtNumGrades.setText((numGrades) + "");
txtMean.setText(average);
txtStdDeviation.setText(stdDeviation);
} else {
enterGrades = false;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame,
"Your input must be numeric!",
"Bad Data!",
JOptionPane.ERROR_MESSAGE);
}
}
}
Also, I don't know how I can make another catch block in case the user enters more than 25 grades. Here is my program guidelines from my teacher so you can have a better understanding on what it looks like and what is exactly being asked. http://homepages.uc.edu/~thomam/OOProg_1/assignment5.html
Can you guys help me out?
EDIT: Another question. How can I make the variable numElem work? I don't know how I can make that equal to the sum of all the grades entered.

The main problem you are asking about is trying to access those other methods you wrote, like getAverage(). You need to always pass those methods parameters; a name without parentheses after it is treated as just a variable, but through the magic of syntax the moment you put some parentheses with parameters, it becomes a method call: getAverage(gradeArray, numberOfGradesInput).
That said, there are faster ways to do most of what you're working on.
////////// CLASS FIELDS //////////
private double[] gradeArray = new double[25];
private int numberOfGradesInput = 0;
// You do not need any other fields! None! This is all you need to remember!
////////// BUTTON PRESSED //////////
if (numberOfGradesInput == 25) {
// We've already finished entering the max # of grades
JOptionPane.showMessageDialog(frame,
"You've already entered the maximum of 25 grades.",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
do {
String gradeInput = JOptionPane.showInputDialog(frame,
"Enter Grade",
"Enter Grade",
JOptionPane.PLAIN_MESSAGE);
// When we receive empty/null input, we're done entering grades
if (gradeInput == null || gradeInput.length() == 0) break;
double gradeValue = 0d; // Set to avoid 'may be unset' compiler error
try {
gradeValue = Double.parseDouble(gradeInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame,
"Your input must be numeric!",
"Bad Data!",
JOptionPane.ERROR_MESSAGE);
continue; // start over again
}
// Put the grade into the array and update the number of grades entered
gradeArray[numberOfGradesInput] = gradeValue;
numberOfGradesInput++;
// Add to the grade total
txtNumGrades.setText(Integer.toString(numberOfGradesInput));
// ---> You should look at using a number formatter so you don't get a million digits
double gradeAverage = getAverage(gradeArray, numberOfGradesInput);
txtMean.setText(Double.toString(gradeAverage));
double standardDeviation = getStdDev(gradeArray, numberOfGradesInput, gradeAverage);
txtStdDeviation.setText(Double.toString(standardDeviation));
} while (numberOfGradesInput < 25);
This code should work a bit more smoothly. Notice how it keeps track of the total number of grades input in numberOfGradesInput and only loops until either a blank entry is encountered or it's reached its maximum. Using enterGrades to track whether you're in the loop works, but the break statement is a much faster, cleaner, and more readable way to do it.
I must warn you to be extremely cautious of your fields! You are declaring a bunch of public fields at the top, then using them as local variables and loop variables. You are even hiding some of these variables with parameter names:
public int numElem;
-vs-
public double getAverage(double[] gradeArray, int numElem) {
This should be avoided to maintain clean code and avoid bugs. The best way to do it is to avoid using public fields whenever possible. By and large, if you only need a value in a certain method once at a time and don't need to remember it in between executions, it should not be a field, let alone a public one. Use instance variables inside your method instead! If possible, create these variables only inside their own loop rather than reusing them. Think of it this way: the farther away a variable can be touched, the more can go wrong. A quick example:
You defined the field public int i;. Let's say you're using that as a loop variable in getAverage(): for (i = 0; i < numElements; i++) {. Now, you also want to use a loop in a method called, say, enterGrades():
for (i = 0; i < 25; i++) {
getAverage(gradeArray, i);
}
Every time you jump over to getAverage(), it's messing with the exact same value you're trying to use to control the other loop you're already in. Problems will occur!
Again, if you don't need variables outside their loop, define them inside it: for (int i = 0; .... If you need to know what number it ended on, just define a local variable right before the loop. And even if you aren't using them, defining fields like public int i when you are accustomed to using those names for loops etc. is just inviting disaster: if you forget to define your local variable i, your IDE probably won't warn you that you're using the public field.
Best of luck.

This line of code:
average = getAverage; // from your if((gradeInput != null) && (gradeInput.length() > 0)) block;
The "getAverage(args)", the average = getAverage() <-- requires parameters to be passed into the method for further operation;
Replace "args" in the brackets with the parameters it requires and it should work;

Related

Finding mode of numbers taken from an input file WITHOUT array

First, I have an input file with 11 (or less) lines of numbers.
Part of my assignment is to find the mode ( number that appears the most ) WITHOUT using arrays. I have tried to use for loops or if loops after finding the amount of lines in my input file. I know it sounds stupid to do this without arrays, but I am not allowed to use arrays in this assignment.
Since I made variables ( earnedGrade1, earnedGrade2, earnedGrade3, etc. ) for each number that is pulled from the input file, I'm not sure how to compare the numbers without using consecutive if statements ( as shown in example below ).
//Assume count has been declared and initialized to 0
//Assume earnedGrade1/2/3 has been intialized with the numbers
pulled from input file
if(earnedGrade1 == earnedGrade2)
{
count++;
}
if(earnedGrade1 == earnedGrade3)
{
count++;
}
The above example doesn't seem to be a very good way to find the mode, since I would have to do around 11 if-statements for each and every earnedGrade variable.
If anyone has any suggestions, please do help.
Thank you for any help and please understand that I am new to programming.
One way to do this without an array is to write a helper method, something like this:
static int count(double gradeToCount, double grade1, ..., double gradeN) {
int count = 0;
if (gradeToCount == grade1)
count++;
if (gradeToCount == grade2)
count++;
// And so on...
return count;
}
It's just like if you were using a loop:
for (double grade : gradesArray)
if (gradeToCount == grade)
count++;
Except the loop is unrolled, and you check each grade and increment the count yourself.
Once you can count the occurrences of each grade, then you have to write another unrolled loop where you find the grade which has the maximum count.
Writing a helper method means that you only have to write out 2N comparisons by hand instead of N2 comparisons.
I don't really know what you are supposed to learn from having to do it this way, except for why arrays are necessary I guess.
I was thinking about it again, and another way to do this would be to just repeatedly read the file using Scanner. Something like this:
Scanner in1 = new Scanner(fileOrPath);
while (in1.hasNextDouble()) {
double gradeToCount = in1.nextDouble();
Scanner in2 = new Scanner(fileOrPath);
while (in2.hasNextDouble()) {
double grade = in2.nextDouble();
if (grade == gradeToCount)
count++;
}
}
This is pretty awful too, but it could be better than writing the comparisons by hand, I guess. I think Poosh's answer is suggesting something similar to this.
Probably not the most efficient, but here's an idea from what you mentioned you've covered in the course so far: read the input file into a String. Then write methods that let you do things to the String that you can do with an array, like get the count of items, and get the item at a certain index. Then you could do some loops using those methods.
One way might be to get the first number in the String, count how many times you find it, then store that number and how many times it appears in the String in variables. Then go to the second number in the String, do the same thing, and reset those variables if the number appears more times than the previous number. Otherwise leave the variables alone. Once you get to the last item in the String, you'll have your mode.
Another downside besides the inefficiency is that this would only find a single mode. You could overcome this by using another String to "play the role of an array" using methods.
I believe the simplest (yet most laborious) solution here would be to use several if-else statements like you suggest. I think your instructor wants to show you that using several if-else statements in programming is inefficient and that he is using this question in order to transition into another concept. Either that, or the instructor is simply making your assignment busy work by introducing this requirement.
Since you are in an introductory class you probably have not been taught about more advanced data structures like ArrayLists yet and so unless you are allowed to use such structures for this assignment, you will have no other option but to make a huge if-else section in your code.
I have an idea, I know it's a pain because the program need to loop through the file many times, but however, it may be helpful as it doesn't use any array nor Collection (Explanation in Comments):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* The "mode" is the value that occurs most often
*/
public class ModeWithoutArray {
public static void main(String[] args) {
int count =0, lines = 0;
double mode =0;
File file = new File("C:\\Users\\Yahya\\Desktop\\grades.txt"); // for example
try {
Scanner read = new Scanner(file);
// count how many lines/grades the file contains
while(read.hasNextLine()){
read.nextLine();
lines++;
}
// now compare every grade with the others (line by line) specified by the index "i"
for(int i=0; i<lines; i++){
int result = count(i, file); // count how many time it's repeated
if(result>count){ // if it's bigger than the current count
count=result; // accept it
mode = findGrade(file, i); //then find the actual grade at that line
}
}
read.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
System.exit(0);
}
if(count>1){
System.out.println("The Mode is: " + mode + ", Repeated " + count + " times" );
}
else{
System.out.println("No Mode Found" );
}
}
// this method to count the repetition of a grade at particular line
private static int count(int atLine, File file){
double gardeToCount = 0;
int count=0;
try {
Scanner read = new Scanner(file);
// find the grade at that line
gardeToCount = findGrade(file, atLine);
// then compare it with other grades
while(read.hasNextLine()){
if(gardeToCount==Double.parseDouble(read.nextLine())){
count++;
}
}
read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return count; // return the count
}
// this method to find the actual grade at a given line in the file
private static double findGrade(File file, int atLine){
int line =0;
try {
Scanner read = new Scanner(file);
while(read.hasNextLine()){
if(line==atLine){
return Double.parseDouble(read.nextLine());
}
read.nextLine();
line++;
}
read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return 0;
}
}
Test
The File Content (grades.txt)
50
60
70
80
50
60
60
90
100
Output
The Mode is: 60.0, Repeated 3 times
UPDATE
Another approach, which is also more efficient, instead of reading the file many times [Also Added Validation To The File Content], you can do something like this (Explanation in Comments):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* The "mode" is the value that occurs most often
*/
public class ModeWithoutArray {
static int count =0, lines = 0;
static double mode =0;
public static void main(String[] args) {
// the file that contains the grades (a grade at each line)
File file = new File("C:\\Users\\Yahya\\Desktop\\grades.txt");
// get all grades and convert them to a String separated by one space
String allGrades = collectGrades(file);
double gradeToComapre = 0;
int gradeRep = 0;
// compare every grade with the others and count its repetition
// every round change mode and count to the bigger values
for(int i=1; i<=lines; i++){
gradeToComapre = grade(allGrades, i);
for(int j=i; j<=lines; j++){
if(gradeToComapre==grade(allGrades, j)){
gradeRep++;
}
}
if(gradeRep>count){
count=gradeRep;
mode = gradeToComapre;
}
gradeRep = 0;
}
if(count>1){ // if there is a mode
System.out.println("The Mode is: " + mode + ", Repeated " + count + " times." );
}
else{
System.out.println("The Collection Has No Mode!" );
}
}
//////////////////////////////////////////////////////////////////////
/**
* This method to collect all Valid Grades
* from a given file and concatenate them to a String to be
* returned at the end
* #param file
*/
private static String collectGrades(File file){
String allGrades = "";
try {
Scanner read = new Scanner(file);
// read the file and accept ONLY valid grades
while(read.hasNextLine()){
String oneGrade = read.nextLine().trim();
if(!oneGrade.isEmpty() && isValidGrade(oneGrade)){
allGrades += oneGrade + " "; // one space between every grade
// increment the global variable lines
// to be used in the comparison loops
lines++;
}
}
read.close();
} catch (FileNotFoundException e) {
System.out.println("File Does Not Exists!");
System.exit(0);
}
return allGrades;
}
//////////////////////////////////////////////////////////////////////
/**
* This method to check if a given Grade is valid
* this will return true/false
* #param oneGrade
*/
private static boolean isValidGrade(String oneGrade){
try{ // try to parse it as a double value
// this will throw an exception if it's not a number!
double theGrade = Double.parseDouble(oneGrade);
if(theGrade>=0 && theGrade<=100){ // is it in the range?
return true;
}
}catch(NumberFormatException e){
// catch the exception if it's not a number
// and return false
return false;
}
// return false if it's <0 or >100
return false;
}
//////////////////////////////////////////////////////////////////////
/**
* This method to fetch a particular grade from the
* String that contains all grades
* #param allGrades
* #param index
*/
private static double grade(String allGrades, int index){
String oneGrade = "";
int count = 0;
for(char c : allGrades.toCharArray()){
if(!Character.isWhitespace(c)){
// if it's not a space, concatenate the char to oneGrade
oneGrade += c;
}
else{ // the space determines the end of grade
count++;
if(count==index){ // if it's the required grade
// return it as a double
return Double.parseDouble(oneGrade);
}
else{// if it's not the required grade
// restart concatenation
oneGrade = "";
}
}
}
// this will never be the case unless you
// ask for a grade out the range
// (e.g. there are 3 grades and you want the fourth!!)
return -1;
}
}
Test
The File Content (grades.txt)
50
60.5
66
75
32
95
50.5
75
60.5
80
60.5
78
Output:
The Mode is: 60.5, Repeated 3 times.

how to call on a method outside of the main method in java

I have a method outside of the main method that averages. At the end of the main I am calling on that averaging method. I am not understaning the propper way to
1. use variables I declare with other methods in this program. for example the sum which is defined in the calculate_average method.
or
The sum which is defined in the main method.
Please show me
how to interchange variables in and out of the main method. interchangeably between methods that are not in main.
call on a method outside of main in main to calculate the average.
Here is my current code.
import java.util.ArrayList;
import java.util.Scanner;
class programTwo
{
private static Double calculate_average( ArrayList<Double> myArr )
{
Double Sum = 0.0;
for (Double number: myArr)
{
Sum += number;
}
}
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
ArrayList<Double> myArr = new ArrayList<Double>();
double Sum = 0;
int count = 0;
System.out.println("Enter a number to be averaged, repeat up to 20 times:");
String inputs = scan.nextLine();
while (!inputs.matches("[qQ]") )
{
if (count == 20)
{
System.out.println("You entered more than 20 numbers, you suck!");
break;
}
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
myArr.add(scan2.nextDouble());
count += 1;
System.out.println("Please enter another number or press Q for your average");
inputs = scan.nextLine();
}
Double average = calculate_average(myArr);
System.out.println("Your average is: " + average);
return Sum / myArr.size();
}}
You have this at the end of main:
return Sum / myArr.size();
You need to move it to calculate_average:
private static Double calculate_average( ArrayList<Double> myArr )
{
Double Sum = 0.0;
for (Double number: myArr)
{
Sum += number;
}
return Sum / myArr.size();
}
Given that main is void and an average makes no sense as an exit code even if it weren't, I'm assuming that is some kind of typographical error.
Some code review
Local variables should start with a lower case letter. So sum, not Sum
You can use the primitive double instead of a Double object. Using the object will cause boxing/unboxing overhead.
Indent your while loop and its contents by four more spaces so the loop beginning aligns vertically with the code above it because it's in the same block (the method's block).
Split those last 2 braces into separate lines
Line up the last two braces vertically with the matching opening brace
You've started by creating your calculate_average method, but continue breaking up main. It's too long. Too much is going on there.
Change if (count == 20) to if (count >= 20). Harder to mess up, then.
i think you have static method,
so you can call them bye using className.MethodName Directly.
Just Declare your method as public and you can call them outside also.
programTwo.calculate_average(myArr)
No need to create object for calling static methods.
There's nothing I can see wrong with your code, except you are missing a return statement in your calculate_average method.
Also, if you name a method calculate_average, it should return the average not the sum.
Try this:
private static Double calculate_average( ArrayList<Double> myArr )
{
Double sum = 0.0;
for (Double number: myArr)
{
sum += number;
}
return sum/myArr.size(); // added return statement
}

How to call method properly

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.

Implementing methods: search, load and print

Please see my comments in the code to better explain things. Basically having issues with the methods below. I can get the load method to run but I am unsure whether the numbers entered by the user are actually being stored in the array.
In addition, the search method has been throwing things off and i think its going in a loop.
See below for more. Thank you in advance.
import java.util.Scanner;
public class MyContainer {
private int[] values;
private int size;
public MyContainer(){
values=new int[50];
size=0;}
//Load Method - Display a message to the user
//and get positive intergers from user
public void load()
{
int input;
Scanner in = new Scanner(System.in);
System.out.println("Enter a series of positive integers (Negative to Terminate): ");
input=in.nextInt();
while (input >=0) {
values[size]=input;
size++;
input=in.nextInt();
}
}//End Load
//Compute Average from the above entered numbers
public double computeAverage() {
double avg= 0.0;
int count = 0;
while(values[size] >=0)
{avg = avg + values[size];
count++;
}
size = size + 1;
avg = avg / size;
return avg;
}
//Get user input to search for a number in the array
public boolean search(int myInt){
while(values[size] >=0) {
if (values[size] == myInt){
return true;}
else{
size++;}
}
return false;
}
//print the position of the number
public void print(){
for(int i=0;i>=size;i++) {
System.out.println("The number at position " + i + " is " + values[i]);
}
}
}
That is what I have so far. I also have created a tester class for the above container.
class Tester {
public static void main(String[] args) {
MyContainer in = new MyContainer();
in.load();
in.computeAverage();
in.search(); //i know for a fact this is wrong just stuck
in.print();
}
}
Any advise/help would be greatly appreciated. My professor is terrible at teaching and the book only partially explains things.
Your search() method has parameters that you aren't passing.
you declare it as...
public boolean search(int myInt) {
while (values[size] >= 0) {
if (values[size] == myInt) {
return true;
} else {
size++;
}
}
return false;
}
but call it with...
in.search();
This code won't even compile. For argument sake I set this to 5.
In your computeAverage() method, this is an infinite loop...
while (values[size] >= 0) {
avg = avg + values[size];
count++;
}
The main problem I believe you are running into is the reuse of your size variable. In the load function it will work as expected say for loading in 10 numbers size will be 10 and elements 0->9 in values will have numbers in them. However when you get to computeAverage size will still be 10. So you are in an infinite loop.
while(values[size] >= 0) {
avg = avg + values[size];
count++;
}
First iteration you will check values[10] (which is wrong remember valid elements are only in 0->9 if size is 10). Next iteration avg and count are increased but size remains the same so you will add the same number to avg and continue in the loop. You should use a different conditional for your while loops in computeAverage and search. The last negative number entered to quit will not be in the array; you will need to use something else. As a hint it will involve count and size.

Import? working with packages

I'm working on homework and I'm close but I am having an issue. I just learned how to work with packages in eclipse so I have a class that is importing another class from a package (I think I said that right)
The main prompts the user to enter an integer between -100 and 100 and I am having an issue with validating it. I know the issue is where I'm importing I'm just unsure the direction I need to go to fix it.
This is a section of my main code. (my issue starts with the last couple lines if you want to skip ahead)
import myUtils.util.Console;
public class ConsoleTestApp
{
public static void main(String args[])
{
// create the Console object
Console c = new Console();
// display a welcome message
c.println("Welcome to the Console Tester application");
c.println();
// int
c.println("Int Test");
int i = c.getIntWithinRange("Enter an integer between -100 and 100: ", -101, 101);
c.println();
In that last line of code
int i = c.
I get a squiggly line under i that tells me I am not using the local variable so I'm not sure what exactly fixes that in this situation since I'm trying to use it in another class. Do I need to create an object?
I have a class called Console that is located in another package that I believe I have properly imported.
here is the code I am stuck on in my console class.
package myUtils.util;
import java.util.Scanner;
public class Console
{
Scanner sc = new Scanner(System.in);
public void print(String s)
{
System.out.println();
}
public void println(String s)
{
System.out.println();
}
public void println()
{
System.out.println();
}
public int getIntWithinRange(String prompt, int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.println(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
if (i < min)
{
System.out.println("Error! Please enter an integer greater than -100");
}
else if (i > max)
{
System.out.println("Error! Please enter an integer less than 100");
}
else
isValid = true;
}
else
System.out.println("Error! Invalid number value");
sc.nextLine();
}
// return the int
return i;
}
public double getDoubleWithinRange(String prompt, double min, double max)
{
int d = 0 ;
boolean isValid = false;
while (isValid == false)
{
System.out.println(prompt);
if (sc.hasNextInt())
{
//if user chooses menu option less than 1 the program will print an error message
d = sc.nextInt();
if (d < min)
{
System.out.println("Error! Please select menu option 1, 2, or 3");
}
//if the user chooses a menu option greater than 3 the program will print an error
else if (d > max)
{
System.out.println("Error! Please select menu option 1, 2, or 3");
}
//if the option is between 1 and 3 the menu option is valid
else
isValid = true;
}
else
System.out.println("Error! Invalid number value");
sc.nextLine();
}
// return the int
return d;
}
public String getRequiredString(String prompt)
{
return prompt;
}
public String getChoiceString(String prompt, String s1, String s2)
{
return s2;
}
public int getInt(String prompt)
{
return 0;
}
}
when I run this I keep getting my last print which is an invalid number value. am I not importing the code from the main method in the other console properly?
This isn't an import problem. If you're importing something wrong, your program won't compile in the first place, or at a bare minimum won't launch.
As far as actually fixing your problem, I'd recommend looking at the two lines you think are associated with the outermost else in getIntWithinRange and considering which code is actually associated with the else and which code isn't. The main issue is that an if or an else is only associated with one line unless you surround the multiple lines with curly braces. So, you should modify the last else of getIntWithinRange to look like
else {
System.out.println("Error! Invalid number value");
sc.nextLine();
}
EDIT: In response to the updated question
I get a squiggly line under i that tells me I am not using the local variable so I'm not sure what exactly fixes that in this situation since I'm trying to use it in another class. Do I need to create an object?
Right now, the code that you have written doesn't use i in main. That includes not passing it to any other method or to any constructor. Since i is a local variable, it's not accessible outside main, so Eclipse warns you. This "squiggly red line" warning from Eclipse won't stop your code from compiling and running just fine, but it is intended to help you find bugs in your own code.
On a broader note, there are a lot of bugs that arise because of unused locals, and Eclipse wants to help you prevent those bugs. Consider the example of wanting to initialize all the elements of a two-dimensional array to some user-supplied number (the variable names are shorter than I would use in a real program, but they still get the point across):
public static final int N = 10;
public void main(String[] args) {
int[][] a = new int[N][N];
int n = /* Read number from the user */;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
a[i][j] = i; // Bug - we meant to initialize to n
}
}
// ...
}
Eclipse's flagging of unused locals helps you find these kinds of bugs more easily.

Categories