How to pass the validated user inputs to the method parameter? - java

I have two classes: MyNumbers and MyScanner. I am trying to pass the validated inputs to the calculateSum (int x, int y) method in order to print the final result in the MyScanner class, but I don't know how I can take the user inputs from the MyScanner class to pass them to the validate() method in the MyNumbers class so that it allows the calculateSum() method to perform its task.
P.S. validate() method should be void and parameterless, but calculateSum() method should be string to return the result as a string and take two parameters. I also want the validate() method to prompt for user input and validate the values to make sure that they are in the certain range. This method needs to keep prompting until user inserts a valid number.
How can I achieve this without introducing another variable/implementing setters/ passing variables as a parameter to the validate() method?
public class MyNumbers {
int number1;
int number2;
public void validate() {
if (number1 >= 10 && number1 <= 50) {
if(number2 >= 5 && number2 <= 20){
System.out.println(calculateSum(number1, number2));
}
}
else {
System.out.println("Number should be between 10 and 50");
}
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
validate();
return "Sum: " + number1 + number2;
}
}
public class MyScanner {
public static void main(String[] args) {
MyNumbers myNumbers = new myNumbers();
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
do{
switch(option){
case 1:
System.out.println("Enter number 1");
int x = scanner.nextInt();
System.out.println("Enter number 2");
int y = scanner.nextInt();
myNumbers.calculateSum(x, y);
break;
}
}
while(option!=0);
}
}

EDIT :
import java.util.*;
class MyNumbers {
int number1;
int number2;
public void validate() {
int valid=0;
int x;
int y;
Scanner s = new Scanner(System.in);
System.out.println("Welcome!");
do{
System.out.println("Enter Number 1: ");
x = s.nextInt();
if (x >= 10 && x <= 50) {
valid=2;
}
else {
System.out.println("Number 1 should be between 10 and 50");
}
}while(valid!=2);
do {
System.out.println("Enter Number 2: ");
y = s.nextInt();
if(y >= 5 && y <= 20){
System.out.println(calculateSum(x, y));
valid=3;
}
else {
System.out.println("Number 2 should be between 5 and 20");
}
}while(valid!=3);
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
return "Sum: " + (number1 + number2);
}
}
public class Main {
public static void main(String[] args) {
MyNumbers myNumbers = new MyNumbers();
myNumbers.validate();
}
}
Try
import java.util.*;
class MyNumbers {
int number1;
int number2;
public void validate(int number1 , int number2) {
if (number1 >= 10 && number1 <= 50) {
if(number2 >= 5 && number2 <= 20){
System.out.println(calculateSum(number1, number2));
}
}
else {
System.out.println("Number should be between 10 and 50");
}
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
return "Sum: " + number1 + number2;
}
}
public class Main {
public static void main(String[] args) {
MyNumbers myNumbers = new MyNumbers();
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
switch(option){
case 1:
System.out.println("Enter number 1");
int x = scanner.nextInt();
System.out.println("Enter number 2");
int y = scanner.nextInt();
myNumbers.validate(x, y);
myNumbers.calculateSum(x, y);
break;
}
}
}

Related

How do I pass the user inputs to a constructor in a different class?

My professor told me that I have to Design a class "SharePattern" that has the following two fields: "numberOfDaysInPeriod" and
"SharePointsOnFirstDay".
The class should have a constructor to set the values of these two fields.
In a separate class he said to get user input in the main of my other class. So what goes into the constructor?
First class:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner more = new Scanner(System.in);
System.out.print("Number of days in the period: ");
int input1 = more.nextInt();
while(input1 < 10 || input1 > 20)
{
System.out.println("The number of days that is entered must not be less than 10 and more than 20. The number of days doesn't meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
input1 = more.nextInt();
}
System.out.print("Share points on the first day: ");
int input2 = more.nextInt();
int half = input1 / 2;
more.close();
SharePattern sp = new SharePattern(input1, input2, half);
sp.findFinalDaySharePoints(input1, input2, half);
}
}
2nd class:
package hw4Question2;
public class SharePattern {
public SharePattern(int input1, int input2, int half)//constructor
{
}
public void findFinalDaySharePoints(int input1, int input2, int half)
{
System.out.println(input2);
if(input1%2 == 0) {
for(int i = 1; i <= input1 ; ++i)
{
if(i<half)
{
input2 = input2 + 50;
System.out.println(input2);
}
else if(i>half)
{
input2 = input2 - 25;
System.out.println(input2);
}
}
}
else
{
for(int i = 1; i <= input1 ; ++i)
{
if(i<=half)
{
input2 = input2 + 50;
System.out.println(input2);
}
else if(i>half)
{
input2 = input2 - 25;
System.out.println(input2);
}
}
System.out.println("The final share value is "+input2);
}
}
}
First class
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner more = new Scanner(System.in);
System.out.print("Number of days in the period: ");
int input1 = more.nextInt();
while(input1 < 10 || input1 > 20)
{
System.out.println("The number of days that is entered must not be less than 10 and more than 20. The number of days doesn't meet the required criteria, enter it again");
System.out.print("Number of days in the period: ");
input1 = more.nextInt();
}
System.out.print("Share points on the first day: ");
int input2 = more.nextInt();
int half = input1 / 2;
more.close();
SharePattern sp = new SharePattern(input1, input2);
sp.findFinalDaySharePoints(half);
}
SharePattern.class
int numberOfDaysInPeriod;
int sharePointsOnFirstDay;
public SharePattern(int input1, int input2) {
this.numberOfDaysInPeriod = input1;
this.sharePointsOnFirstDay = input2;
}
public void findFinalDaySharePoints(int half)
{
System.out.println(sharePointsOnFirstDay);
if(numberOfDaysInPeriod %2 == 0) {
for(int i = 1; i <= numberOfDaysInPeriod; ++i)
{
if(i<half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay + 50;
System.out.println(sharePointsOnFirstDay);
}
else if(i>half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay - 25;
System.out.println(sharePointsOnFirstDay);
}
}
}
else
{
for(int i = 1; i <= numberOfDaysInPeriod; ++i)
{
if(i<=half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay + 50;
System.out.println(sharePointsOnFirstDay);
}
else if(i>half)
{
sharePointsOnFirstDay = sharePointsOnFirstDay - 25;
System.out.println(sharePointsOnFirstDay);
}
}
System.out.println("The final share value is "+ sharePointsOnFirstDay);
}
}

Checking to see if a numbe is prime using methods

The answer is probably staring me in the face but I have been looking at this so long the words are blurring together. The assignment is to have the user input 3 numbers, add the numbers together using a method, then to determine if the sum is a prime number using a different method.
package chpt6_Project;
import java.util.Scanner;
public class Chpt6_Project {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
int num3;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number: ");
num1 = scan.nextInt();
System.out.println("Enter the second number: ");
num2 = scan.nextInt();
System.out.println("Enter the third number: ");
num3 = scan.nextInt();
Chpt6_Project.sum(num1, num2, num3);
if(isPrime()) {
System.out.println("The number is prime");
} else {
System.out.println("The number is not prime.");
}
}
public static void sum(int num1, int num2, int num3) {
int total = num1 + num2 + num3;
System.out.println(total);
}
public static boolean isPrime(int total) {
if((total > 2 && total % 2 == 0) || total == 1) {
return false;
}
for (int i = 3; i <= (int)Math.sqrt(total); i += 2) {
if (total % i == 0) {
return false;
}
}
return true;
}
}
Edit the code as follow and you should do the trick.
The sum function now returns the sum calculated, this value is passed by main to the isPrime function which will return the right value
package chpt6_Project;
import java.util.Scanner;
public class Chpt6_Project {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
int num3;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number: ");
num1 = scan.nextInt();
System.out.println("Enter the second number: ");
num2 = scan.nextInt();
System.out.println("Enter the third number: ");
num3 = scan.nextInt();
if(isPrime(Chpt6_Project.sum(num1, num2, num3))) {
System.out.println("The number is prime");
} else {
System.out.println("The number is not prime.");
}
}
public static int sum(int num1, int num2, int num3) {
int total = num1 + num2 + num3;
System.out.println(total);
return total;
}
public static boolean isPrime(int total) {
if((total > 2 && total % 2 == 0) || total == 1) {
return false;
}
for (int i = 3; i <= (int)Math.sqrt(total); i += 2) {
if (total % i == 0) {
return false;
}
}
return true;
}
Morover i guess this is an homework but there are better way of doing this. For example, there is no need for a sum function.

Options method showing up twice after initial use when the loop repeats

import java.util.Scanner;
public class Calculator {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
String userInput1 = "";
//the do loop so i can go through all the options
do {
options();
userInput1 = userInput.nextLine();
if(userInput1.equals("add")){
System.out.println(calcAdd());
}
else if (userInput1.equals("subtract")) {
System.out.println(calcSub());
}
else if(userInput1.equals("multiply")){
System.out.println(calcMult());
}
else if(userInput1.equals("divide")){
System.out.println(calcDiv());
}
} while(!userInput1.equals("q"));
}
//options for the program
public static void options(){
System.out.println("add");
System.out.println("subtract");
System.out.println("multiply");
System.out.println("divide");
System.out.println("\"q\" to quit");
System.out.print("What do you want to do: ");
}
//addition method
public static int calcAdd(){
System.out.print("First number: ");
int x = userInput.nextInt();
System.out.print("Second number: ");
int y = userInput.nextInt();
int z;
z = x + y;
return z;
}
//subtraction method
public static int calcSub(){
System.out.print("First number: ");
int x = userInput.nextInt();
System.out.print("Second number: ");
int y = userInput.nextInt();
int z;
z = x - y;
return z;
}
//multiplication method
public static int calcMult(){
System.out.print("First number: ");
int x = userInput.nextInt();
System.out.print("Second number: ");
int y = userInput.nextInt();
int z;
z = x * y;
return z;
}
//division method
public static double calcDiv(){
System.out.print("First number: ");
double x = userInput.nextDouble();
System.out.print("Second number: ");
double y = userInput.nextDouble();
double z;
if (y == 0){
System.out.println("Sorry you can't do this");
} else {
z = x / y;
return z;
}
return 0;
}
}

In java, how to call the values from input class?

I can't figure out how to bring a variable from one method into another for use, especially that from input class. For example, this test program doesn't work. How would I make it work?
So here's my main class(Main.java):
class Main
{
public static void main(String args[])
{
Input f = new Input();
f.inputting(num1, num2, num3);
}
}
and my input class(Input.java):
import java.io.*;
class Input
{
void inputting(int number1, int number2, int number3)
{
Console d = System.console();
String a = d.readLine("Enter 1st number:");
String b = d.readLine("Enter 2nd number:");
String c = d.readLine("Enter 3rd number:");
int num1 = Integer.parseInt(a);
int num2 = Integer.parseInt(b);
int num3 = Integer.parseInt(c);
Sort e = new Sort();
e.sorting(num1, num2, num3);
}
}
and my sort class(Sort.java):
class Sort
{
void sorting(int number1, int number2, int number3)
{
if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
if (number2 > number3) {
int temp = number2;
number2 = number3;
number3 = temp;
}
if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
System.out.println("\nThe sorted numbers in ascending order are "
+ number1 + " " + number2 + " " + number3);
}
}
You are passing arguments into inputting with f.inputting(num1, num2, num3);, but you never declared num1, num2, or num3 in main.
If your intent is to do the user input from within the inputting method, you don't need the parameters for the inputting method, so you could do f.inputting(); in main and change the method declaration to void inputting().
This is how it should be
class Main
{
public static void main(String args[])
{
int num1=1;
int num2=2;
int num1=3;
Input f = new Input();
f.inputting(num1, num2, num3);
}
}
Also, you should use ELSE IF!, if not, it could enters the 3 ifs...
if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
else if (number2 > number3) {
int temp = number2;
number2 = number3;
number3 = temp;
}
else if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
You need to either set up a global variable that sub classes or other classes use or you can call the variable from the class like so:
Class Main
class Main
{
public static void main(String args[])
{
Static int number1;
Static int number2;
Static int number3;
Input f = new Input();
f.inputting(number1, number2, number3);
}
}
Class Input
int Main.number1 = Integer.parseInt(a);
int Main.number2 = Integer.parseInt(b);
int Main.number3 = Integer.parseInt(c);

convert string to arithmetic operation [duplicate]

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 9 years ago.
I'm doing a program that presents the student with a math quiz. I am having trouble figuring out how to take the input problem type and turning that string into the arithmetic operator. Here is the method for that part of the code. Please and thanks!
public static String getUserChoice(String choice) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the symbol that corresponds to one of the following problems\n"
+ "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
choice = in.next();
if ("+".equals(choice)){
return +;
}
}
return choice;
Update
Here's the entire code if it helps see what I am doing.
public static void main(String[] args) {
int digit = 0;
int random = 0;
String result1 = getUserChoice("");
digit = getNumberofDigit1(digit);
int number1 = getRandomNumber1(digit);
int number2 = getRandomNumber2(digit);
System.out.println(number1 + result1 + number2);
getCorrectAnswer(number1, result1, number2);
}
public static String getUserChoice(String choice) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the symbol that corresponds to one of the following problems\n"
+ "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
choice = in.next();
return choice;
}
public static int getNumberofDigit1(int digit) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a 1 for problems with one digit, or a 2 for two-digit problems: ");
digit = in.nextInt();
return digit;
}
public static int getRandomNumber1(int numbers) {
int random = 0;
if (numbers == 1) {
random = (int) (1 + Math.random() * 9);
} else if (numbers == 2) {
random = (int) (10 + Math.random() * 90);
}
return random;
}
public static int getRandomNumber2(int numbers) {
int random2 = 0;
if (numbers == 1) {
random2 = (int) (1 + Math.random() * 9);
} else if (numbers == 2) {
random2 = (int) (10 + Math.random() * 90);
}
return random2;
}
public static void getCorrectAnswer(int number1, String result1, int number2) {
}
public static void getUserAnswer() {
Scanner in = new Scanner(System.in);
}
public static void CheckandDisplayResult() {
}
here is the one approach to your problem:
private static Scanner input;
public static void main(String[] args) {
input = new Scanner(System.in);
final String result1 = getUserChoice();
final int digit = getNumberofDigit1();
final int number1 = getRandomNumber(digit);
final int number2 = getRandomNumber(digit);
System.out.println(number1 + result1 + number2);
final int userAnswer = input.nextInt();
final int correctAnswer = getCorrectAnswer(number1, result1, number2);
System.out.println( (userAnswer == correctAnswer) ? "Ok" : ("Wrong, right is: " + correctAnswer));
input.close();
}
public static String getUserChoice() {
System.out.println("Please enter the symbol that corresponds to one of the following problems\n" + "Addition (+)\n Subtraction (-)\n or Multiplication (*): ");
return input.next();
}
public static int getNumberofDigit1() {
System.out.println("Enter a 1 for problems with one digit, or a 2 for two-digit problems: ");
return input.nextInt();
}
public static int getRandomNumber(final int numbers) {
return (int) ( (numbers == 1) ? (1 + Math.random() * 9) : (10 + Math.random() * 90) );
}
public static int getCorrectAnswer(final int number1, final String result1, final int number2) {
if ("+".equals(result1))
return number1+number2;
else if ("-".equals(result1))
return number1-number2;
else if ("*".equals(result1))
return number1*number2;
return -1;
}
and here is a little bit another getCorrectAnswer part:
public interface IMyOperator {
public int operation(final int a, final int b);
};
static class classSum implements IMyOperator {
public int operation(final int a, final int b) {
return a+b;
}
}
static class classSub implements IMyOperator {
public int operation(final int a, final int b) {
return a-b;
}
}
static class classMul implements IMyOperator {
public int operation(final int a, final int b) {
return a*b;
}
}
final static HashMap<String, IMyOperator> operators = new HashMap<String, IMyOperator>(3) {{
put("+", new classSum());
put("-", new classSub());
put("*", new classMul());
}};
public static int getCorrectAnswer(final int number1, final String result1, final int number2) {
return operators.get(result1).operation(number1, number2);
}
First, I want to show you how to test to see if it is what you want.
You can always check to make sure it is a string, or int, or w/e by doing the following.
Scanner scan = new Scanner(System.in);
while(scan.hasNext()) {
if(scan.hasNextInt()) {
int response = scan.nextInt();
}
}
Here is code for what you want to do.
import java.util.Random;
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
// Math Quiz v1.0 //
String printme = "Please choose the quiz type:\n\n"
+ "(1) Addition\n"
+ "(2) Subtraction\n"
+ "(3) Multiplication\n"
+ "(4) Division\n"
+ "(5) Modulus\n\n\n";
System.out.println(printme);
int reponse = in.nextInt();
// Setup //
int a = new Random().nextInt(100);
int b = new Random().nextInt(100);
int answer = -1;
switch(reponse) {
case 1:
System.out.println("What is " + a + " + " + b + "?");
answer = in.nextInt();
if(answer == a + b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 2:
System.out.println("What is " + a + " - " + b + "?");
answer = in.nextInt();
if(answer == a - b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 3:
System.out.println("What is " + a + " * " + b + "?");
answer = in.nextInt();
if(answer == a * b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 4:
System.out.println("What is " + a + " / " + b + "?");
answer = in.nextInt();
if(answer == a / b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
case 5:
System.out.println("What is " + a + " % " + b + "?");
answer = in.nextInt();
if(answer == a % b) {
System.out.println("Your right!");
} else {
System.out.println("You fail!");
}
break;
default:
System.out.println("Error, enter an integer between 1 & 5.");
break;
}
}
}

Categories

Resources