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());
}
}
Related
in this code i want to take no. of testcases by keyboard input and rest is the same problem. only what i am doing is like. if i take 2 test cases then it shud be print the result based on both cases after taking the complete input. For example: INPUT testcases : 2 //case1// 5(no of building) 7 5 2 11 1 //case2// 3(no. of building) 1 2 3 OUTPUT 7//OUTPUT FOR 1ST CASE// 0//OUTPUT FOR 2ND CASE// HOPE, NOW PROBLEM IS CLEAR
import java.util.Scanner;
public class Komal {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("enter the test cases");
int T=sc.nextInt();
for(int i=1;i<=T;i++)
{
System.out.println("total no of building");
int n=sc.nextInt();
int ar[]=new int[n];
for(int j=0;j<n;j++)
{
System.out.println("enter the heights");
ar[j]=sc.nextInt();
}
for(int j=1;j<ar.length;j++)
{int sum=0;
if(ar[0]<ar[i])
{
break;
}else
{
sum += (ar[0]-ar[i]);
}
System.out.println(sum);
}
}
}
}
Here is the complete code. Luckily i had my laptop running and this isn't a very difficult program.
public class TillGreater{
public static void main(String args[]){
int[] ar = {5,4,2,7,1};
int sum=0;
for(int i = 1 ; i < ar.length;i++){
if(ar[0]<ar[i]){
break;
}else{
sum = sum + (ar[0]-ar[i]);
}
}
System.out.println(sum);
}
}
try this:
public static int SumUntilBigger(int[] a)
{
int sum=0;
for(int i=1;i<a.length;i++)
{
if(a[i]<=a[0])
sum+=a[0]-a[i];
else
return sum;
}
return sum;//will reach this statement if all the elements are bigger than the first one
}
this compares each element with the first element and when the element is bigger it just return the sum and exits from method, if all elements are bigger than the first one just return the sum of all differences.
you can use it in main like this:
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("enter the size of the array");
int size=s.nextInt();
int[] a=new int[size];
System.out.println("enter the array values");
for(int i=0;i<size;i++)
a[i]=s.nextInt();
System.out.println("The differences sum : "+SumUntilBigger(a));
}
I'm trying to get my program to repeat, but it's not working out too well. This is what I have so far:
import java.util.*;//to use scanner class
public class ArrayDemo
{
public static void main(String args[])
{
int a[]=new int[5];
Scanner sc=new Scanner(System.in);//use to take input
int i;
for(i=0;i<a.length;i++)//arrayname.length gives the length of array
{
System.out.println("Enter number:");
a[i]=sc.nextInt();
}
int sum=0;
long pro=1;
int max=a[0];
int min=a[0];
for(i=0;i<a.length;i++)
{
sum=sum+a[i];
pro=pro*a[i];
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
float avg=sum/a.length;
System.out.print("You entered");
for(i=0;i<a.length;i++)
{
System.out.print(", 1"+a[i]);
}
System.out.println("\nThe sum of those numbers is "+sum);
System.out.println("The product of those numbers is "+pro);
System.out.println("The largest number entered is "+max);
System.out.println("The smallest number entered is "+min);
System.out.println("The average of the numbers entered is "+avg);
}
}
I have another program that I'm trying to work into repeating, but it says no main applets or methods to be found, so it doesn't return anything:
import java.util.*;//to use scanner class
public class ArrayDemo
{
public static void myMethod(Scanner scanner)
{
int a[]=new int[5];
int i;
for(i=0;i<a.length;i++)//arrayname.length gives the length of array
{
System.out.println("Enter number:");
a[i]=scanner.nextInt();
}
int sum=0;
long pro=1;
int max=a[0];
int min=a[0];
for(i=0;i<a.length;i++)
{
sum=sum+a[i];
pro=pro*a[i];
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
float avg=sum/a.length;
System.out.print("You entered");
for(i=0;i<a.length;i++)
{
System.out.print(","+a[i]);
}
System.out.println("\nThe sum of those numbers is "+sum);
System.out.println("The product of those numbers is "+pro);
System.out.println("The largest number entered is "+max);
System.out.println("The smallest number entered is "+min);
System.out.println("The average of the numbers entered is "+avg);
System.out.println();
do {
myMethod (scanner);
System.out.println("You want to continue : (Y/N) ");
} while("Y".equalsIgnoreCase(scanner.next().trim()));
scanner.close ();
}
}
You need a main method like
public static void main(String args[])
Scanner scanner = new Scanner(System.in);
do {
myMethod (scanner);
System.out.println("You want to continue : (Y/N) ");
} while("Y".equalsIgnoreCase(scanner.next().trim()));
scanner.close ();
}
so move this code to a main method from your (my) `myMethod
Your first code has main method:
public static void main(String[] args) {// some code }
but second code has not this method. In the java language a program must start from main method with above signature.
In your 2nd approach you don't have the main method. So you can't run the file.
Another thing is don't put all the logic in main method. Try your best to separate them as much as possible. Then it is more clear.
Put your calculation logic to a method and call it from a while or do while loop
e.g.
class A{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int[] a= new int[5];
boolean bRepeat = true;
while(bRepeat){
for(i=0;i<a.length;i++){
System.out.println("Enter number:");
a[i]=sc.nextInt();
}
System.out.println("Sum is " + getSum(a));
System.out.println("Average is " + getAvergae(a));
.....
System.out.println("Do you wanna repeat? T/F");
String response = scanner.nextLine();
if(response.equalsIgnoreCase("T"))
bRepeat = true;
else
bRepeat = false; // or break
}
}
public static int getSum(int[] number){
//logic
}
public static double getAverage(int[] number){
//logic
}
public static int getProduct(int[] number){
//logic
}
public static int getMax(int[] number){
//logic
}
................
}
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
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++;}
}}
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));
}
}