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);
}
}
Related
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!
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.
Both probabilities have the same code,but when i want to make addition,the text "enter the first number" is not shown. What did i do false?
import java.util.Scanner;
public class berketurer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int command1;
int number1;
int number2;
int result;
System.out.print("for subtraction,press 1.for addition,press 2.");
command1=input.nextInt();
if (command1==1)
System.out.print("enter the first number:");
number1=input.nextInt();
System.out.print("enter the second number:");
number2=input.nextInt();
result=number1-number2;
System.out.printf("the result is=%d\n",result);
if (command1==2)
System.out.print("enter the first number;"); //here is the problem
number1=input.nextInt();
System.out.print("enter the second number;");
number2=input.nextInt();
result=number1+number2;
System.out.printf("the result is=%d\n",result);
}
}
You're missing the {} braces from your if statement bodies, all you have is the indentation (which doesn't work since Java isn't Python).
import java.util.Scanner;
public class berketurer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int command1;
int number1;
int number2;
int result;
System.out.print("for addition,press 1.for subtraction,press 2.");
command1=input.nextInt();
if (command1==1) { // <-- opening
System.out.print("enter the first number:");
number1=input.nextInt(); // <- your code stops here
System.out.print("enter the second number:");
number2=input.nextInt();
result=number1-number2;
System.out.printf("the result is=%d\n",result);
} // <-- closing
if (command1==2) { // <-- opening
System.out.print("enter the first number;"); //here is the problem
number1=input.nextInt();
System.out.print("enter the second number;");
number2=input.nextInt();
result=number1+number2;
System.out.printf("the result is=%d\n",result);
} // <-- closing
}
}
You forgot the opening and closing of each block. So the first print is not executed and your code stops waiting for input.
I have a problem statement
Problem
Write a program to calculate the sum of 2 numbers and print the output.
Input
Line 1: An integer.
Line 2: An integer.
Output :The output consists of a single integer which corresponds to sum, followed by a new line
Sample Input I
3
1
Sample Output I
4
Sample Input II
13
10
Sample Output II
23
To which my solution is
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Add {
public static void main(String[] args)throws IOException
{
int a=0, b=0, sum;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the numbers to be summed");
try{
a=sc.nextInt();
sc.nextLine();
b=sc.nextInt();
}
catch(InputMismatchException e){
System.out.println("Please enter an Integer number");
e.printStackTrace();}
catch(Exception e){System.out.println(e);}
sum=a+b;
System.out.println(sum);
sc.close();
}
}
I'm supposed to submit it to an online directory, that I assume tries to execute the program automatically. And when I do, it tells me
Wrong Answer Almost there,think some more
I think pondering over it for an hour is more than enough before you decide to call in for reinforcement.
The output should be "a single integer which corresponds to sum, followed by a new line".
But the output of your program is
Enter the numbers to be summed
<the sum>
remove sc.nextLine(). It makes it move to the next line, but since both integers are on the same line, the value for b remains at 0.
These can be solve by two thing command line arguments or Scanner class or BufferReader.
Using the Command line Arguments.
public Class Sum
{
public static void main(String [] args)
{
int a ,b,c;
a=Integer.parseInt(args[0]); //using Integer wrapper Class to cast object
to primitive Datatype Integer.
b= Integer.parseInt(args[1]) ;
c= a+b;
System.out.println("The Sum of two number is : "+c);
}
}
Using Command Line Arguments with code re usability(Method Sum)
public Class Sum
{
public static long sum(int a,int b)
{
return a+b;
}
public static void main(String [] args)
{
int a ,b;
long c; // for long summation of numbers .
a=Integer.parseInt(args[0]); //using Integer wrapper Class to cast object
to primitive Datatype Integer.
b= Integer.parseInt(args[1]) ;
c= sum(a,b);
System.out.println("The Sum of two number is : "+c);
}
}
Using the External resources from the java.util.Scanner
public Class Sum
{
public static void main(String [] args)
{
int a ,b;
long c;
Scanner scan;
scan = new Scanner(System.in) ; //Taking system Keyboard for input.
System.out.println("Enter the value of A: \n");
a= ss.nextInt() ;
System.out.println("Enter the value of B: \n");
b=ss.nextInt();
c= (long) (a+b);
System.out.println("The Sum of two number is : "+c);
}
}
Try this:
import java.util.Scanner;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
int sum = 0;
System.out.println("Enter Number: ");
num1 = in.nextInt();
System.out.println("Enter Number2: ");
num2 = in.nextInt();
sum = num1 + num2;
System.out.println(sum);
}
}
package stack;
public class Satck {
public static int MAX=100;
int top;
int [] a= new int [MAX];
boolean empty()
{
return (top<0);
}
Satck()
{
top=-1;
}
void push(int x)
{
a[++top]=x;
}
public int pop()
{
int x=a[top--];
return x;
}
public int peek()
{
int x=a[top];
return x;
}
public static void main(String[] args) {
Satck s=new Satck();
s.push(10);
s.push(11);
s.push(12);
s.push(13);
System.out.println(s.peek());
System.out.println(s.empty());
System.out.println(s.pop());
System.out.println(s.peek());
}
}
How would I return my x and y variable into main in order to perform the addition?
Thanks in advance for the help!
import java.util.Scanner;
public class calling {
public static int x;
public static int y;
public static void num1() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number: ");
x=scanner.nextInt();
}
public static void num2() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number: ");
y=scanner.nextInt();
}
public static void main(String[] args){ **//place to return variables.**
num1();
num2();
System.out.print("The sum of the two numbers is: " + (x+y));
}
}
public static int getInput() {
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
public static void main(String[] args){
System.out.println("Please enter a number: ");
int x = getInput();
System.out.println("Please enter a second number: ");
int y = getInput();
int sum = x + y;
System.out.print("The sum of the two numbers is: " + sum);
}
or a more OO (Object Orientated) approach might look like
public class Calculator {
private Scanner scanner;
public Calculator() {
scanner = new Scanner (System.in);
}
public int getInput() {
return scanner.nextInt();
}
public int add(int x, int y) {
return x + y;
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println("Please enter a number: ");
int x = calculator.getInput();
System.out.println("Please enter a second number: ");
int y = calculator.getInput();
int sum = calculator.add(x, y);
System.out.print("The sum of the two numbers is: " + sum);
}
Note that Java naming conventions state classes should have uppercase first letters.
You shouldn't be using static data members or methods - those should only be used when the member of method applies to all instances of a class.
In this case the only static method should be main and that should only create a single instance of the current class. main should almost never do any real work - although in this trivial example I suppose an exception could be made.
You should ideally also only create a single Scanner object - the Scanner class is perfectly capable of reading a continuous stream of numbers without you needing to create a new one over and over for each number to be read.
In the code below I just create one and use it twice directly.
import java.util.Scanner;
public class calling {
public calling() {
Scanner scanner = new Scanner (System.in);
System.out.print("Please enter a number: ");
int x = scanner.nextInt();
System.out.print("Please enter a second number: ");
int y = scanner.nextInt();
System.out.println("The sum of the two numbers is: " + (x + y));
}
public static void main(String[] args) {
new calling();
}
}
Alternatively the scanner object could have been stored as a member variable, as in this example:
import java.util.Scanner;
public class calling {
private Scanner scanner = null;
private int getInt(String prompt) {
System.out.print(prompt);
return scanner.nextInt();
}
public calling() {
scanner = new Scanner(System.in)
int x = getInt("Please enter a number: ");
int y = getInt("Please enter a second number: ");
System.out.println("The sum of the two numbers is: " + (x + y));
}
public static void main(String[] args) {
new calling();
}
}
Simply change the return types of num1 and num2 to int and save the result of both functions in variables in main. Then perform your addition with the new variables, or just change the addition to (num1() + num2()).
In addition to that, grab a book and try to understand how to use functions because what you're asking is pretty basic.
if you are looking for a way to return the values to main function, read the code below
import java.util.Scanner;
public class test {
public static int x;
public static int y;
public static int num1() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number: ");
x=scanner.nextInt();
return x;
}
public static int num2() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number: ");
y=scanner.nextInt();
return y;
}
public static void main(String[] args){
int a = num1();
int b = num2();
System.out.print("The sum of the two numbers is: " + (a+b));
}
}