How to input 1~2 instead of 1 2. InputMismatchException - java

So I was solving a problem on Techgig which goes like this :
There I have to print the sequence of Fibonacci numbers till 10 places in array and the first two inputs were entered by the user.
My code goes like:
import java.io.*;
import java.util.*;
public class CandidateCode{
public static void main(String args1[]) throws Exception
{
Scanner sc=new Scanner(System.in);
int first=sc.nextInt();
int second=sc.nextInt();
int [] array=new int[10];
array[0]=first;
array[1]=second;
int i;
for(i=2;i<10;i++)
{
array[i]=first+second;
first=array[i-1];
second=array[i];
}
System.out.print("{"+array[0]);
for(i=1;i<10;i++)
{
System.out.print(","+array[i]);
}
System.out.print("}");
}
}
Now the sample input should go like 1 2 and output should be displayed as {1,2,3,5,8,13,21,34,55,89}
But they have used Test Case as 1~2 and the code when compiled gives InputMismatchException. Please provide me a method to remove this Exception

This code will resolve your problem.
import java.io.*;
import java.util.*;
public class CandidateCode{
public static void main(String args1[]) throws Exception
{
Scanner sc=new Scanner(System.in);
String s=sc.next();
int first=Integer.parseInt(s.substring(0,s.indexOf("~")));
int second=Integer.parseInt(s.substring(s.indexOf("~")+1));
int [] array=new int[10];
array[0]=first;
array[1]=second;
int i;
for(i=2;i<10;i++)
{
array[i]=first+second;
first=array[i-1];
second=array[i];
}
System.out.print("{"+array[0]);
for(i=1;i<10;i++)
{
System.out.print(","+array[i]);
}
System.out.print("}");
}
}
Read a input string of format "Num1~Num2" and then extract the numbers from this string.

Related

Having trouble with java.lang.Math(i get an error stating I'm using an Int and it needs a String)

import java.util.Scanner;
import java.lang.Math;
public class TestMax {
int minNum = 1, maxNum = 5;
public int inputNum() {
Scanner num = new Scanner(System.in);
return inputNum();
}
public void displayNum(int userNum) {
System.out.printf(Math.min(userNum, maxNum));
System.out.printf(Math.max(userNum, minNum));
}
public static void main(String[] args) {
TestMax input;
input = new TestMax();
int userNum = input.inputNum();
input.displayNum(userNum);
}
}
Sorry about any incorrect formatting, it's my first time posting. I'm creating a program for a school in which a user enters a number and the program then outputs the 'maxNum' or 'minNum' depending on whether the number entered is less than or greater than the min/maxNum. I think I have everything right except for when it comes to the math function. I want it to compare the userNum to the min/maxNum but its saying I'm using an int and need a string. Any help would be greatly appreciated.
You need to return a number from Scanner like this:
public int inputNum() {
Scanner s = new Scanner(System.in);
int number = s.nextInt();
return number;
}

are Print Statements inside or outside of For Loops?

I'm coding a program to calculate factorials but can't seem to figure out the part where it actually prints out the final value.
import java.util.*;
public class Factorial {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter integer value: ");
int x=scan.nextInt();
System.out.print(x+"!=");
int y=0;
for(int i=x;i>0;i--) {
//y=x*i;
y=i*(i-1);
if(i==1)
System.out.print(i+"=");
else
System.out.print(i+"*");
//for (int j=2;j>=1
}
System.out.print(y);
}
}
the program is supposed to display the numbers it multiplied by as well
i.e. INPUT=5
OUTPUT= 5!=5*4*3*2*1=120
or
OUTPUT=5!=1*2*3*4*5=120
First thing you need to do is to put the curly brackets on and then indent,so as to decrease the confusion.
The code below does what you intend to and has the necessary comments
import java.util.*;
public class Factorial {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter integer value: ");
int x=scan.nextInt();
System.out.print(x+"!=");
int y=1;// Initialize to 1 not 0 as you'll be multiplying.
for(int i=x;i>0;i--) {
/*
Iteration by iteration:
i = 5,y= 1-> y = 1*5
i = 4,y= 5-> y = 5*4
So on...
*/
y*=(i);
if(i==1)
{
// Print Equal only if its the last number. Since
we are going 5*4*3*2*1 =. We need this if to print
1 =.
System.out.print(i+"=");
}
else
{
//For other cases just print Number and *.
System.out.print(i+"*");
}
}
// Print the actual output.
System.out.print(y);
}
}

SPOJ Life Universe and Everything

I am trying to solve the below problem on spoj with Java6(JAR):-
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
Input:
1
2
88
42
99
Output:
1
2
88
SPOJ is not accepting my solution.I think the below solution has some error. If not, Is there ant special format to write the code on spoj so that my solution will get accepted.
import java.util.*;
class Life
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int arr[] = new int[100];
int a;
for( a=0;a<100;a++)
{
int i = sc.nextInt();
if(i<100)
{
arr[a]=i;
}
if(a>0)
{
if(arr[a-1] > arr[a])
break;
}
}
for(int j=0;j<a;j++)
{
System.out.print(arr[j]);
}
sc.close();
}
}
You didn't understand problem statement perfectly! It is like you have infinite input as integer but stop when you get the input as 42 till that print all the integers you get as an input. So here is the code for it!
import java.util.Scanner;
class Life
{
public static void main(String args[])
{
Scanner sc =new Scanner(System.in);
while(true) //This loop will always run till we break it from inside the loop
{
int ip=sc.nextInt(); //Taking input as an integer
if(ip == 42) //If input is 42 , break the loop
break;
System.out.println(ip); //else print that integer and continue the loop
}
}
}
Accepted Solution of above problem
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<Integer> arrayList = new ArrayList();
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int num = Integer.parseInt(scanner.nextLine());
if(num>=0 && num<100){
if(num == 42){
break;
}
arrayList.add(num);
}
}
Iterator itr = arrayList.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Simple Java Solution
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
if (sc.hasNext())
{
while(true)
{
int n=sc.nextInt();
if (n==42)
{
break;
}
System.out.println(n);
}
}
}
}

Input using scanner class in java

I was making a program to reduce given integers to their simplest ratio.But an error is occurring while taking inputs through Scanner class in a sub-method of program.Here is the code :
package CodeMania;
import java.util.Scanner;
public class Question5
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();// number of test cases
sc.close();
if(T<1)
{
System.out.println("Out of range");
System.exit(0);
}
for(int i=0;i<T;i++)
{
ratio();//line 19
}
}
static void ratio()
{
Scanner sc1=new Scanner(System.in);
int N=sc1.nextInt();//line 26
if((N>500)||(N<1))
{
System.out.println("Out of range");
System.exit(0);
}
int a[]=new int[N];
for(int i=0;i<N;i++)
{
a[i]=sc1.nextInt();
}
int result = a[0];
for(int i = 1; i < a.length; i++)
{
result = gcd(result, a[i]);
}
for(int i=0;i<N;i++)
{
System.out.print((a[i]/result)+" ");
}
sc1.close();
}
static int gcd(int a, int b)
{
while (b > 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
The error is--
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at CodeMania.Question5.ratio(Question5.java:26)
at CodeMania.Question5.main(Question5.java:19)
Here I have used 2 seperate scanner objects sc in main function and sc1 in ratio function to take input from console.
However if I am declaring a public static type Scanner object in class scope and then using only one Scanner object throughout the program to take input then program is working as required without error.
Why this is happening...?
The reason for this error is that calling .close() on the scanner also closes the inputStream System.in, but instantiating a new Scanner will not re-open it.
You need to either pass a single Scanner around in your method parameters, or make it a static global variable.
Since your main() and your ratio() method are using Scanners they throw exceptions,when an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be handled.
An exception can occur for many different reasons, below given are some scenarios where exception occurs.
A user has entered invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run out of memory.
You can handle these exceptions by using Try/Catch blocks,or you can handle them by using the word throws after your method's definition,
in your case these two approaches are going to be like this:
With Try/Catch :
public static void main()
{
try{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();// number of test cases
sc.close();
}
catch(NoSuchElementException e){
System.out.print("Exception handled" + e);
//rest of method
}
static void ratio(){
try{
Scanner sc1=new Scanner(System.in);
int N=sc1.nextInt();}
catch(NoSuchElementException e){
System.out.print("Exception handled" + e);}
//rest of method
}
With "throws":
public static void main()throws Exception{
//rest of method
}
static void ratio()throws Exception
{
//rest of method
}
Try this one. You can pass the scanner as argument
package stack.examples;
import java.util.Scanner;
public class Question5 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();// number of test cases
if (T < 1) {
System.out.println("Out of range");
System.exit(0);
}
for (int i = 0; i < T; i++) {
ratio(sc);// line 19
}
sc.close();
}
static void ratio(Scanner sc1) {
int N = sc1.nextInt();// line 26
//Your Logic
}
static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
import java.util.*;
public class Understanding_Scanner
{
public static void main()
{
Scanner sc= new Scanner(System.in);
System.out.println("Please enter your name");
String name=sc.next();
System.out.println("Your name is:"+name);
}
}
Now to explain this thing so we have to import a scanner class from the Java Utility package so this can be achieved by the code on the first line
the second line is creating a class NOTE (THE NAME OF THE CLASS NEED NOT START WITH CAPITAL) now coming to the main topic Scanner class so for this we must create a scanner class within the program with the code that's been given in the 4th line... in this statement 'sc' is an object which stores the values of the scanner class so if you want to do any operation in the scanner class you can do it via the object 'sc' *NOTE(You can name ur object as anything eg:poop,bla etc)...
then we have this interesting command which says System.in now this allows users to write any statement through the keyboard or any such input devices during run time....
String name=sc.next() this line helps us to write any string that we want to write during the run time, which will b stored in the name variable
So that's it, this is the scanner class for u. Hope its easy to understand.
cheers!! Keep coding :-)

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

Categories

Resources