How to close Scanner opened in a method JAVA - java

I started learning JAVA a couple of days ago, so my question might be too basic.
I have created a piece of code which is as follows:
import java.util.Scanner;
public class Que01 {
public static void main(String[] args) {
int principle=acceptInt("Principle");
int roi=acceptInt("Rate Of Interest");
int years=acceptInt("Years");
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(String s1)
{ System.out.println("Please Enter value for "+s1+" :");
Scanner sc = new Scanner(System.in);
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}
I want to know where should I write:
sc.close();
Also:
Any other suggestion to code for improvement are Welcome!

You should not close the scanner do not worry about that it will terminated after calculating the simpleInterest. When you run the program and after entering required values it will calculate and return the result and quit.
In you code 1 improvement is you should not create Scanner object again and again there should be only 1 object of Scanner throughout the life cycle.
Below is your updated code -
public class Que01 {
private static Scanner sc = null;
public static void main(String[] args) {
sc = new Scanner(System.in);
int principle=acceptInt("Principle");
int roi=acceptInt("Rate Of Interest");
int years=acceptInt("Years");
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(String s1)
{ System.out.println("Please Enter value for "+s1+" :");
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}
Create Scanner on start of the program and use it again and again. thats it
hope this will help you.

Thanks to Vince, I was able to create a good version of my code.
and this is the answer I needed.
public class Que01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int principle=acceptInt(sc,"Principle");
int roi=acceptInt(sc,"Rate Of Interest");
int years=acceptInt(sc,"Years");
sc.close();
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(Scanner sc,String s1)
{ System.out.println("Please Enter value for "+s1+" :");
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}```

import java.util.Scanner;
public class Que01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int principle = acceptInt("Principle", false, sc);
int roi = acceptInt("Rate Of Interest", false, sc)
int years = acceptInt("Years", true, sc);
float si = simpleInterest(principle, roi, years);
System.out.println("Simple Interest for given details is : " + si);
}
static int acceptInt(String s1, boolean closeScanner, Scanner sc) {
System.out.println("Please Enter value for " + s1 + " :");
int i = sc.nextInt();
if (closeScanner)
sc.close();
return i;
}
static float simpleInterest(int p, int r, int yr) {
return p * yr * r / 100;
}
}
i am not sure if this is a good practice of passing boolean as parameter to decide to close scanner

import java.util.Scanner;
public class Que01 {
Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int principle = acceptInt("Principle");
int roi = acceptInt("Rate Of Interest");
int years = acceptInt("Years");
float si = (p * yr * r/100);
System.out.println("Simple Interest for given details is : " + si);
}
static int acceptInt(String s1) {
System.out.println("Please Enter value for " + s1 + " :");
int i = sc.nextInt();
sc.close();
return i;
}
}
This is what I would say but I'm not an expert. sc.close just saves anything you did with the scanner, eg. writing to a file and saving the file. - thus in this scenario I wouldn't even use it. I also wouldn't use a method to calc the si unless you plan to use it elsewhere as it's just taking up more space

Related

Two lines of my System.out.println code do not work and I cannot figure out why

I recently made a simple calculator that calculates the perimeter and area of a rectangle when you give it the measurements of two sides. However, two of my lines of System.out.println are not working. How can I fix this?
Here is the code:
import java.util.Scanner;
class Rectangle
{
static int n;
static int m;
Scanner s= new Scanner(System.in);
//The below two System.out.println lines do not work. How do I fix this?
System.out.println("Enter the width:")
n = s.nextInt();
System.out.println("Enter the length:");
m = s.nextInt();
public static void main(String args[])
{
int Area;
Area=n*m;
System.out.println("Area = " + Area);
return;
}
private static int solvePerimeter;
{
int Perimeter;
Perimeter = 2*(m+n);
System.out.println("Perimeter = " + Perimeter);
Print statements should be inside a function.
Change your code to :
import java.util.Scanner;
class Rectangle
{
static int n;
static int m;
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.println("Enter the width:")
n = s.nextInt();
System.out.println("Enter the length:");
m = s.nextInt();
}
You also need to declare two separate functions for area and perimeter and call from main method.
Your System.out.println("Enter the width:"); should be inside a method. Other than any variable declaration, everything should be inside methods.
import java.util.Scanner;
class Rectangle
{
static int n;
static int m;
Scanner s= new Scanner(System.in);
//The below two System.out.println lines do not work. How do I fix this?
public void readArguments() {
System.out.println("Enter the width:");
n = s.nextInt();
System.out.println("Enter the length:");
m = s.nextInt();
}
public static void main(String args[])
{
int Area;
readArguments();
Area=n*m;
System.out.println("Area = " + Area);
return;
}
private static int solvePerimeter;
{
int Perimeter;
Perimeter = 2*(m+n);
System.out.println("Perimeter = " + Perimeter);

Eclipse outputting strange string at end of code

Recently I began noticing that at the end of every code I run through Eclipse, it will end with an anomaly:
[0x7FFABD5170E3] ANOMALY: use of REX.w is meaningless (default operand size is 64)
If seeing the entire code helps, here it is:
import java.util.Scanner;
public class FracCalc {
static Scanner sc = new Scanner(System.in);
public static int inputA(){
System.out.print("Integer A: ");
int x = sc.nextInt();
return x;
}
public static int inputB(){
System.out.print("Integer B: ");
int x = sc.nextInt();
return x;
}
public static double division(double n, double d){
double a = (n / d);
return a;
}
public static void main(String[] args) {
int numerator = inputA();
System.out.println("Divided by...");
int denominator = inputB();
double answer = division(numerator, denominator);
System.out.println(answer);
}
}
If someone could help explain why this is happening that would be very appreciated.

Use scanner only from main method

I have this class (with setters, getters and one method) that asks from a user a number indefinitely until he types -1.
I've called the Scanner Method from both, the main method and the class itself, is there a way to call the Scanner method only once only from the main method and apply the input to the class every time it is needed? I really appreciate your help. If something is not clear, please contact me.
Here's the Class Code:
public class calculation {
int current = 0;
int maxNum = 0;
int minNum;
int counter=0;
float sum = 0;
float avg;
Scanner scan = new Scanner(System.in);
public void setMin(int min){
this.minNum = min;
}
public int getMin(){
return minNum;
}
public void setMax(int max){
this.maxNum = max;
}
public void setSum(float sum){
this.sum += sum;
}
public void minMax(int current){
setMin(current);
while(current!=-1){
setSum(current);;
if(current>getMin()){
setMax(current);
}else if(current<getMin()){
setMin(current);;
}
current = scan.nextInt();
counter++;
}
System.out.println("The smallest number you entered was: \n" + minNum);
System.out.println("The biggest number you entered was: \n" + maxNum);
System.out.println("The sum of all those numbers is: \n" + sum);
System.out.println("The avarege number is: \n" + (sum/counter));
}
}
And here's the main method code:
public class minusOne {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
calculation cal1 = new calculation();
System.out.println("Type numbers at will, when finish, type -1 and press enter");
cal1.minMax(scan.nextInt());
scan.close();
}
}
From what I understand, you don't want to have two call to new Scanner(System.in);
To avoid this, you can simply, in your class calculation, write :
Scanner scan;
And add a constructor :
public calculation(Scanner sc){
scan = sc;
}
Of course, in the main method you should write :
new calculation(scan)
I hope I answered your question
Note: in Java your classes name should start with uppercase letter, it should be Calculation
You have some alternatives for this, you can have your Calculator class with a constructor that takes a Scanner as a parameter and then store it in a field, or you cand have a public field in the Calculator class and in your main when you get the scanner just affect this field (but it should be private, you can change it via getters and setters methods).
/* This is the first option*/
public class Calculation {
int current = 0;
int maxNum = 0;
int minNum;
int counter=0;
float sum = 0;
float avg;
private Scanner scan;
public Calculation(Scanner scan){
this.scan = scan;
}
public int setCurrent(int current){
this.current = current;
return current;
}
public void setMin(int min){
this.minNum = min;
}
public int getMin(){
return minNum;
}
public void setMax(int max){
this.maxNum = max;
}
public void setSum(float sum){
this.sum += sum;
}
public void minMax(int current){
setMin(current);
while(current!=-1){
setSum(current);;
if(current>getMin()){
setMax(current);
}else if(current<getMin()){
setMin(current);;
}
current = setCurrent(current);;
counter++;
}
System.out.println("The smallest number you entered was: \n" + minNum);
System.out.println("The biggest number you entered was: \n" + maxNum);
System.out.println("The sum of all those numbers is: \n" + sum);
System.out.println("The avarege number is: \n" + (sum/counter));
}
}
/* Second option */
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
calculation cal1 = new calculation();
//if the field scan in Calculation is public
cal1.scan = scan;
//if it is private
cal1.setScan(scan);
System.out.println("Type numbers at will, when finish, type -1 and press enter");
cal1.minMax(scan.nextInt());
scan.close();
}

Whats wrong in my code?

I seems like I cant skip over the while loop as my code does not understand that I typed in the right number.
import java.util.Scanner;
public class HelloWorld1{
static Scanner userInput = new Scanner(System.in);
static int randomNumbe
public static void main(String[] args){
System.out.println(randomNum());
int randomGuess = -1 ;
while(randomGuess != randomNum()){
System.out.println("Guess a number between 0 to 100");
randomGuess = userInput.nextInt();
}
System.out.println("Yes the random number is:" + randomGuess);
}
public static int randomNum(){
randomNumber = (int) (Math.random()*101);
return randomNumber;
}
}
When you call randomNum(), you're getting another random value back. Try:
int expected = randomNum();
System.out.println(expected);
int guess = -1;
while(guess != expected) {
...
}
package randomguess;
import java.util.Scanner;
public class RandomGuess {
/**
* #param args the command line arguments
*/
static int randomNumber = 0;
public static int getRandomInt() {
randomNumber = (int) (Math.random()*101);
return randomNumber;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int guessInt = sc.nextInt();
int randomInt = getRandomInt();
while(guessInt != randomInt) {
System.out.println("Better luck nextTime :D Random number was "+randomInt);
guessInt = sc.nextInt();
randomInt = getRandomInt();
}
System.out.println("Yeah! You are oracle!");
}
}
Here is probably what you want. Let me know if it is.

Methods' outputting twice with arrays

I have to basically make a program that would add a name given a prompt and place it in the array. It should do the same for the age of the person. I have been forced to do this with methods. The only issue i am having is that with the 3rd last line, the name get's asked twice. I don't know how to fix that. Any help is appreciated.
public class Testing1 {
public static int[] ageinput(String names[], int q2){
int holderage[] = new int[q2];
for(int x = 0; x<q2;x++) {``
System.out.println("Please input the age of " + names[x]);
Scanner age = new Scanner(System.in);
int a1 = age.nextInt();
holderage[x] = a1;
}
return holderage;
}
public static String[] nameinput(int q2){
String holdername[] = new String[q2];
for (int x = 0; x<q2;x++) {
System.out.println("Please input the name of the person");
Scanner name = new Scanner(System.in);
String n1 = name.nextLine();
holdername[x]=n1;
}
return holdername;
}
public static void output(String names[], int ages[]){
for(int x = 0; x<names.length;x++){
System.out.println(names[x]+" is "+ages[x]+" years old");
}
}
public static void main(String[] args) {
System.out.println("How many names do you want to input?");
Scanner question = new Scanner(System.in);
int q1 = question.nextInt();
output(nameinput(q1),ageinput(nameinput(q1),q1));
}
}
In output(nameinput(q1),ageinput(nameinput(q1),q1)); you call the method nameinput twice, so the code also will be executed twice.
You could ask the names in nameinput, store them into an array and pass that array to ageinput.
#Aadithya Gowthaman, try this one in your editor.
package com.aamir;
import java.util.Scanner;
public class Testing1 {
public static int[] ageinput(String names[], int q2){
int holderage[] = new int[q2];
for(int x = 0; x<q2;x++) {
System.out.println("Please input the age of " + names[x]);
Scanner age = new Scanner(System.in);
int a1 = age.nextInt();
holderage[x] = a1;
}
return holderage;
}
public static String[] nameinput(int q2){
String holdername[] = new String[q2];
for (int x = 0; x<q2;x++) {
System.out.println("Please input the name of the person");
Scanner name = new Scanner(System.in);
String n1 = name.nextLine();
holdername[x]=n1;
}
return holdername;
}
public static void output(String names[], int ages[]){
for(int x = 0; x<names.length;x++){
System.out.println(names[x]+" is "+ages[x]+" years old");
}
}
public static void main(String[] args) {
System.out.println("How many names do you want to input?");
Scanner question = new Scanner(System.in);
int q1 = question.nextInt();
String [] namesArray = nameinput(q1);
int [] ageArray = ageinput(namesArray, q1);
output(namesArray, ageArray);
}
}

Categories

Resources