Calling boolean methods - java

My overall goal with this program is to validate that a user inputted string is in fact a valid number. I am required to use at least two methods, including the main method. I have read many posts related to calling user-defined methods from within the main method, but I am however struggling to make mine work. When declaring my isAValidNumber method, I keep getting the error "illegal start of expression". How can I declare this method so that I can call it from within the main method and contentiously run it until the user enters an invalid invalid number?
import java.util.Scanner;
public class IsAValidNumber
{
public static void main(String[] args)
{
//prompt user for a valid number
Scanner consoleInput = new Scanner(System.in);
System.out.print("\nEnter a valid integer or floating point value: \n");
String input = consoleInput.nextLine();
/* while(isAValidNumber = true)
{
//
} */
public static isAValidNumber(String input)
{
for(int j=0;j<input.length();j++)
{
if(input.matches("\\d+(\\.\\d*)?|\\.\\d+") == true)
{
boolean isAValidNumber = true;
}
else
{
boolean isAValidNumber = false;
}
}
}
}
}

You can't declare methods inside of methods in Java. Declare isAValidNumber outside of main (either before or after it, doesn't matter) and you should be OK:
public class IsAValidNumber
{
public static boolean isAValidNumber(String input)
{
// Method's body snippet for brevity's sake
}
public static void main(String[] args)
{
// Code that can call isAValidNumber
}
}

Related

How can a static method change a variable? (Java)

I have this class:
class Inventory {
boolean smallknife = false;
boolean SRLockerkey = false;
void checkinv () {
System.out.println("You have the following items in your inventory: ");
System.out.println(smallknife);
System.out.println(SRLockerkey);
}
}
The Inventory test class
class InvTester {
public static void main(String args[]) {
Inventory TestInv = new Inventory();
System.out.println("This program tests the Inventory");
SKTrue.truth(TestInv.smallknife);
TestInv.checkinv();
}
}
and this class with a method to try to change the inventory
class SKTrue {
static boolean truth(boolean smallknife) {
return true;
}
}
class SKTrue {
static void truth(boolean smallknife) {
smallknife = true;
}
}
I would like to avoid using TestInv.smallknife = SKTrue.truth(TestInv.smallknife) and still change the variable but with a method. Is there a way that this can be done? I want that the truth method does the variable changing and I don't want to do the pass by reference part in the Inventory Test class. Thanks. Is there a way to do this in Java? (I also tried the second version which I think makes more sense)
Assuming you don't want to reference the variables directly (i.e. TestInv.smallknife = blah), the best practice in Java is to declare the variables as private and access them by getters/setters, e.g.:
class Inventory {
private boolean smallknife;
public boolean isSmallknife() {
return smallknife;
}
public void setSmallknife(boolean smallknife) {
this.smallknife = smallknife;
}
}
Now, you can do this:
Inventory TestInv = new Inventory();
TestInv.setSmallknife(SKTrue.truth(blah));
It is called Encapsulation, you can read more about it here.

Java variable 'never used'

I am learning Java and currently attempting to combine if statements and multiple class files.
It is a simple I/O program with a twist, if userName = JDoe I want the program to say something other than the standard saying.
From main.java:
import java.util.Scanner;
import java.lang.String;
class main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
UInput uInput = new UInput();
System.out.println("What is your name: ");
uInput.setName(input.nextLine());
uInput.saying();
}
}
class ifMain {
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
From UInput.java:
public class UInput {
private String userName;
public void setName(String name){
userName = name;
}
public String getName(){
return userName;
}
public void saying(){
System.out.printf("Hello %s", getName());
}
}
However, in class ifMain{}, IntelliJ is saying "Variable userName never used", what am I missing?
See comments:
class ifMain {
public static void main(String[] args){
String userName = "JDoe"; // <=== Declared here
if (test.matches("JDoe")) { // <=== Not used here
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
The local variable userName is never used in the main method of the ifMain class.
You probably meant:
if (test.matches(userName)) {
Side note: The overwhelming convention in Java is that class names start with an uppercase character. So IfMain, not ifMain.
Your program wouldn't even compile in first place. I believe that you are new to Java. But still, look at this code.
class ifMain {//Please change the class name to CamelCase convention
public static void main(String[] args){
String userName = "JDoe";
if (test.matches("JDoe")) {// Compile error. Variable test is not declared.
System.out.println("You smell!");
} else {
UInput.saying();
}
}
}
Are you trying in a notepad and executing it? You can try using eclipse/NetBeans/IntelliJ IDEs in that case to help you better.

Driver class for Array

How would I develop the driver class for this code ive written ?
Array Class:
import java.util.Scanner;
public class Array
{
Scanner sc = new Scanner(System.in);
private double[] array = new double[];
public void setArray(double[] arr)
{
//I must set a value for the array length. set by user.
//user must input data
}
public boolean isInIncreasingOrder()
{
//must test if input is in increasing order
}
public boolean isInDecreasingOrder()
{
//must test if input is in descending order
}
public double getTotal()
{
//must find the total of all input
//total +=total
}
public double getAverage()
{
//must calculate average
//average = total/array.length
}
}
I guess what I'm asking is what exactly do i call in the DriverClass and how do I do it.
Thanks
The simplest way to test a class is to have a "public static void main(String[] args)" method in the class itself.
In this "main" method, you first create an instance of the class, and then call the various methods in the class, and verify that they do what you expect. To make testing easier, you might want to print out a message after each call to the class under test, showing the expected result, the actual result, and a friendly "OK" or "FAIL" to let you see easily if the method did what you wanted.
Example:
class MyClass {
private int x = 0;
public int getX() { return x;}
public void setX(int x) { this.x = x; }
public static void main(String[] args) {
MyClass instance = new MyClass();
instance.setX(42);
int value = instance.getX();
System.out.print("Expected 42, got "+value);
if (value == 42) {
System.out.println("OK");
}
else {
System.out.println("FAIL");
}
}
}
Once you're familiar with this approach to testing, you might look into unit test frameworks such as JUnit, which provide better ways to "assert" that a particular test is passing, and to understand the results of your testing.

Call data from a string array to another class

public class QuestionBank {
public static void main(String[] args) {
int k = 0;
String Bank[][] = {{"The sun is hot.","A. True","B. Flase","A"},
{"Cats can fly.","A. True","B. False","B"}};
}
}
Above is my QuestionBank class that creates a 2X4 string array. First column being the question, 2nd and 3rd being the answer choices, and 4th being the correct answer.
Below is my RealDeal class.
import javax.swing.JOptionPane;
import java.util.Scanner;
public class RealDeal {
public static void main(String[] args) {
input = JOptionPane.showInputDialog(Bank[0][0]\nBank[0][1]\nBank[0][2]);
if (input == Bank[0][3]) {
input = 10;
} else {
input = 0;
}
total = input/1;
JOptionPane.showMessageDialog(null,"You scored a " + total + " out of 10. Great job!");
System.exit(0);
}
}
What I'm trying to do is to get Bank[0][0], Bank[0][1], and Bank[0][2] to output on my RealDeal class and then to check whether Bank[0][3] matches with the users input. Can anyone please help me with this. Im really new to java so if anyone could actually draw out the answer and explain it to me that would be great.
I think the best way is reading a good Java book and become familiar with the language itself and then try to solve this by your own. If you then have a real question there is no problem asking it here again. But your code is... not really working at all.
I don't think this portal is a "please do my work for me" portal.
To call anything from another class you will need to either setup a method for a return or make the variables public.
So:
public class Class1
{
// for method 1
public String s1 = "This is a string"
// for method 2
public Class1 {}
public returnString()
{
return s1;
}
}
public class CLASS2
{
public static void main(String args[])
{
// get the class
cls1 = new Class1();
// retrieving - method 1
String str = cls1.s1;
// retrieving - method2
str = cls1.returnString();
}
}

There are no main classes found

When I play it in NETBEANS IDE 8.0 it keeps saying there is no main class even though I added the main class already?
Need help can't understand.
PS. If I delete the static in magic() it blocks the magic() in main.
package fibotail;
import java.util.Scanner;
public class Fibotail {
public static int fibo(int control, int currentValue, int previousValue) {
if (control < 2) {
return currentValue;
}
return fibo(control - 1, currentValue + previousValue, currentValue);
}
public static void magic() {
String cCharacter;
do {
System.out.println("Input here: ");
int something = new Scanner(System.in).nextInt();
for (int i = 1; fibo(i, 0, 1) <= something; i++) {
System.out.println(fibo(i, 0, 1));
}
do {
System.out.println("Do you want to try again? ");
cCharacter = new Scanner(System.in).next();
} while (!(cCharacter.equals("y") || cCharacter.equals("Y") || cCharacter.equals("N") || cCharacter.equals("n")));
} while (cCharacter.equals('y') || cCharacter.equals('Y'));
}
public static int main(String args[]) {
magic();
return 0;
}
}
Return type should be void, not int:
public static void main(String args[]) { ... }
The JVM looks for the exact signature of the method.
When you run your project you would get:
Error: Main method must return a value of type void in class MainTest, please
define the main method as:
public static void main(String[] args)
In other languages than java, where main returns int (such as C and C++) the return code of main becomes the exit code of the process, which is often used by command interpreters and other external programs to determine whether the process completed successfully.
But java needs void as the return value. (Java internal architecture)
If you reaaly need to return a value just use the following:
System#exit(int)
To enable your program quit with a specific exit code which can be interpreted by the operating system.
Your main() method must have return type void
public static void main(String[] args){
}
Not int or other.
main() method is the entry point of your program and JVM is looking exact main() method.
You have to change your code a little bit. It should be:
public static void main(String args[])
The return type of main method is void

Categories