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 :-)
Related
I am new to JAVA. I want to create a class and write a function in it. I then want to use that function in the main class.
import java.util.Scanner;
public class multi_fun {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a, b, c;
System.out.println("Enter 1st number: ");
a = scan.nextInt();
System.out.println("Enter 2nd number: ");
b = scan.nextInt();
Addition obj = new Addition();
c = obj.add(a,b);
System.out.println("The sum is "+c);
scan.close();
}
}
class Addition{
public int add (int a, int b)
{
return(a+b);
}
}
The problem I think according to error message you mentioned in the comments:
Exception in thread "main" java.lang.NoSuchMethodError:
Addition.add(II)I at multi_fun.main(multi_fun.java:15)
It seems that you are putting class Addition declaration in the same source file of multi_fun.java program.
You should create a java class file called Addition.java and put your class code in it:
class Addition{
public int add (int a, int b)
{
return(a+b);
}
}
After that it should work without any errors.
Update:
You can check this Answer which explain Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'it would be a useful solution to your problem.
Make sure both the java files are in the same folder.
MultiFun.java
import java.util.Scanner;
public class MultiFun {
public static void main(String[] args) {
Addition obj = new Addition();
Scanner scan = new Scanner(System.in);
int a, b, c;
System.out.println("Enter 1st number: ");
a = scan.nextInt();
System.out.println("Enter 2nd number: ");
b = scan.nextInt();
c = obj.add(a, b);
System.out.println("The sum is " + c);
scan.close();
}
}
Addition.java
class Addition {
public int add(int a, int b) {
return (a + b);
}
}
run the following commands
javac MultiFun.java
java MultiFun
import java.util.Scanner;
public class multi_fun {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a, b, c;
System.out.println("Enter 1st number: ");
a = scan.nextInt();
System.out.println("Enter 2nd number: ");
b = scan.nextInt();
add(a,b);
System.out.println("The sum is "+c);
scan.close();
}
}
public static int add (int a, int b)
{
return(a+b);
}
The reason for this error is that there was already an other file in the same folder named Addition. So when I wrote a Class with the same name and tried to create an object, it was giving error message, as the parameters where different.
Thank you everyone for your help.
If you are run your program using Terminal or command prompt(cmd) make sure to run the class that have main method(created object from Addition class). And also do not create main methods in both classes and do not add public to Addition class.
One last thing: compile and run only the main class(multi_fun). Which is,
javac multi_fun.java
java multi_fun
Here is the file that contains the method:
package getmethodical;
import java.util.Scanner;
public class GetMethodical {
public static void main(String[] args) {
}
// Validate INT input and checks if it's in range
public static int getRangedInt(Scanner pipe, String prompt, int low, int high){
System.out.println("Inside getRangedInt");
System.out.println(prompt);
String trash = "";
int value = -5;
boolean flag = false;
while(!flag){
if(pipe.hasNextInt()){
value = pipe.nextInt();
pipe.nextInt();
if(value >= low && value <= high){
flag = true;
}else{
System.out.println("Please enter a number from 0 to 100");
}
}else{
trash = pipe.nextLine();
System.out.println(trash + " is not a valid input, please enter a number");
pipe.nextLine();
}
}
return value;
}
}
In in another java file I'm trying to call the method:
package getmethodical;
import java.util.Scanner;
public class BirthDateTime {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner pipe = new Scanner(System.in);
// Year
String prompt = "Enter input: ";
int high = 10;
int low = 0;
GetMethodical.getRangedInt(pipe, prompt, low, high);
}
}
I want to call getRangedInt which is a class in one java main file in another java main file. When I do run the 2nd block, it runs successful but it doesn't call the method.
When I call the method in the main class of the file it's established in and then call it in another file it works.. This is really confusing to write over text so please let me know if there's anything else you need
your main method is having
Scanner pipe = new Scanner(System.in);
This will expect an input from the console. comment out this line and hard code this pipe value for the below method to see u r getting anything as output.
GetMethodical.getRangedInt(<some value>, prompt, low, high);
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);
}
}
}
}
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT.
int a,b,n;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
Scanner sv=new Scanner(System.in);
b=sv.nextInt();
Scanner st=new Scanner(System.in);
n=st.nextInt();
for(int i=0;i<n;i++)
{
int c=0;
c=2*c*b;
int result=a+c;
System.out.print(result+ " ");
}
}
}
I tried using scanner class but it is not executed by eclipse as it only shows sc,sv and st objects of scanner class is resource leaked and never closed.
Well, it appears you have some configs that keep your program from compiling and running based on the resource leaking (not an Eclipse user). Your code compiles and runs with Intellij on my machine so you have a few choices.
Change your configuration to ignore the warning/error. (not recommended)
Close the one Scanner you need. (scanner.close()) You can get more than one value from the single scanner. So, ditch the other ones.
To accomplish (2) another way you could use try-with-resources block and it will be closed automatically at the end of the try.
try (Scanner sc = new Scanner(System.in)) {
// put your code to get input here
} catch (IOException ioe) { ... }
In addition to the scanner issues you're asking about, you have a significant error in your code that will make it impossible to get any meaningful/accurate output. Consider...
for (int i = 0; i < n; i++) {
int c = 0;
c = 2 * c * b;
int result = a + c;
System.out.print(result + " ");
}
c is made anew on each loop and assigned a value of 0 and so c = 2 * c * b; will equal 0 always; and a + c will then always just equal a.
Dont need to create a new Scanner Object...
just do:
int a, b, n;
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
n = sc.nextInt();
for (int i = 0; i < n; i++) {
int c = 0;
c = 2 * c * b;
final int result = a + c;
System.out.print(result + " ");
}
I was typing this out when #Xoce was posting his answer, so it's exactly the same as his :)
The only other thing that I'd like to add is that if you're using IntelliJ, try pressing control-alt-i to auto-indent your code.
public static void main(String[] args) {
//Enter your code here. Read input from STDIN. Print output to STDOUT.
int a,b,n;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
n=sc.nextInt();
for(int i=0;i<n;i++)
{
int c=0;
c=2*c*b;
int result=a+c;
System.out.print(result+ " ");
}
}
I'm writing some Java code that'll make a guessing game, where a random number is generated based on your maximum value and you have to guess the correct number. You can also set the amount of attempts you can get. This is where the problem occurs.You see, you can set a number of attempts in number form or write out "unlimited". I have an example of the code that does this here with comments to help you out:
import java.util.Scanner;
public class Game{
public static int processMaxAttempts;
public static Scanner maxAttempts;
public static String processMaxAttempts2;
public static void main(String args[]){
//Prints out text
System.out.println("Fill in your maximum attempts OR write \"unlimited\".");
//Creates a scanner
maxAttempts = new Scanner(System.in);
//Looks at the scanner "maxAttempts" and reads its integer value
processMaxAttempts = maxAttempts.nextInt();
//Looks at the scanner "maxAttempts" and reads its string value
processMaxAttempts2 = maxAttempts.nextLine();
//Prints out "unlimited" if "maxAttempts" has a string value and "set" if it has an integer value
if(processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}//Close else
}//Close main method
}//Close class
What happens is a get an error that says this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:857)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at com.pixelparkour.windows.MainGameWindow.main(MainGameWindow.java:34)
That error targets this line of code:
processMaxAttempts = maxAttempts.nextInt();
So... yeah. I have no idea. I'm very new to Java (I've been learning it for only 3 days) and I'm a bit helpless. I'd love to know what my problem is so I can apply to it the future and program some cool games!
You need to put a check on content type before reading the content.
What you need is :
if(maxAttempts.hasNextInt()){ // this will check if there is an integer to read from scanner
processMaxAttempts = maxAttempts.nextInt();
} else {
processMaxAttempts2 = maxAttempts.nextLine();
}
if(processMaxAttempts2!=null && processMaxAttempts2.equals("unlimited")){
System.out.println("unlimited");
}else{
System.out.println("set");
}
I think this is what you are looking for
public class Test
{
private int guessableNumber;
private Integer maxAttempts;
public Test()
{
maxAttempts = 0;
}
public void doYourStuff(){
Scanner scan = new Scanner(System.in);
Random random = new Random();
System.out.println("Please enter your amount of guesses or type unlimited for unlimited guesses");
String s = scan.next();
if(s.toUpperCase().equals("UNLIMITED")){
guessableNumber = random.nextInt(100);
}
else {
try{
maxAttempts = Integer.parseInt(s);
guessableNumber = random.nextInt(100) + Integer.parseInt(s);
}catch(Exception e){
System.out.println("You did not enter a valid number for max attempts");
}
}
int counter = 0;
System.out.println("Type in a guess");
while(scan.nextInt() != guessableNumber && counter <=maxAttempts){
System.out.println("You did not guess correctly try again");
++counter;
}
if(counter > maxAttempts){
System.out.println("You have exceeded your max attempts");
}
else {
System.out.println("Correct you guessed the correct number: "+ guessableNumber);
}
}
public static void main(String[] args)
{
Test test = new Test();
test.doYourStuff();
}
}
One little trick that always works for me is just going ahead and making a second scanner, i.e. num and text, that way you can always have one looking for int values and the other dealing with the Strings.