SPOJ Life Universe and Everything - java

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

Related

Java while loop not breaking after "break" statement

import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
while(true){
if(input == -1){
break;
}
}
System.out.println("Thank you and see you later!");
}
}
The user should be able to put in multiple numbers until -1 is reached. Once its reached it should break the loop and print the last line.
You need to put
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
into your loop, else it will never get new user input
You need call scanner inside loop
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
while(true){
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int input = Integer.parseInt(reader.nextLine());
if(input == -1){
break;
}
}
System.out.println("Thank you and see you later!");
}
}

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

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

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.

Write input lines in reverse order

Write a Java program that takes all the lines input to standard input and writes them to standard output in reverse order. That is, each line is output in the correct order, but the ordering of the lines is reversed.
I wrote this:
public static void main(String[] args) {
Scanner sc=new Scanner (System.in);
System.out.println("Enter the line");
String a=sc.nextLine();
System.out.println("Enter the line");
String b=sc.nextLine();
System.out.println(b+" "+a);
}
Is this efficient?
As suggested by one of the comments a Deque would be a good data structure to achieve this:
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Deque deque = new LinkedList<>();
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your lines (Enter exit to continue):");
while(sc.hasNext()) {
String line = sc.next();
if(line.toLowerCase().equals("exit")) {
break;
}
deque.add(line);
}
System.out.println("\n=====Reversed Lines=====\n");
Iterator reverse = deque.descendingIterator();
while (reverse.hasNext()) {
System.out.println(reverse.next());
}
}
}
Try it here!

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 :-)

Categories

Resources