Hello
I'm new to java and need someone to answer a problem I'm having. I have recently started a project to make a calculator in Java. However i'm having a problem with one prat of my code. Basically i can't call a string off from an method. Ive tried varoius other attemps to fix the problem but to no avail. Here is the code:
package CalculatorCore;
import java.util.Scanner;
public class calculations {
static void firstNumber() {
Scanner firstNum = new Scanner(System.in);
System.out.print("First Number: ");
String n1 = firstNum.next(); //You can see, i put the string in a method
}
static void secondNumber() {
Scanner secondNum = new Scanner(System.in);
System.out.print("Second Number: ");
String n2 = secondNum.next(); //Here too
}
public static void main(String[] args) {
System.out.println("Please Choose one of the following equasions: +, -, * or /");
System.out.println("");
System.out.println("");
mathEquasions();
}
static void mathEquasions() {
Scanner equasions = new Scanner(System.in);
System.out.print("Enter input: ");
String e = equasions.next();
if (e.equals("+")) {
System.out.println("");
System.out.println("Please enter the first number that you want to add");
firstNumber();
System.out.println("");
System.out.println("Now add the second number");
secondNumber();
var plusAnswer = (n1 + n2); /*The problem is situated here, i need to call the
strings from another class*/
System.out.println("");
System.out.println("");
System.out.println("Your answer is...");
firstNumber();.n1
}
}
I've already used methods to make the user inputs compact so if theres no other way should i remove the methods?
You need to return the numbers you retrieved in your both methods. Don't forget to parse them as integers, using nextInt:
public class calculations {
static int firstNumber() {
Scanner firstNum = new Scanner(System.in);
System.out.print("First Number: ");
int n1 = firstNum.nextInt();
return n1;
}
static int secondNumber() {
Scanner secondNum = new Scanner(System.in);
System.out.print("Second Number: ");
int n2 = secondNum.nextInt();
return n2;
}
}
Then, when calling firstNumber or secondNumber, create new variables to store their return values:
public class calculations {
static void mathEquasions() {
Scanner equasions = new Scanner(System.in);
System.out.print("Enter input: ");
String e = equasions.next();
if (e.equals("+")) {
System.out.println("");
System.out.println("Please enter the first number that you want to add");
int n1 = firstNumber();
System.out.println("");
System.out.println("Now add the second number");
int n2 = secondNumber();
var plusAnswer = (n1 + n2);
System.out.println("");
System.out.println("");
System.out.println("Your answer is...");
}
}
}
welcome to SO! When trying something for the first time it's a good practice to make it as simple as you can, and from there gradually use more complex techniques.
In this case everything is in one class already, so as a first step you could try to put all your code back into the main method.
public static void main(String[] args) {
//All your code can come here first in the order they are supposed to to be called.
}
As a second step, when it all works, you can extract the parts where you would duplicate code, into separate methods.
Like here instead of having firstNumber() and secondNumber() you could have just one, with something like:
static int getNumber() {
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int number = scanner.nextInt();
return number;
}
and you can call the same method to get both numbers:
public static void main(String[] args) {
//...
System.out.println("Please enter the first number that you want to add");
int n1 = getNumber(); // Using the same method for both
System.out.println("");
System.out.println("Now add the second number");
int n2 = getNumber(); // Using the same method for both
//...
}
Learning by doing and jumping into the thick of it is one of the best ways to learn. There are tons of good quality materials freely available (eg. on yt) and they can really boost your skills. That's also how I started learning, so good luck!
Related
I am trying to change my code to incorporate an int and double parameter for one method name. My end goal is to let the user pick two numbers and if they type one as int and the other as double, I want the code to still be able to account for those different types and print successfully. The code as follows is the basics I have come up with so far and I would like some help on how to change this code to use method overloading.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Select operation:");
System.out.println("1. Divide 2 numbers");
System.out.println("2. Exit");
System.out.print("Enter choice(1/2:");
int choice = input.nextInt();
if (choice == 1){
division();
}
else if (choice == 2){
Exit();
}
input.close();
}
public static void division(){
int nOne, nTwo;
Scanner input = new Scanner(System.in);
System.out.println("Division");
System.out.print("First Number: ");
nOne = input.nextInt();
System.out.print("Second Number: ");
nTwo = input.nextInt();
input.close();
System.out.println("Sum: " + nOne + " / " + nTwo + " = " + (nOne /
nTwo));
}
public static void Exit(){
Scanner input = new Scanner(System.in);
System.out.println("Goodbye");
System.exit(0);
}
}
You need to give the dataype via the parameters. So you then have two methods like this:
public int division(int number1, int number2){
//do division
return result;
}
public double division(double number1, double number2){
//do division
return result;
}
you can then call the method division both with int and double and the according method will be chosen.
I have a problem with solving exercise
There are two classes ready in the exercise: ObjectFunctionality and
Calculator. Your task is to create the class Printer which asks for
two integers from the user, calls the method Sum() of class Calculator
relaying the inputted integers to the method. Method Sum() counts the
sum of the numbers and returns the result. Finally Sum() prints the
sum on screen.
import java.util.Scanner;
public class ObjectFunctionality {
public static void main(String args[]) {
Printer thing = new Printer();
thing.Print();
}
}
// Write the missing class here
// Class is written in the text box below.
class Calculator {
static int Sum(int first, int second) {
int sum = first + second;
return sum;
}
}
Here is my code:
class Printer {
Scanner input = new Scanner(System.in);
System.out.print("Type in the first integer: ");
int first = reader.nextInt();
System.out.print("Type in the second integer: ");
int second = reader.nextInt();
System.out.print("Sum of the numbers: " + sum.sum);
}
I know that something is very wrong, but I cant solve this.
PS. I need an output like this:
Type in the first integer: -3 Type in the second integer: -1 Sum of
the numbers: -4
Thanks a lot!
You can try this:
public class Printer {
void Print(){
Scanner input = new Scanner(System.in);
System.out.print("Type in the first integer: ");
int first = input.nextInt();
System.out.print("Type in the second integer: ");
int second = input.nextInt();
System.out.print("Sum of the numbers: ");
int sum = Calculator.Sum(first, second);
System.out.println(sum);
}
}
I'm creating a simple program that gets name, age and favorite number/s. The problem is that this exception appears when user chooses to input more than 1 favorite number.
Please help me to solve this problem that still uses ellipse in testing class --> favnum2 method.*
testing class
import java.util.Scanner;
public class testing{
public static Scanner input;
public static void main(String[] args){
boolean choicerepeat=true;
int favnumoftimes;
while(choicerepeat==true){
input = new Scanner(System.in);
testing2 obj1 = new testing2();
String name="";
int age=0;
favnumoftimes=0;
double favnum=0, favnumarr[]=new double[999];
boolean choice1;
System.out.print("What is your name? ");
name = input.nextLine();
System.out.print("What is your age? ");
age = input.nextInt();
obj1.message1(name);
obj1.message2(age);
System.out.print(name+" do you only have one favorite number? (If yes type 'true' else 'false' - NOTE: lowercase only) ");
choice1 = input.nextBoolean();
if(choice1==true)
favnum1();
else{
System.out.println("How many favorite numbers do you have "+name+"? ");
favnumoftimes = input.nextInt();
for(int a=0;a<favnumoftimes;a++){
System.out.print("Enter favorite number "+ (a+1) +": ");
favnumarr[a]=input.nextDouble();
}
for(int a=0;a<favnumarr.length;a++){
favnum2(favnumoftimes, favnumarr[a]);
}
}
System.out.println();
System.out.println("Do you want to restart the program? (true(Yes) else false(No)) ");
choicerepeat = input.nextBoolean();
}
}
public static void favnum1(){
System.out.print("Enter favorite number: ");
double favnumholder1 = input.nextDouble();
System.out.println("Your favorite number is "+favnumholder1+" ." );
}
public static double favnum2(int favnumoftimesholder,double...favtemphold2){
System.out.print("Your favorite numbers are ");
for(int a=0;a<=favnumoftimesholder;a++){
System.out.print(favtemphold2[a]+", ");
}
return 0;
}
}
testing2 class
public class testing2{
public static String message1(String nameholder){
for(int a=0;a<nameholder.length();a++){
char strholder = nameholder.charAt(a);
if(Character.isDigit(a)){
System.out.println("Names don't have numbers... ");
break;
}
else continue;
}
System.out.println("\nHi "+nameholder+"! Welcome to my simple program. ");
return nameholder;
}
public static int message2(int ageholder){
System.out.println("Your age is "+ageholder+" years old? Oh my goodness. ");
System.out.println();
return ageholder;
}
}
The problem is that varargs create new arrays with a length equal to the number of parameters passed. Thus double...favtemphold2 will create a new array favtemphold2 and since you only pass 1 element (favnum2(favnumoftimes, favnumarr[a]);) that array will have length 1.
You might want to either pass more elements or the entire array, i.e. favnum2(favnumoftimes, favnumarr);. Since double... is basically syntactic sugar for double[] they are equal and passing a double array for a double vararg will work.
A warning for future use of varargs though: be carefull with Object... since arrays are objects as well.
package Exercises;
import java.util.Scanner;
public class ArrayPlusN {
public static void createArray(int indeces){
Scanner in = new Scanner(System.in);
int valueAdded, y = 0;
int[] arraySet = new int[indeces];
for(int i = 0; i < arraySet.length; i++){
System.out.printf("Enter element #%s: ",i+1);
arraySet[i] = in.nextInt();
}
System.out.println("These are the elements in your array: ");
for(int i:arraySet){
System.out.printf("%s ", i);
}
System.out.println("");
System.out.print("Enter a number to add in each of your Array's element: ");
valueAdded = in.nextInt();
System.out.println("These are the elements in your array when we added "+ valueAdded + " to each: ");
for(int i:arraySet){
arraySet[y]=i+valueAdded;
System.out.printf("%s ", i+valueAdded);
y++;
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int indeces;
System.out.print("Enter how many array index/indeces you want: ");
indeces = in.nextInt();
createArray(indeces);
}
}
Well to start things up, i'm trying to make a program where it will add a value on each element in the array, by getting user input of how many index that user wants to make, elements of the said array and the value to be added on the said array. There's no error in this code though you can copy paste it but im asking if i can do it as OOP. i don't think that this is OOP, anybody can help? I mean i wanted to seperate all those functions on each methods, is that possible? i tried it but i can't seem to know on how to call another variable from another method. i wanted to make createArray, fillArray and addElement methods to make it look more OOP rather than just making 1 createArray with all the functions in it.
Here's the code defining the main(), createArray(), fillArray() and addElement() methods; calls the methods in the order needed and accomplishes the task in the manner you want.
package Exercises;
import java.util.Scanner;
public class ArrayPlusN {
static int arraySet[];
public void createArray(int indeces){
Scanner in = new Scanner(System.in);
int valueAdded, y = 0;
arraySet = new int[indeces];
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
ArrayPlusN object=new ArrayPlusN();
int indeces;
System.out.print("Enter how many array index/indeces you want: ");
indeces = in.nextInt();
object.createArray(indeces);
object.fillArray();
object.addElement();
}
public void fillArray(){
Scanner in=new Scanner(System.in);
for(int i=0;i<arraySet.length;i++){
System.out.println("Enter element number "+(i+1));
arraySet[i]=in.nextInt();
}
System.out.println("The elements of your array are");
for(int i:arraySet)
System.out.print(i+" ");
System.out.println();
}
public void addElement(){
Scanner in=new Scanner(System.in);
System.out.println("Enter value to be added to each element");
int valueAdded = in.nextInt();
int y=0;
System.out.println("These are the elements in your array when we added "+ valueAdded + " to each: ");
for(int i:arraySet){
arraySet[y]=i+valueAdded;
System.out.printf("%s ", i+valueAdded);
y++;
}
}
}
The arraySet array is declared as a global static one. All the methods are declared as public void. The arrays are called in the main() method with the object object of class ArrayPlusN in order and gets the job done. Hope it helps you.
I'm fairly new to java, so don't think this is some idiot. Anyways, I've been trying to make a program that can read a certain letter from the console and then decide which operation to use, let's say to add. However, I can't get an If loop to read the variable that decides which operator to use, here is the code, and please help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int number;
String function;
System.out.println("What Do You Want to Do? (a to add; s to" +
" subrtact; d to divited; m to multiply, and sq to square your nummber.)" );
function = user_input.next();
if (function == "sq"){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
}
(I made the description shorter so that it would fit).
This is just an example to get you started in the right direction.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num1, num2, result;
System.out.println("What Do You Want to Do? (a to add; s to"
+ " subrtact; d to divited; m to multiply, and s to square your nummber.)");
String choice = user_input.next();
// Add
if (Character.isLetter('a')) {
System.out.println("Enter first number: ");
num1 = user_input.nextInt();
System.out.println("Enter second number: ");
num2 = user_input.nextInt();
result = num1 + num2;
System.out.println("Answer: " + result);
}
}
}
If you use hasNext() on a scanner it will wait for an input until you stop the program. Also using equals() is a better way of comparing strings.
while(user_input.hasNext()){
function = user_input.next();
if (function.equals("s")){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int a=s.nextInt();
int b=s.nextInt();
if(str.equals("+"))
c=a+b;
else if(str.equals("-"))
c=a-b;
else if(str.equals("/"))
c=a/b;
// you can add operators as your use
else
System.out.println("Unidentified operator" );
I hope it helps!