Use scanner only from main method - java

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

Related

Parameters, methods and inputs

I am a beginner in Java and I am wondering if there is a way to use one input from the user in more than one method? I am making a program that is supposed to take some inputs (integers) from the user and control the inputs, then calculate the average and lastly count the occurrence of the inputs?
I have one main method + 3 different methods (one calculates the average etc). I have tried a lot of different things, but haven't seemed to understand the point with parameters and how they work.
So this is just a quick overview.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int value = sc.nextInt(); //Number of how many elements the user want to enter
int[] input = new int[value]; //An array with all the values
}
public int secureInt(int number, int[] input, int value) {
if (!Integer.parseInt(number)) {
System.out.println("Invalid input");
} else {
for (int i = 0; i < value; i++) { //Add all the inputs in the array
input[i] = sc.nextInt();
}
}
public double averageCalculator (int value, int[] in){
double average; // The average
double sum = 0; // The total sum of the inputs
if (int i = a; i < value; i++) {
sum = sum + in[i];
}
average = sum / value;
return average;
}
//Count the occurence of inputs that only occure once
public static int countOccurence(//what parameter should i have here?) {
int count = 0;
}
}
Here is some code that may be helpful to you. The idea is to try to emulate or imitate the style & best practices in this excerpt:
import java.util.Scanner;
public class ArrayFiller {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int input_element_count = sc.nextInt(); //Number of how many elements the user want to enter
int element_count = input_element_count;
int[] array = new int[element_count]; //An array with all the values
enter_elements_of_array(array, element_count, sc);
double average = averageCalculator(array, element_count);
printArray(array);
System.out.println("The average of the entered numbers is " + average);
}
public static void printArray(int[] array) {
System.out.print("The array you entered is : [");
for (int element : array) {
System.out.print(" " + element + " ");
}
System.out.print("]" + "\n");
}
public static void enter_elements_of_array( int[] array, int element_count, Scanner sc) {
for (int i = 0; i < element_count; i++) { //Add all the inputs in the array
System.out.println("Please enter element " + (i+1) + " of " + element_count + ":");
array[i] = sc.nextInt();
}
}
public static double averageCalculator ( int[] array, int element_count){
double average; // The average
double sum = 0; // The total sum of the inputs
for (int i = 0; i < element_count; i++) {
sum = sum + array[i];
}
average = sum / element_count;
return average;
}
//Count the occurence of inputs that only occur once
public static int countOccurence(int[] array) {
int count = 0;
// algorithm for counting elements with cardinality of 1
return count;
}
}

Cannot find the highest and lowest

I have some problems in highest and lowest.
import java.util.Scanner;
public class Lab3bq1
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double [] num = new double[10];
double [] p = new double[10];
System.out.println("Enter the number of books purchased by :");
for(int i=0;i<num.length;i++)
{
System.out.print("Customer #"+(i+1)+ " = ");
num[i] = input.nextDouble();
}
System.out.println("Review for 10 Selected Customers");
System.out.println("Points Awarded:");
setp(num,p);
System.out.println("Total books purchased : "+settotalbook(num));
System.out.println("Highest points : Customer "+sethighest(p));
System.out.println("Lowest points : Customer "+setlowest(p));
}
public static void setp(double[] num, double[] p)
{
for(int i=0;i<p.length;i++)
{
if(num[i]>=1 && num[i]<=3)
p[i] = 10;
else if(num[i]<=6)
p[i] = 25;
else if(num[i]<=9)
p[i] = 40;
else
p[i] = 75;
System.out.println("Customer #"+(i+1)+ " = " + p[i] + " points");
}
}
public static double settotalbook(double[] num)
{
double total=0;
for(int i=0;i<num.length;i++)
{
total+=num[i];
}
return total;
}
public static double sethighest(double[] p)
{
double max=p[0], custnum=0;
for(int i=0;i<p.length;i++)
{
if(p[i]>max)
max=p[i];
custnum=i;
}
return (custnum+1);
}
public static double setlowest(double[] p)
{
double min=p[0], custnum=0;
for(int i=0;i<p.length;i++)
{
if(p[i]<min)
min=p[i];
custnum=i;
}
return (custnum+1);
}
}
Problem is with if block in both method
try:
if(p[i]<min){
min=p[i];
custnum=i;
}
and
if(p[i]>max){
max=p[i];
custnum=i;
}
store customer number who have min or max value..
It looks like you are beginner. Anyway, you should return max in the sethighest method and min in the setlowest method as #Uta Alexandru suggested.
There is one more mistake in the code. Whenever we write something like
if(condition)
statement#1
statement#2
So if condition is true then only statement#1 will execute and statement#2 is out of the condition.
Here in your code your wrote
if(p[i]>max)
max=p[i];
custnum=i;
and
if(p[i]<min)
min=p[i];
custnum=i;
custnum is updated at every iteration in loop.
If you want it to be updated only when your condition is true then you need to put your code in block like this.
if(p[i]>max) {
max=p[i];
custnum=i;
}
and
if(p[i]<min) {
min=p[i];
custnum=i;
}
Hope this helps. Enjoy :)

Output will not print the correct information

I'm trying to make a program which asks the user a particular bird then how many of them they had seen at that point. If the use at any point enters the word 'END' then the system should print out the most seen bird and the number seen. However, when running my program if I enter 'END' at random points it instead returns that the most seen was END with 0 seen. I can't figure out how to make it work. I've tried different methods but it's just not working properly. Also, I've set the maximum array limit to 10 possitions but it continues after 10 and if i enter a value the system crashes. Have I written the limit part properly? Or am I missing something important?
import java.util.Scanner;
public class testing
{
public static void main (String[] param)
{
birdInput();
most();
System.exit(0);
}
public static void birdInput()
{
int i = 0;
String birdInput;
int numberInput;
Scanner scanner = new Scanner(System.in);
int maxVal = Integer.MIN_VALUE;
int maxValIndex = -1;
while (true)
{
System.out.println("What bird did you see?");
birdInput = scanner.nextLine();
if (birdInput.equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.exit(0);
}
else
{
String[] birds = new String[10];
int[] numbers = new int[10];
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
if (birds[i].equals("END"))
{
maxVal = numbers[i];
maxValIndex = i;
System.out.print("\nThe most common bird that you saw was the " + birds[maxValIndex] + " with " + maxVal + " being seen in total\n");
System.exit(0);
}
}
}
}
public static void most()
{
System.out.println("fdff");
}
}
This is my edit of Till Hemmerich's answer to my issue. I tried to remove the global variables and so combine the entire code into 1 method. However, I'm still having some issues. Been working at it but really confused.
import java.util.Scanner;
public class birds2
{
public static void main(String[] param)
{
birdInput();
System.exit(0);
}
public static void birdInput()
{
Scanner scanner = new Scanner(System.in);
String[] birds = new String[99999999];
int[] numbers = new int[99999999];
int i = 0;
int maxIndex;
while (i <= birds.length)
{
System.out.println("What bird did you see?");
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
}
int newnumber = numbers[i];
if ((newnumber > numbers.length))
{
maxIndex = i;
i++;
}
if (birds[i].toUpperCase().equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
}
}
You're re-declaring the birds and numbers arrays in each iteration of the loop. They should be declared and initialized only once, before the loop.
I changed a lot so im going to explain my changes here in total.
First of all i had to move the Array Definition out of your while-loop as >mentioned above, since other wise you would override these Arrays every time.
I also made them globally accessible to work with them in other methods.
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
in general I re structured the whole code a little bit to make it more readable and a little bit more object-orientated.
For example I created an method called inputCheck() which returns our input as a String and check if it equals END so you do not have to write your logic for this twice. (it also considers writing end lower or Uppercased by just Upper our input before checking it"if (input.toUpperCase().equals("END"))")
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
this method can now be called every time you need an input like this:
birds[i] = inputCheck();
but you need to be carefull if you want to get an integer out of it you first have to parse it like this:Integer.parseInt(inputCheck())
after that I wrote a method to search for the biggest Value in your numbers Array and getting its index:
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
it takes an int array as parameter and returns the index of the highest element in there as an Integer. Called like this:maxIndex = getMaxIndex(numbers);
Then after that I rewrote your end method. It now just calles our getMaxIndex method and prints some output to the console.
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
to fix your last problem (crashing after more then 10 inputs)I changed your while-loop. Since your array only has 10 places to put things it crashes if you try to put information in place number 11. it not looks like this:while (i <= birds.length) instead of while (true) this way the max loops it can take is the amout of places Array birds has and it wont crash anymore.
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
Here is the whole code in total:
import java.util.Scanner;
/**
*
* #author E0268617
*/
public class JavaApplication1 {
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
public static void main(String[] param) {
birdInput();
most();
System.exit(0);
}
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
public static void most() {
System.out.println("fdff");
}
}
I hope you understand where the Problems had been hidden if you have any Questions hit me up.

How to return two values in Java

I know that java can't normally return two values, but I'm trying to return the value as a method.. From there I want to use the values of score1 and maxScore1 in a string in the main method. getHwGrades is the method I'm having issues with. I get "error: cannot find symbol". I'm not allowed to use arrays for this program. On another note, I'm also not supposed to use any if/else statements, but I could not find any other way to limit the value of discussionGrade to 20. Any help is appreciated
import java.util.Scanner;
public class Grades
{
public static void main(String[] args)
{
Scanner getG = new Scanner(System.in);
int weight1;
int weight2;
int weight3;
int score2 = 0;
int maxScore2 = 0;
int sections;
int discussionGrade;
System.out.println("What is the weight for the HW and Exam 1?");
weight1 = getG.nextInt();
weight2 = getG.nextInt();
weight3 = getWeight(weight1, weight2);
System.out.println("Using weights of " + weight1 + " " + weight2 + " " + weight3);
getHwGrades();
sections = numberSections();
discussionGrade = calcDGrade(sections);
System.out.println("What is your grade for exam1?"); //move under hw total points and final grade, add curve
score2 = getG.nextInt();
maxScore2 = getG.nextInt();
System.out.println("Total Points =" + (score1+ discussionGrade) + "/ "(maxScore1 + 20));
}
public static int getHwGrades()//method for asking and storing hw grades
{
int score1;
int maxScore1;
int nOfA;
Scanner getG = new Scanner(System.in);
System.out.println("How many HW assignments are there?");
nOfA = getG.nextInt();
for (int i = 1; i <= nOfA; i++) //loop that asks for the grades corresponding to the amount of hw assignments there were
{
System.out.println("What is your grade and then the max grade for assignment " + i + "?");
score1 += getG.nextInt();
maxScore1 += getG.nextInt();
}
return new getHwGrade(score1, maxScore1); //returns results of inputs into method holding the 2 variables
}
public static int numberSections() //finds out how many sections the student attended
{
Scanner getG = new Scanner(System.in);
System.out.println("How many sections did you attend?");
return getG.nextInt();
}
public static int calcDGrade(int sections) //method to calculate the grade for the students sections
{
int maxDGrade = ((sections*4)); if (maxDGrade > 20) //limits total score to 20
{
return 20;
}
else
{
return maxDGrade;
}
}
public static int getWeight(int weight1, int weight2)//returns the weight that will be used for weight3
{
return (100-(weight1 + weight2));
}
public static double round2(double number)
{
return Math.round(number * 100.0) / 100.0;
}
}
Since you can only return a single value, you need to return a single value. :-) Normally if a method needs to return complex information, the way you have it do that is either:
Return a newly-created instance of a class that has fields for the individual pieces of information
Have the method fill in an instance of such a class that's passed to it (usually not ideal barring a good reason for doing it)
So for instance:
class HwGrades {
private int score1;
private int maxScore1;
ScoreInfo(int _score1, int _maxScore1) {
this.score1 = _score1;
this.maxScore1 = _maxScore1;
}
// ...accessors as appropriate, presumably at least getters...
}
Then return an instance of HwGrades from getHwGrades:
public static int getHwGrades()//method for asking and storing hw grades
{
int score1;
int maxScore1;
// ...
return new HwGrades(score1, maxScore1);
}
If you needed, you could further decouple things by making HwGrades an interface, which you then implement with a private class, so that the API isn't tied to a specific class. Almost certainly overkill for a small school project.
getHwGrade is expected to be a class.
Have a class like this
class getHwGrade{
int a;
int b;
public getHwGrade(int a,b){
this.a=a;this.b=b;
}

Basic Java questions Scanning

This is very basic java that i'm struggling with n00b style. it just prints out this
Please enter '.' when you want to calculate
1 2 3
.
Numbers are 1 2 3
The Sum is0The Product is1
when it is supposed to calculate the sum and product of those consecutive numbers. something is wrong id appreciate any help!
main method
import java.util.*;
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to calculate");
Scanner keyboard = new Scanner(System.in);
String scannedString = keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
while(!keyboard.nextLine().equals("."))
{
scanz.set(scannedString);
}
keyboard.close();
System.out.println("Numbers are"+scannedString);
scanz.printState();
}
}
Class Scanning
public class Scanning {
int num;
int sum;
int product;
String userInput;
public Scanning(String userInput)
{
num=0;
sum=0;
product=1;
this.userInput=userInput;
}
public void set(String userInput)
{
for(int index=0; index<userInput.length(); index++)
{
if(Character.isDigit(userInput.charAt(index))==true)
{
num=userInput.charAt(index);
sum+=num;
product*=num;
}
else
{
index++;
}
}
}
public void printState()
{
System.out.println("The Sum is"+sum+"The Product is"+product);
}
}
A few things to look at:
We know keyboard.nextLine() gets the input from the console, but where are you checking it's validity (more importantly, when do you check it?). Are you looking at all input or just the last line?
isDigit will return true if the passed in character is a number. Do you want to operate on numbers or characters in your for loop?
(a side note, What happens if I enter "1 10" in the console?)
A for loop will automatically increment its index at the end of a loop, so an additional ++ is unnecessary
You might find this helful in case you just need the sum and product values of a user entered
values.
public class ProductSumCalculator{
private static List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
getInputs();
calculateSumAndProduct();
}
private static void getInputs() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter numbers or ctrl+z to end inputs");
while(scanner.hasNext()){
numbers.add(scanner.nextInt());
}
}
private static void calculateSumAndProduct() {
Iterator<Integer> iterator = numbers.iterator();
int sum=0;
int product=1;
int nextVal;
while(iterator.hasNext()){
nextVal = iterator.next();
sum+=nextVal;
product*=nextVal;
}
System.out.println("Value entered are: "+numbers+".\nThe sum is "+
sum+".The product is "+product);
}
}
You can also try this. You can calculate the sum and product of all the int from your string line input like this:
import java.util.Scanner;
public class Scanning {
/*
* This method returns the integer. If while
* conversion an Exception is thrown it returns
* null. Otherwise the integer.
*/
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
/*
* Next String line is scanned. It is split by space.
* Stores String tokens in an String array from one String variable.
* Then passed to tryParse() class method. null or auto Boxed Integer
* is returned accordingly. It is auto unboxed from Integer
* object to int variable. Then sum and product is calculated and
* the final result is printed on the console Or Integrated
* Development Environment.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
String strInts = keyboard.nextLine();
String[] splits = strInts.split("\\s+");
int i = 0;
Integer anInteger = null;
int total = 0;
int product = 1;
while((i < splits.length)) {
anInteger = tryParse(splits[i]);
if(anInteger != null) {
total = total + anInteger;
product = product * anInteger;
}
++i;
}
System.out.println("The sum is: " + total);
System.out.println("The product is: " + product);
}
}

Categories

Resources