blank output, error with scanner/jvm? - java

I rechecked this code tons of times and am pretty sure there isn't anything wrong with it, I thought theres a problem with scanner or return statement but even though I changed it still the problem persists. can anyone pleeease point out my flaw is it the scanner im goin nuts. the output is showing blank is my jvm spoilt
import java.util.Scanner;
public class draft {
int num;
int num2;
int result;
int multiplier;
draft(int set){
this.multiplier = set;
};
public void question(){
Scanner kb = new Scanner(System.in);
System.out.println("Enter number of choice: ");
int a = kb.nextInt();
this.num = a;
System.out.println("Enter number 2: ");
int b = kb.nextInt();
this.num2 = b;
}
public void multiply(){
result = num * multiplier + num2 * multiplier;
System.out.print(result);
}
public static void main(String[] args) {
draft aaa = new draft(5);
aaa.question();
aaa.multiply();
}
}

You must add your numbers, click under "Enter number of choice" and add number:
public static void main(String[] args) {
Draft g = new Draft(2);
g.question();
g.multiply();
}
Consol:
Enter number of choice:
4
Enter number 2:
2
12

Related

How to call strings from other methods into main method?

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!

Program that reads num and prints from 1 to num

i need help in logic, i need the program to read an integer from user and then prints all the integers from 1 to num1. here's what i got :
import java.util.Scanner;
public class test
{
public static void main(String []args)
{
Scanner scan = new Scanner(System.in);
int num1;
int num2;
System.out.println("Enter any number:");
num1 = scan.nextInt();
while (num1<=num2) {
System.out.println(num+1);
}
}
}
Try this out:
import java.util.Scanner;
class test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number;
System.out.println("Enter any number:");
// Note : The below statement will fail if user does not enter integer value
number = scan.nextInt();
// You can use while loop as well but for loop provides cleaner approach for iteration
for (int i = 1; i <= number; i++) {
// Print numbers sequentially from 1 to number
System.out.println(i);
}
}
}
Program that reads num and prints from 1 to num
Try,
System.out.println("Enter any number:");
num1 = scan.nextInt();
int i=1;
while (i<=num1) {
System.out.println(i);
i++;
}
do like this
int num1=0;
int num2=0;
System.out.println("Enter any number:");
num1 = scan.nextInt();
while (num2 <= num1) {
System.out.println(num2);
num2++;
}
thanks alot guys! its been couple of years since last i coded a java program so im a little rusty! here's my final code :
import java.util.Scanner;
public class test
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int num;
int a=1;
System.out.println("Enter any number:");
num=scan.nextInt();
while (a<=num)
{
System.out.println(a);
a++;}
}}

A simple java program

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());
}
}

Add Problems In java

I want to take input of two variable as integer and than do addition with the two variables.
The ans will stored in another variable. The program will repeat after every addition end and will ask for user input of varibles and will do addition again.
My qus is taht how can i add all aditions ans again:
Exm:
Input a= 5
Input b=5
ans=10
Agin program will ask for
Input a= 6
Input b= 6
ans=12
now how can i take all " ans " value with program and do additions of all "ans"
Final Ans=10+12=22
code:
import java.io.*;
import java.util.Scanner;
public class math{
public void add()
{
Scanner keyboard = new Scanner(System.in);
int a;
int b;
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c=a+b;
System.out.println("\nans is :"+c);
math ob_m=new math();
ob_m.add();
}
public static void main(String args[])
{
math ob_main=new math();
ob_main.add();
}
}
The code just do addition one after another but i want that it will do one more task that ....
It all add all aditions reasuts also. how can i do it?
import java.io.*;
import java.util.Scanner;
public class Test {
int a;
int b;
int sum = 0;
public void add() {
Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
sum = sum + (a + b);
System.out.println("\nans is :" + (a + b));
}
public static void main(String args[]) {
Test ob_main = new Test();
while (true) {
ob_main.add();
}
}
}
Just keep adding the intermediate sums to another variable, so at the end you get the final total.
Another alternative (though not preferable when simple solution is available) is to put these sums in a list and at the end iterate through the list and calculate the final total.
Also, do not use ob_m.add(); - just call add();
Store every answer in an additional variable. Then when you're done, sum all the answer variables
You can use a loop for repeating your action, and store each addition in a total sum?
Change
public void add() {
Scanner keyboard = new Scanner(System.in);
int a;
int b;
int total = 0;
for(int i = 0; i < 2; i++) {
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c = a+b;
total += c;
}
System.out.println("\nans is :"+total);
}
Have a total variable which you just keep adding c to.
I also changed your unneeded recursion into a while-loop.
public class math
{
public static void main(String args[])
{
int total = 0;
Scanner keyboard = new Scanner(System.in);
while (true)
{
System.out.print("\nEnter a (-999 to quit): ");
int a = keyboard.nextInt();
// terminating condition, modify appropriately
if (a == -999)
break; // break out of the while-loop
System.out.print("Enter b: ");
int b = keyboard.nextInt();
int c = a + b;
total += c;
System.out.println("\nans is: " + c);
}
System.out.println("total is: " + total);
}
}
have a field GrandSUM,
GrandSum = 0;
and after every addition, add ans to it.
GrandSum += ans;
at the end , GrandSum will have result you want.
Edit:
import java.io.*;
import java.util.Scanner;
public class math{
int GrandSum = 0;//added
public void add()
{
Scanner keyboard = new Scanner(System.in);
int a;
int b;
System.out.print("\nEnter a : ");
a = keyboard.nextInt();
System.out.print("Enter b : ");
b = keyboard.nextInt();
int c=a+b;
GrandSum += c;//added
System.out.println("\nans is :"+c);
}
public static void main(String args[])
{
math ob_main=new math();
ob_main.add();
//.....repeat as many times you want
ob_main.add();
System.out.println("grandsum: " + ob_main.GrandSum);
}
}
package farzi;
import java.util.ArrayList;
import java.util.Scanner;
public class dummy {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
ArrayList<Integer> sum = new ArrayList<Integer>();
String choice = "";
do{
System.out.println("enter the first number");
int a = keyboard.nextInt();
System.out.println("enter the second number");
int b = keyboard.nextInt();
int tempSum = a+b;
list1.add(a);
list2.add(b);
sum.add(tempSum);
System.out.println("Do you want to continue : type yes or no");
choice = keyboard.next();
}while(choice.toLowerCase().charAt(0)=='y');
System.out.println("here are the inputs with theri sum");
System.out.println("num1\t num2\t sum");
for(int i=0;i<list1.size();i++)
{
System.out.println(list1.get(i)+"\t"+list2.get(i)+"\t"+sum.get(i));
}
}
}

How would I return x and y from different classes to main in Java?

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));
}
}

Categories

Resources