Java method not running in another file - java

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

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

Calling a method that displays the output pattern only

I'm having a hard time with my second method, The method declaration is:
public static void displayOutput(int loopCount)
The method is called from the main() and is passed the valid input value which determines repetition. The method displays the output pattern only and returns nothing. Every 3rd line displays a space and 3 asterisks
I know I'm not calling each method right in the main() and I know that displayOutput(int loopCout) is wrong.
Could someone explain this to me or use an example that would help write the program?
public static void main(String[] args) {
int repeat;
Scanner goGet = new Scanner(System.in);
repeat = getValidValue(goGet); //Uncompilable source code -Erroneous sym type
displayOutput(repeat);
}
public static int getValidValue() {
int input;
do {
Scanner getInfo = new Scanner(System.in);
System.out.print("Enter an integer Greater than zero: --> ");
input = getInfo.nextInt();
} while (input <= 0);
return input;
}
public static int displayOutput(int loopCount) {
int i;
for (i = 0; i < loopCount; i++) {
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon. ");
System.out.print("The semester is ending soon.*** ");
}
return loopCount;
}
You are passing a value to method getValidValue which doesn’t take any value.
Also displayOutput is returning loopcount but you are not catching it anywhere so after asterisk it is not displaying anything.

Methods for Functions

Note: Desire to move this to Code Review with a clearer structure for answer and my modified code which was very similar to the answer besides calcmin method.
I'm trying to break this code up into multiple methods and I was successful with the first bit but the other two I can't seem to figure out.
With the second method I was trying to make it so it would ask the user for an integer and continually prompts them until a proper integer is entered.
With the third method I was trying to make it so that it takes three integer parameters and returns the minimum value of those parameters.
I'd really appreciate the help on this. I've looked through examples in my book and can't seem to get it.
My code:
import java.util.Scanner;
public class MinOfThreeInts
{
public static void intro ()
{
System.out.println("This program determines the minimum of three ints");
System.out.println("It gracefully reports errors when erroneous data is entered ");
System.out.println("For example, if you type in 'abc' when this program asked for an int");
System.out.println("the program will report the error & ask for another int");
System.out.println("Try giving it bad input ! \n\n");
}
public static void readInt (int value1, int value2, int value3)
{
System.out.print(" Please enter an integer value ");
Scanner console = new Scanner(System.in);
String input = console.nextLine();
Boolean goodInt;
int parsedValue = 0;
goodInt = false;
while (!goodInt)
{
try
{
parsedValue = Integer.parseInt(input);
goodInt = true;
}
catch(NumberFormatException ex)
{
System.out.print(" Invalid input, please enter Int ");
input = console.nextLine();
}
}
value1 = parsedValue;
// Get the second integer
System.out.print(" Please enter an integer value ");
input = console.nextLine();
goodInt = false;
while (!goodInt)
{
try
{
parsedValue = Integer.parseInt(input);
goodInt = true;
}
catch(NumberFormatException ex)
{
System.out.print(" Invalid input, please enter Int ");
input = console.nextLine();
}
}
value2 = parsedValue;
// Get the third integer
System.out.print(" Please enter an integer value ");
input = console.nextLine();
goodInt = false;
while (!goodInt)
{
try
{
parsedValue = Integer.parseInt(input);
goodInt = true;
}
catch(NumberFormatException ex)
{
System.out.print(" Invalid input, please enter Int ");
input = console.nextLine();
}
}
value3 = parsedValue;
}
public static void calcMin (min)
{
int min = value1;
if (value2 < min)
{
min = value2;
}
if (value3 < min)
{
min = value3;
}
// Now report the results
System.out.println(" The minimum value of the three ints is " + min);
}
public static void main(String[] args)
{
value1 = readInt(console);
value2 = readInt(console);
value3 = readInt(console);
min = calcMin(value1,value2,value3);
}
}
You have a couple of issues. I refactored your code and added comments, I stayed close to your code in order to give you insights on where you can improve.
First, the code:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MinOfThreeInts {
//the main method, things start here
public static void main(String[] args) {
//initialize a new scanner that the application will use
Scanner console = new Scanner(System.in);
//print the intro
intro();
//read the values one by one and save them in a variable
int value1 = readInt(console);
int value2 = readInt(console);
int value3 = readInt(console);
//calculate the minimum and save it in the min variable
int min = calcMin(Arrays.asList(value1,value2,value3));
// Now report the results
System.out.println(" The minimum value of the three ints is " + min);
}
/**
* Reads an integer from the given console
*/
public static int readInt(Scanner console) {
System.out.print(" Please enter an integer value ");
//read the input
int parsedValue = 0;
boolean goodInt = false;
//as long as we don't find a valid number
while (!goodInt)
{
try
{
//read the input
String input = console.nextLine();
//try to parse the value
parsedValue = Integer.parseInt(input);
//set goodInt to true so that the while loop will end
goodInt = true;
}
catch(NumberFormatException ex)
{
//if the provivded value was not an integer, print a message and return to the start of the while loop
System.out.print(" Invalid input, please enter Int ");
}
}
return parsedValue;
}
/**
* calculates the minimum of a list of values
*/
public static int calcMin (List<Integer> values) {
//find the minimum and return the value
return Collections.min(values);
}
/**
* prints an intro message
*/
public static void intro () {
System.out.println("This program determines the minimum of three ints");
System.out.println("It gracefully reports errors when erroneous data is entered ");
System.out.println("For example, if you type in 'abc' when this program asked for an int");
System.out.println("the program will report the error & ask for another int");
System.out.println("Try giving it bad input ! \n\n");
}
}
Now, on what you can do to improve:
compile the code does not compile, always take care your code compiles and then slightly edit it until it compiles again
scope your code has multiple declared integers, the problem was that the values were not visible in other methods, if you declare a variable, say int value1 in some method, another method will not be able to see it. If you have another int value1 in that other method, it will only be visible in that specific method and it will actually be another variable
arguments vs return types methods take arguments and return something. The arguments are the input of the method and the returned value is the result of the method. Take for example your method: public static void readInt (int value1, int value2, int value3). This is a method that should read an integer value from the console. However, this method signature says it takes 3 integers as parameter. These integers would be passed by value, since they are primitive types, so you can not pass them, then fill them and then return them. There is also no return type, so the method is not returning something. Since the integer parameters value1, value2 and value3 are only visible in the method scope, you will loose your data. Compare with the new signature: public static int readInt(Scanner console). This method takes a console to read from as a parameter and returns an integer, the number that has been read. This method encapsulates the retry.

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

Using nextLine() and nextInt() together in my context always gets an error

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.

Categories

Resources