Trying to build a basic calculator using multiple classes - java

I am trying to use multiple classes not to bulk the whole entirety of the calculator in the main class. I was planning to use switch but I have been stuck on trying to combine User Input when it comes to your choice of operation.
ApplesUserInput.java
package applesuserinput;
import java.util.Scanner;
public class ApplesUserInput {
public static void main(String args[]){
calculator c1 = new calculator();
System.out.println("Hello! Welcome to my Calculator.");
System.out.print("You may add (A), subtract (S), multiply (M) or divide (D) two different numbers. Please select one of the letters for your desired operation: ");
calculator.geta();
}
}
calculator.java
package applesuserinput;
import java.util.Scanner;
public class calculator {
public static void geta(){
Scanner scan = new Scanner(System.in);
String a;
a = scan.nextLine();
}
}
So far it compiles and runs well but I cannot get the switch statement to recognize the a String from my geta(). So I'm pretty much stuck here right now.

Your geta() method isn't returning anything, nor have you assigned the result to anything.
It should be:
public static String geta(){
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
return a;
}
And in ApplesUserInput.java, it should be:
String a = calculator.geta();

Related

How to put multiple programs into one class?

I have made two programs for an assignment. Now my professor wants me to put both programs into the same file and use a switch to create a menu where the user can use to choose what program they want to run. How do I do this? I will copy-paste both of my original programs below.
Program 1:
import java.util.Scanner;
public class ReadName {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please type in your full name: ");
String names = scanner.nextLine();
String[] namesSep = names.split(" ");
int lastString = namesSep.length - 1;
System.out.println(namesSep[0]);
System.out.println(namesSep[lastString]);
}
}
Program 2:
import java.util.Scanner;
public class FindSmith {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Type in your list of names: ");
String names = scanner.nextLine();
String[] namesSep = names.split(",");
for (int i=0; i<namesSep.length; i++) {
if (namesSep[i].contains("Smith")) {
System.out.println(namesSep[i]);
}
}
}
}
You have two classes that do work in a single main() method each.
Start with: moving the content of that main() methods into another static method within each class, like:
import java.util.Scanner;
public class ReadName {
public static void main(String[] args) {
askUserForName();
}
public static void askUserForName() {
Scanner scanner = new Scanner(System.in);
System.out.print("Please type in your full name: ");
...
}
}
Do that for both classes, and make sure that both classes still do what
you want them to do.
Then create a third class, and copy those two other methods into the new class.
Then write a main() method there, that asks the user what to do, and then
runs one of these two methods from there.
Alternatively, you could also do
public class Combo {
public static void main(String[] args) {
...
if (userWantsToUseClassOne) {
Readme.main(new String[0]);
} else {
FindSmith.main(...
In other words: as long as you keep your classes in the same directory, you can directly re-use what you already have. But it is much better practice to put your code into meaningful methods, like I showed first.
As you might know, each Java program only has a single entry point; defined by the method public static void main(String[] args). As each class can define this method only once and you have to specify the class the method is in in your META-INF.MF file, it is impossible to have multiple entry points.
So you have to implement the logic that controls the program flow and respects the user's choice on your own. You can e.g. ask the user via the command line what kind of subprogram they want to execute.
you can use multiple method instead of multiple class . and call all method from your main method should be solve your problem.....
public class Combo{
public void readName(){
// place here all code form main method block of ReadName class
}
public void findSmith(){
// place here all code form main method block of FindSmith class
}
public static void main(String[] args) {
Combo c = new Combo();
c.readName();
c.findSmith();
}
}
Rather than creating two classes, you can create single class with one main method. Where you can create 3 switch cases.
1) To call ReadName (RN)
2) To call FindSmith (FS)
3) To break the code (BR)
After every execution you can again call main method. (Optional) I have added that to continue the flow.
package test.file;
import java.util.Scanner;
public class Test {
private final static Scanner scanner = new Scanner(System.in);
//public class ReadName
public static void main(final String[] args) {
switch (scanner.nextLine()) {
case "FS" :
findSmith();
break;
case "RN" :
readName();
break;
case "BR" :
break;
default :
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
}
private static void findSmith() {
System.out.println("Type in your list of names: ");
final String names = scanner.nextLine();
final String[] namesSep = names.split(",");
for (int i = 0; i < namesSep.length; i++) {
if (namesSep[i].contains("Smith")) {
System.out.println(namesSep[i]);
}
}
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
private static void readName() {
System.out.print("Please type in your full name: ");
final String names = scanner.nextLine();
final String[] namesSep = names.split(" ");
final int lastString = namesSep.length - 1;
System.out.println(namesSep[0]);
System.out.println(namesSep[lastString]);
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
}
Welcome to this community! As #Stultuske comments, your better approach is convert your main methods to regular methods and invoke them depending on the user's input.
The steps you should follow are:
Join both main methods to a single class file.
Convert both main methods to regular methods:
Change their name from "main" to any other name. Usually, using their functionality as a name is a good practice. In your case, you can use the class names you already defined ("ReadName" and "FindSmith").
Remove their input parameter "args": as they are no more the main method of a class, they won't be reciving any args parameter, unless you specify it.
Define a new main method which reads from the scanner and call your new methods acordingly to the user input.

How would I get a String from another class?

import java.util.*;
class Player {
public static void main (String [] args) {
String number = Text.nextLine
}
}
I want the user input from this class and
bring into another class and use the number variable for a
If statement
I want the user input from this class and bring into another class and
use the number variable for a If statement.
It is simple take a look at below example(make sure to add both classes in one package different java files as Player.java and ExampleClass.java),
This is the class that Scanner has:
import java.util.*;
public class Player{
public static void main (String [] args){
Scanner getInput = new Scanner(System.in);
System.out.print("Input a number");
//you can take input as integer if you want integer value by nextInt()
String number = getInput.nextLine();
ExampleClass obj = new ExampleClass(number);
obj.checkMethod();
}
}
This is the class that check number:
public class ExampleClass{
int number;
public ExampleClass(String number){
try{
//If you want to convert into int
this.number = Integer.parseInt(number);
}catch(NumberFormatException e){
System.out.println("Wrong input");
}
}
public void checkMethod(){
if(number > 5){
System.out.println("Number is greater.");
}else{
System.out.println("Number is lesser.");
}
}
}
Few thing to mention:
Your example code contains syntax errors, fix those first.
If you want integer you can use getInput.nextInt() rather than
getInput.nextLine().
You can create getter and setters to set vaues and get values. In my example I just only set value through the constructor.
Use proper naming convention.
In my example I convert the String into integer inside the constructor and wrap with try-catch block to prevent from NumberFormatException(If you input character or something you can see wrong input will print). Sometimes in variaus situation it is not good to use try-catch in constructor. To learn more about this, please read Try / Catch in Constructor - Recommended Practice.
Where you normally make an import on the other class, just import the Player class and it should work
I'm not sure if I got it, I suppose you're using a scanner.
This is the way I would do that:
Scanner class:
public class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Insert a decimal:");
String inputValue = scanner.nextLine();
if(!new ScannerCalc().isNumeric(inputValue)){
System.out.println("it's not a number...");
break;
}
else
new ScannerCalc().checkNumber(inputValue);
}
}
}
ScannerCalc class:
public class ScannerCalc {
public boolean isNumeric(String s) {
return s != null && s.matches("[-+]?\\d*\\.?\\d+");
}
public void checkNumber(String number){
if(Integer.parseInt(number)%2==0)
System.out.println("it' even");
else
System.out.println("it's odd");
}
}
Pay attention on instantiation of classes to reuse methods.
If you want to make use of a local variable in another entity, it is better to pass it as an argument to a method of the other entity. For example
OtherClass.operation(scanner.nextLine()); // In case method is static
new OtherClass().operation(scanner.nextLine()); // In case method is not static

Server/Client classes with two dimensional array (Java)

I am EXTREMELY new to Java and completely lost on the concept of ARRAYS. I need to create a "World" class to display a two dimensional array that is user specified in size, using a constructor that accepts two values [rows] and [columns] with a character (Lets say "P") located in the array. A separate "Driver" class will hold the main method. Other methods (moveUp, moveDown, moveLeft, and moveRight) need to be created to move the character around inside the array. There needs to be a fifth method to display the world array. I currently have the following code, but nothing is working so I got rid of it. even this code itself won't compile - says "identifier expected before the parenthesis of my second println. I have no idea why this won't go any further. This is the only place I have to seek help since the college offers no tutors for Java, youtube videos are extremely vague and use terminology I do not know, library books I've checked out don't show me the actual code needed to perform these tasks, and the class textbook shows code close, but not quite what is needed. and since I'm extremely new to Java, my last questions garnered me the threat of losing the ability to post on this site, so that would take away my only recourse for help if this is also dubbed inferior. I do not know what to do at this point.
import java.util.*;
public class World
{
public static void main(String[] args)
{
System.out.println(array);
}
Scanner input = new Scanner(System.in);
System.out.println("Enter number of row: ");
private int crow = input.nextInt();
System.out.println("Enter number of columns: ");
private int ccol = input.nextInt();
private String[][] array = newString[crow][ccol];
public int displayWorld()
{
}
public int moveUp()
{
}
public int moveDown()
{
}
public int moveLeft()
{
}
public int moveRight()
{
}
}
Compling problems-> use an IDE (eclipse netbeans idea jdeveloper ...) for developing java applications.
Here you have part of one solution, since you are learning, play with this code before implementing the rest of methods.
Regarding java learning, there are plenty of good tutorials by searching on google.
import java.util.*;
public class World{
private static final String P="P";
private String[][] array;
public World(){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of row: ");
int crow = input.nextInt();
System.out.println("Enter number of columns: ");
int ccol = input.nextInt();
array = new String[crow][ccol];
array[0][0]=P;
}
public void displayWorld(){
System.out.println();
for(int i=0;i<array.length;i++){
for (int j=0;j<array[i].length;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
public void moveUp(){
}
public void moveDown(){
for(int i=0;i<array.length;i++){
for (int j=0;j<array[i].length;j++){
if ((array[i][j])!=null){
if (i<array.length-1){
array[i][j]=null;
array[i+1][j]=P;
}
return;
}
}
}
}
public void moveLeft(){
}
public void moveRight(){
}
public static void main(String[] args){
World world=new World();
world.displayWorld();
world.moveDown();
world.displayWorld();
}
}

How do i call a class in the main method java?

OK im kinda new in java and i made this averaging program in one class, but now if i want to like call it from another class, then how do i do it?I tryed some object stuff but its hard to understand for.
this is the code and i want this program to start when i call it.
package Gangsta;
import java.util.Scanner;
public class okidoki {
public static void main(String []args){
Scanner input = new Scanner(System.in);
double average, tests, grades, total = 0;
int cunter = 1, start = 0;
System.out.println("Press 2 to start averaging, or press 1 to end");
start = input.nextInt();
while (cunter<start){
System.out.println("Enter how many tests u have");
tests = input.nextDouble();
System.out.println("Enter tests grades");
int counter = 0;
while (counter<tests){
counter++;
grades = input.nextDouble();
total = grades+total;
}
average = total/tests;
System.out.println(average);
System.out.println("Press 3 to end or 1 to average again");
cunter = input.nextInt();}
}
}
this is the code where i want to execute it
package Gangsta;
public class tuna {
public static void main(String []args){
okidoki okidokiObject = new okidoki();
System.out.println(okidokiObject);
}
}
In java the main method is the main (it's in the name) entry point of a program. That said, there is only one main in your program. Nevertheless if you want to have your code wrapped in another class just do it:
public class MyClass {
public void myFancyMethod() {
Scanner input = new Scanner(System.in);
//....rest of
//....your code
counter = input.nextInt();
}
}
and access it like:
MyClass myClassObject = new MyClass();
myClassObject.myFancyMethod();
You should really start reading (or read them again) the fundamentals of object oriented programming languages, naming conventions etc, because this is something you should understand to make progress in programming.
Object-Oriented Programming Concepts in Java
For now, you can just do this in tuna.java to achieve what you want:
package Gangsta;
public class tuna {
public static void main(String []args){
okidoki okidokiObject = new okidoki();
okidokiObject.main()
}
}
System.out.println(okidokiObject) prints Gangsta.okidoki#659e0bfd because it is the hashcode of your object (Hashcode is something like an ID, See Object toString()). You usually do not want to print objects, but invoke their methods.
If you change your main method in okidoki class to constructor it will work exactly like you wish !
Example:
Example.java
public class Example {
public Example() {
System.out.println("Example class constructed");
}
}
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Program started.Constructing Example class");
Example exClass = new Example();
System.out.println("Program finished.");
}
}

Why can't I print a variable that is provided by user inside a loop?

I apologize if the answer to this question is so obvious I shouldn't even be posting this here but I've already looked up the error compiling the following code results in and found no explanation capable of penetrating my thick, uneducated skull.
What this program is meant to do is get 2 integers from the user and print them, but I have somehow managed to mess up doing just that.
import java.util.Scanner;
public class Exercise2
{
int integerone, integertwo; //putting ''static'' here doesn't solve the problem
static int number=1;
static Scanner kbinput = new Scanner(System.in);
public static void main(String [] args)
{
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
int integerone = kbinput.nextInt(); //the integer I can't access
}
number++;
}
int integertwo = kbinput.nextInt();
System.out.println(integerone); //how do I fix this line?
System.out.println(integertwo);
}
}
Explanation or a link to the right literature would be greatly appreciated.
EDIT: I want to use a loop here for the sake of exploring multiple ways of doing what this is meant to do.
Remove the int keyword when using the same variable for the second time. Because when you do that, it is essentially declaring another variable with the same name.
static int integerone, integertwo; // make them static to access in a static context
... // other code
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
integerone = kbinput.nextInt(); //no int keyword
}
number++;
}
integertwo = kbinput.nextInt(); // no int keyword
And it needs to be static as well since you're trying to access it in a static context (i.e) the main method.
The other option would be to declare it inside the main() method but before your loop starts so that it'll be accessible throughout the main method(as suggested by "Patricia Shanahan").
public static void main(String [] args) {
int integerone, integertwo; // declare them here without the static
... // rest of the code
}
How about:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
System.out.println("Type in an integer: ");
int integerone = kbinput.nextInt();
System.out.println("Type another: ");
int integertwo = kbinput.nextInt();
System.out.println(integerone);
System.out.println(integertwo);
}
}

Categories