Import? working with packages - java

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.

Related

how can i check if the number is perfect square by not using math.sqrt

i want to make a program which related to this question:
An integer that can be expressed as the square of another integer is called a perfect square, such as 4,9,16,25, etc. Write a progran that checks if a number is a perfect square.
I did built something goes like:
import java.util.Scanner;
class Q3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = 0;
int a = 0;
System.out.println("Type a number to check if it has square");
num = sc.nextInt();
for(a = 1;a<num;a++){ }
if (a*a == num){
System.out.println("Ok");
break;
}
else if (a*a != num){
System.out.println("Not ok");
}
}
}
So it doesn’t give what i want when i run it. What should i change or add ?
I think your for loop interpretation might be wrong, I made up something that might just work. Give this code a try.. You can make the method return a boolean too if you want.
static void perfectSquare(int number) {
for (int i = 1; i < i * number; ++i) {
// 'i' is the divisor, making sure
// it is equal to the quotient
if ((number % i == 0) && (number / i == i)) {
System.out.println(i);
}
}
If you want to brute force every number then you are on the right track but you should only print "Not ok" if all numbers in the loop have failed otherwise you may have a perfect square but "Ok" will be hidden within many "Not ok" lines. Also there is nothing in your for loop so the if statement always checks if 0*0 == num.
This looks like it may be a homework question so I won't give a full answer for you but think about how you can make this more efficient.
If you have found an integer number that matches do you need to keep going?
Do you need to check every number? (a starting point may be following the principles of a binary search)
I ended up like this:
import java.util.Scanner;
class Q3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = 0;
int a = 0;
int b = 0;
System.out.println("Type a number to check if it has square");
num = sc.nextInt();
for(a = 1;a<num;a++){
if (a*a == num){
b = 1;
break;
}
}
if(b==1){
System.out.println("Perfect Square");
}
else {
System.out.println("Not ok");
}
}
}
Thanks for support !

Facing problem in java code while running in terminal

** I am Trying to print this pattern in JAVA
a/2 + a/3 + a/4 ....+ a/n
**
Here is my java code
import java.util.*;
public class ser
{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value of a and n");
int a,i,n;
double s=0;
a=in.nextInt();
n=in.nextInt();
for(i=1;i<n;i++)
s=s+(double)a/(i+1);
System.out.println("ssss = "+s);
}
}
I'm using Kali linux and today I'm facing this error while running my java code in terminal
Enter the value of a and n
a 12
Error:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at ser.main(one.java:9)```
There is no problem1 with your code.
The problem is with the input that you are giving to the program.
Assuming that you are running from the command line, the way to compile and run the program is like this.
steve#greybeast:/tmp$ javac ser.java
steve#greybeast:/tmp$ java ser
Enter the value of a and n
2 12
ssss = 4.206421356421357
steve#greybeast:/tmp$
See?
When it asks me to "enter a and n", I type 2 12 <ENTER>.
And it works (as far as I can tell).
What you have been doing is entering letters, numbers in quotation marks and other things. But the program as you have written it2 expects only 2 integers with whitespace between them. And when it gets something that it doesn't expect, the nextInt() call throws an InputMismatchException.
1 - Actually, there is a problem. Your code ignores a number of important Java style conventions. For example, class names should NOT start with a lowercase letter, and code should be correctly indented. But these things only matter to humans who have to read your code.
2 - I hope that >you< wrote it. 'Cos if you copied it rather than writing it yourself, you are cheating yourself of the opportunity to learn to program.
Issue is with your input. Code is expecting integer value as input and you are providing 'a'. You need to provide integer.
You don't need to provide a and then 12, just provide 12, press enter and then provide the next Integer. Right now I think it's trying to decode a as an integer. Just provide the integers in order of their input and it should work.
brother!! just hardcore "a" to the print statement instead for taking it as an input.
may be this code will help u
import java.util.*;
public class ser
{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value of n");
int i,n;
n=in.nextInt();
for(i=2;i<=n;i++)
{
System.out.print("a/"+i);
if(i==n)
break;
else
System.out.print(" + ");
}
}
}
To clear confusion, I modified your code as below.
Provide your input in two separate lines.
import java.util.*;
public class ser
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the value of a and n");
int a, i, n;
String a1, n1;
double s = 0;
a1 = in.nextLine(); // Reading as string value the complete line
n1 = in.nextLine();
// checking whether the value acquired is number or not
if (!isNumeric(a1.toString())) {
System.out.println("Please provide a valid number without alphbets or symbol, you have typed:" + a1);
System.exit(0);
}
if (!isNumeric(n1.toString())) {
System.out.println("Please provide a valid number without alphbets or symbol, you have typed:" + n1);
System.exit(0);
}
a = Integer.parseInt(a1);
n = Integer.parseInt(n1);
for (i = 1; i < n; i++)
s = s + (double) a / (i + 1);
System.out.println("ssss = " + s);
}
// will check whether the string passed is number or not
public static boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
}

Prime Generator compiling and executing in IntelliJ;NZEC error in SPOJ

I am trying to solve the Prime Generator problem on SPOJ using the code below
import java.lang.*;
import java.io.*;
class Prime
{
public static void main (String[] args) throws IOException
{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader nx = new BufferedReader(reader);
int t; //t is the number of test cases
int n1;
int n2;// n1 and n2 and the smaller and larger number b/w which we have to find all the primes
System.out.println("Enter the number of test cases");
t = Integer.parseInt(nx.readLine());
if(t<=0)
{
return;
}
int i = 0;
do
{
System.out.println("Enter the first number");
n1 = Integer.parseInt(nx.readLine().trim());
if(n1<0)
{
return;
}
if(n1<0)
{
return;
}
System.out.println("Enter the second number");
n2 = Integer.parseInt(nx.readLine().trim());
if(n2<0)
{
return;
}
int a;
int b;
for(a = n1; a <= n2; a++)
{
for(b = 2; b < a; b++)
{
int quot = a%b;
if(quot == 0){
break;
}
}
if(a == b)
{
System.out.println(" "+a);
}
}
System.out.println();
i++;
}while(i < t);
}
}
I apologize for the poorly indented code and the fact that the class declaration seems to have leaked out of the area meant for adding code but I haven't written Java in 4 years. I have been stuck on this problem since yesterday night and I can't get it to work in SPOJ even though it works perfectly in IntelliJ
code running as it should in IntelliJ
But when I run the same code in SPOJ I get this
SPOJ output
I Googled the error message and tried to use try catch to solve the problem without success. Some people who got similar errors were advised to use the trim() function in parseInt() to remove whitespace but that did not solve my problem.
In line 18 you try to convert a null string to a number. The string is null because there is no input available. From the documentation of readLine():
Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
Note also the "Standard input is empty" in the screenshot.
To summarize: there is nothing wrong with the program, you just don't provide any input data.

When the program loops it prints the line "Enter your name (first and last): " twice?

So in the program I ask the user whether they want to rerun the program but when it does it prints the line "Enter your name," followed by a space, twice. Can someone please help me find the cause of this? It doesn't happen when you run it the first time by the way.
import java.util.Scanner;
public class PirateName
{
static Scanner input = new Scanner(System.in);
static String[]firstNames = {"Captain", "Dirty", "Squidlips", "Bowman", "Buccaneer",
"Two toes", "Sharkbait", "Old", "Peg Leg", "Fluffbucket",
"Scallywag", "Bucko", "Deadman", "Matey", "Jolly",
"Stinky", "Bloody", "Miss", "Mad", "Red", "Lady",
"Shipwreck", "Rapscallion", "Dagger", "Landlubber", "Freebooter"};
static String[]secondNames =
{"Creeper","Jim","Storm","John","George","Money","Rat","Jack","Legs",
"Head","Cackle","Patch","Bones","Plank","Greedy","Mama","Spike","Squiffy",
"Gold","Yellow","Felony","Eddie","Bay","Thomas","Spot","Sea"};
static String[]thirdNames =
{"From-the-West","Byrd","Jackson","Sparrow","Of-the-Coast","Jones","Ned-Head",
"Bart","O'Fish","Kidd","O'Malley","Barnacle","Holystone","Hornswaggle",
"McStinky","Swashbuckler","Sea-Wolf","Beard","Chumbucket","Rivers","Morgan",
"Tuna-Breath","Three Gates","Bailey","Of-Atlantis","Of-Dark-Water"};
static String[] letters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o",
"p","q","r","s","t","u","v","w","x","y","z"};
public static void main(String[] args) {
System.out.println("Welcome to the pirate name generator");
System.out.println("");
boolean running = true;
while(running){
nameGenerator();
}
}
public static boolean nameGenerator()
{
boolean rerun = false;
int x = 0;
System.out.println("Enter your name (first and last): ");
String userName = input.nextLine();
System.out.println("");
try{
String first = userName.substring(0,1);
for (int i=0;i <= 25 ; i++)
{
if(first.equalsIgnoreCase(letters[i]))
{
first = firstNames[i];
}
}
String last1 = userName.substring(userName.indexOf(' ')+1);
for (int i=0;i <= 25 ; i++)
{
if(last1.substring(0,1).equalsIgnoreCase(letters[i]))
{
last1 = secondNames[i];
}
}
String last2 = userName.substring(userName.length() - 1);
for (int i=0;i <= 25 ; i++)
{
if(last2.equalsIgnoreCase(letters[i]))
{
last2 = thirdNames[i];
}
}
System.out.println("Your pirate name is: ");
System.out.println("");
System.out.println(first+" "+last1+" "+last2);
System.out.println("");
System.out.println("Would you like to try again? (Type 1 for yes, 2- no)");
int a = input.nextInt();
if (a==2)
{
rerun = false;
System.out.println("Good Bye!");
return rerun;
}
else
{
rerun = true;
}
return rerun;
}
catch (Exception e){
System.out.println(" ");
}
return rerun;
}
}
I see at least three problems.
At the end of the method, when you read the value of a, you're pulling an integer from the Scanner, but you're not pulling out the newline character that follows the integer. This means that next time you call nextLine(), all you'll get is a blank line. The cure for this is to add an extra input.nextLine() immediately after input.nextInt().
You're catching exceptions and throwing them away, without even printing their stack traces. That means that if your program does encounter a problem, you'll never find out any information about the problem.
You're not using the value rerun outside the nameGenerator method. When you call it, you're checking if running is true, but running will never change, so you'll just go on calling it forever. So you probably want to change the code that calls it to this.
boolean shouldRun = true;
while (shouldRun) {
shouldRun = nameGenerator();
}
It looks like you are using the input scanner for entering both ints and strings. You should use two separate scanners, or change it so that input is brought in with .nextLine() and then changed to an integer.
The problem is you enter two characters when deciding to try again. The first is the int, the second is the character. The second character is not an integer, so it is left in the buffer. Then when you get input a second time, you are using a scanner that already has characters in the buffer. So it processes the buffer and reads the left over char as an empty line.
http://www.java-forums.org/new-java/24042-input-nextline.html

How can I use get methods in an Array?

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;

Categories