I got to calculate the factorial of a number. As a fact factorial of 0 is 1. So I included that case in the function as well.
here's the code:
import java.util.*;
public class Factorial {
static int fact(int n) {
int result;
if (n == 0 || n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
public static void main(String args[]) {
int i, fact = 1;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
fact = fact(n);
System.out.println(fact);
}
}
but if I'm giving input as 0, some exception was raised
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 Factorial.main(Factorial.java:14)
How to resolve this situation?
Edits:
I have changed the exception.All apologies for the thing that yes the code wasn't even 26 lines. I had put some code above as comments before posting just the code here.
This ain't a duplicate. As of the fact I want to know why it doesn't accept 0 as an input. It works perfect for all other inputs.
I use an online Compiler https://www.tutorialspoint.com/compile_java_online.php
Works fine with Java Compiler of the PC JDK 1.7 ,but raises exception on online IDE.
NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. To prevent it from happening, you may consider using hasNextInt() to check if any more tokens are available. Link.
Modified your code and added hasNextInt so that NoSuchElementException is not thrown and sc.close() to close the resource at the end of main method
public static void main(String args[]) {
int fact = 1;
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
int n = sc.nextInt();
fact = fact(n);
System.out.println(fact);
}
sc.close();
}
The online IDE is probably doing some kind of pre-processing of the data that
don't plays very nice with zeros.
TutorialPoint has online compilers for multiple languages and is very likely
that these all share some common backend that does the magic of passing text
from your browser to their servers. I'm not sure what kind of processing is
happening behind but I can imagine that is something like trimming the
unnecessary zeros from the left of the numbers or something like that.
I have encountered the opposite problem in standard C with the function sscanf,
which expected to fail (return 0) when the input string is empty just like its
sister function scanf but it still returns sucess and stores zero in the integer
variables.
By the way, if you just add a leading space or \n to the zero, everything works
just fine.
Related
I have an issue with parallel arrays and getting the program to read integers and doubles. For example, I have a text file with these values:
1234 99.58
5678 1854.99
The first number being an account number and the second number being the balance of the account. I'm not sure how to get them into a parallel array (int[] accountnumber, double[] balance) while going down the list of ideally 10+ accounts and balances.
I've tried filling the arrays separately without success, which doesn't feel like the most efficient method possible. I've tried breaking down the "(int = 0; i < maxAccts; i++)" so I could use the "i" variable for both without resetting it.
public static int readAccts(int[] acctNum, double[] balance, int maxAccts, File myinput, Scanner inputFile) throws IOException {
maxAccts = 0;
while(inputFile.hasNextInt()) {
//Test for reading integers accurately
//System.out.println(inputFile.nextInt());
maxAccts++;
inputFile.nextLine();}
//Test for maxAccts
System.out.println(maxAccts);
acctNum = new int[maxAccts];
balance = new double[maxAccts];
Scanner AccountFiller = new Scanner(myinput);
while(inputFile.hasNext());{
int i = 0;
while (i < maxAccts) {
acctNum[i] = AccountFiller.nextInt();
balance[i] = inputFile.nextDouble();
i++;}
//for (int i = 0; i < maxAccts; i++)
System.out.println(acctNum[1]);}
return maxAccts;
}
I keep getting this error below:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
At this point, I don't know why it's going wrong. In my head the cursor in the document should be right after the integer (account number), and I'm not getting an issue with that part.
You might want to fix your while loop
Your second while loop looks like this:
while(inputFile.hasNext());{
Which has a semicolon between the while and the curly brace, which means that the body of the loop is empty and after it is done looping, you run the code inside the curly braces.
The loop should be like this:
while(inputFile.hasNext()) {
This causes the error of reading the nextDouble since we just consumed the scanner's source until there is no next.
You might also want to check again how you want to read the file, since the first part doesnt really make much sense to me, it appears you just skip over all ints found in the file (while counting how many times you skip)
Im trying to create a method to find the common factors of 2 given numbers but I can not get the file to compile. All of my curly brackets are closed as I'm aware thats usually almost always the cause of this error. Hopefully someone can help me out!
import java.util.Scanner;
public class E1{
public static void main (String [] args){
Scanner kb = new Scanner(System.in);
double n1,n2;
System.out.println("Enter two numbers");
n1=kb.nextDouble();
n2=kb.nextDouble();
printCommonFactors(n1,n2);
}
//call a method that prints the positive shared factors of the 2 inputed numbers
public static void printCommonFactors(int n1,int n2){
//determining the max/min of the two inputed variables
int max,min;
max=Math.max(n1,n2);
min=Math.min(n1,n2);
//setting up 2 arrays to store the factors
int [] maxFactors = new int [max];
int [] minFactors = new int [min];
int counter1;
for (inti=0;i>max;i++)
if (i%max=0)
counter1++;
maxFactors[counter1]=i;
for (int i=0;i>min;i++)
if (maxFactors[i]%min=0)
maxFactors[i]=
}
}
This is the error I receive:
The reason you are seeing the "reached end of file while parsing" is that the parser expects to find a right-hand-side operand for the equals operator but fails to do so. You end your method with maxFactors[i]=. Binary operators always require right-hand-side operands. In this case, you must place a value after the equals-sign.
Also, it looks like you are trying to apply some principles to Java that you probably pulled from another language. The most obvious one here is that you use replace explicit blocks with white-space. This works for languages like Python, but does not work in Java. Indentation is not significant in Java and only has the effect of improving readability.
This is relevant for your for statements. Because you are not actually using blocks, these statements are actually equivalent:
for (inti=0;i>max;i++)
if (i%max=0)
counter1++;
maxFactors[counter1]=i;
for (inti=0;i>max;i++) {
if (i%max=0) {
counter1++;
}
}
maxFactors[counter1]=i;
This will cause issues with i being referenced out of its scope. The other issue with this is that the for initializer (inti=0;) is missing a space and should be int i = 0.
Other issues include trying to allocate arrays with a non-integer size (must be of type int) and using bad test expressions for your for-loops (i>min will invariably remain true if it is ever true due to your incrementor until an integer overflow is reached).
I an coding beginner.I have started practicing SPOJ basic problems.This was the one I was trying to solve , But the code is incorrect.
Please help me where I have coded this question wrong as I am unable to figure out:
public class Print2ndChar {
public static void main(String[] args) throws java.lang.Exception {
Print2ndChar mainObj = new Print2ndChar();
java.io.BufferedReader inputReader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
String noOfTestCase;
if(((noOfTestCase = inputReader.readLine()) == null))
System.exit(0);
int noOfLines = 0;
try{
noOfLines = Integer.parseInt(noOfTestCase);
}catch(Exception e){
System.exit(0);
}
if(noOfLines<0 || noOfLines>100)
System.exit(0);
String [] randomWords = new String[noOfLines];
for(int i=0;i<noOfLines;i++){
randomWords[i] = inputReader.readLine();
if(randomWords[i] == null || randomWords[i].length()<2 || randomWords[i].length()%2!=0 || (randomWords[i].length()/2)>100)
System.exit(0);
}
for (String word : randomWords){
mainObj.letsBegin(word.substring(0, word.length() / 2));
System.out.println();
}
}
private void letsBegin(String data) {
if (data.length() <= 0) {
return;
} else {
System.out.print(data.charAt(0));
if (data.length() >= 3)
letsBegin(data.substring(2, data.length()));
}
}
}
EDIT :
I/P : 4
your
progress
is
noticeable
O/P
y
po
i
ntc
OK! So after a lot of hit and trials, I know what is wrong with your code. The code that you have written fails because of the condition randomWords[i].length()%2!=0 inside your if. There is nothing wrong with you putting this condition to check the input, but if you will select sample test case, inside the highlighted blue area you will notice an extra space after every string. Like this :
You can see that other than the last input all other input strings have a space character at the end. So, when you read the string from stdin the length of the string is 2*k + 1 (because of the space), and your program will exit without any output. Hence you get a wrong answer.
This problem exists with other test cases as well probably. And how do I know this? After spoj shows you wrong answer, if you click on the wrong answer, it will show you 2 failed test cases, something like this:
It shows your program's output is empty because your code exited because of the extra space at the end of strings.
So, I believe the person who wrote the test cases should be given a WT Error (Wrong Test Cases) :P :D
So, the possible correction is you remove the mentioned condition from the if and you will get AC. Because now you will be dividing 2*k + 1 by 2, which will not be an integer and which will get rounded to the nearest smallest integer, which will be same as dividing 2*k by 2 and the program will give the correct result.
A few things that you should take care while solving questions on spoj, you do not have to verify that every input lies within the range specified in the question, or if it is a valid data type. The range is given to tell you that Spoj will only test your program with cases which lie between those ranges and will not exceed them. So, even if you remove all the code where you check for exceptions and ranges of input data, you will get an AC. Moreover, writing such code only adds to the burden.
Hope this helps. :)
I am trying to write a code in which I construct a 52 card pile, then deal the cards out to n number of players (it is possible for some players to have an extra card). The winner is the one with the Ace of Spades card.
Here is my program:
public class CardGame {
public static void main(String[] args) {
System.out.println("Enter the number of players");
int numofPlayers = Integer.parseInt(args[0]);
CardPile gameDeck = CardPile.makeFullDeck();
CardPile [] players = new CardPile[numofPlayers];
for (int i=0;i<numofPlayers;i++) {
int numofnum = i%numofPlayers;
players[i] = new CardPile();
}
for (int i=0;i<52;i++) {
int numofnum =i%numofPlayers;
CardPile curPlayer = players[i%numofPlayers];
Card nextCard = gameDeck.get(i);
players[numofnum].addToBottom(nextCard);
}
for (int i=1;i<numofPlayers;i++) {
if (players[i].find(Suit.SPADES, Value.ACE) != -1) {
System.out.println("Player" + i + "has won!");
}
}
}
}
I keep getting an out of bounds error. The methods that I am calling in this program are well written so the problem should come from this code. Can anyone help ?
Edit : Here is the error that I get
java.lang.ArrayIndexOutOfBoundsException: 0
at CardGame.main(CardGame.java:5)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
>
Thanks !
You're asking for the number of players, but not reading input; instead you're reading the args to the program to figure out the number of players.
Likely you're not passing any arguments on the command line, so it's throwing an exception when you ask for args[0].
You'll want to look into getting input from console within the program, or pass the number of players when you run the program (in which case the println can be removed).
As Alex explained in his answer, the reason is because you are not passing arguments when running your code. If you wish for the code to work then you have to run your code as follow:
java CardGame 5
The above executes your CardGame class and pass 5 as argument to the main method in args[0]. If you are executing the code via some IDE let's assume Eclipse then please see the answer in this question to figure out how to pass argument.
If you wish to replace your code above (to accept input from user) then please replace the following line
int numofPlayers = Integer.parseInt(args[0]);
With the following line
Scanner input= new Scanner(System.in);
int numofPlayers = input.nextInt();
After executing the code will ask you to input the number of players and input a +ve integer value.
If you use the Scanner option then make sure you validate your input against values that are not integer (as well as negative integer). For example, if the input is provided as anything but, integer then you will get InputMismatchException hence, surrounding your input with try{} and catch(){} to catch above exception would be the right way to go about it.
I did go through the other threads on this SPOJ problem, ADDREV (Adding Reversed Numbers), but sadly, I was not able to get an answer by any of the three programs that I have written (in C, Python and Java). I am attaching the code snippets of all three.
Python:
def find_rev(a):
d=0
while(a>=1):
d=d*10+a%10
a=a/10
return d
n=input('enter a number')
for i in range(int(n)):
num1=input('enter the first number')
num2=input('enter the second number')
num=0
num1=find_rev(int(num1))
num2=find_rev(int(num2))
num=num1+num2
num=find_rev(num)
print num
With Python, I get a runtime error.
With C, I get a wrong answer.
#include<stdio.h>
long rev(long);
int main()
{
long int n;
long int n1;
long int n2;
long int i=0;
scanf("%ld",&n);
//printf("%d",n);
for (i=0;i<n;i++)
{
//printf("\n%d",i);
//printf("\nenter the two numbers");
scanf("%ld%ld",&n1,&n2);
n = rev(rev(n1)+rev(n2));
printf("%ld\n",n);
}
return 0;
}
long rev(long a)
{
long d=0;
while(a>=1)
{
d = d*10+a%10;
a = a/10;
}
return d;
}
With Java, I get a compilation error.
import java.util.*;
//import java.io.*;
public class spoj_prob {
public static void main(String args[])
{
long n=0;
System.out.println("enter a number \n");
Scanner in=new Scanner(System.in);
n=in.nextLong();
long n1=0;
long n2=0;
long sum=0;
for (int i=0; i<n; i++)
{
System.out.println("enter two numbers \n ");
n1=in.nextLong();
n2=in.nextLong();
n1=rev(n1);
n2=rev(n2);
System.out.println(n1);
System.out.println(n2);
sum=rev(n1+n2);
System.out.println(sum);
}
}
static long rev(long a)
{
long d=0;
while (a>=1)
{
d=d*10+a%10;
a=a/10;
}
return d;
}
}
}
Of course, those errors are reported by the SPOJ Judge. The programs work fine on my system. Test cases I use are:
2
999999999 11
999 11
Answer
101
101
Also
3
34 54
123 091
00034 00054
Update: Guys, I got the answer in C. Thank you for all the help.
Before you start using any service, it's generally a good thing to read its FAQ. It explains how exactly the program should receive data.
In particular, please notice that printing enter a number and other junk to the console will always lead to a wrong answer. Because a correct program would output something like
34
1998
1
and yours
enter a number
enter two numbers
34
enter two numbers
1998
enter two numbers
1
I can't tell why Java fails to compile, though. You probably should find some information on how to submit in Java with the reference solution.
Also, the problem definition gives no limit for input numbers, so they can possibly be too big for standard integer types in Java and C++.
With Python I think you're getting Runtime Error because you're calling a restricted function input, nothing else comes to mind.
In C you're getting WA because the input integers can be very large, and you're overflowing.
For JAVA there are 2 potential problems that you may have. One is that you're using Scanner class which may not be supported by SPOJ (due to security or other considerations). Second, is that your class name needs to be Main I think. Please search SPOJ forum for more details on this.
Try this solution in Python 3:
import sys
t = int(input())
i=0
while i<t:
a,b = map(int,sys.stdin.readline().split()) #to take both inputs in single line
c=str(a) #converting the number into string
d=str(b)
e=int(c[::-1]) #converting reverse of the string c to int
f=int(d[::-1]) #converting reverse of the string d to int
s=e+f #adding the two reverse numbers
s1=str(s)
s2=int(s1[::-1]) #reverse s and display it
print(s2)
i+=1