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

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

Related

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

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

Calculator function outputs wrong value [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
import java.util.* ;
class Main {
public static double op(String operation, double number1, double number2) {
double x = 0;
if (operation == "+") {
x = number2 + number1;
}
else if (operation == "x" || operation == "*") {
x = number1 * number2;
}
else if (operation == "/" || operation == "÷") {
x = number1 / number2;
}
else if (operation == "-") {
x = number1 - number2;
}
else {
System.out.println("Error: Please re-execute the program and try again!");
}
return x;
}
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
System.out.println("Please enter a number...");
double x = input.nextDouble();
System.out.println("Please enter an operation.... +, -, /, *");
String y = input.next();
System.out.println("Please enter your other number...");
double z = input.nextDouble();
System.out.println(op(y, x, z));
}
}
I want this function to return the correct value when the operation is performed. However, it always returns 0 the initial value assigned. Please help!!!
String comparison should always be done using equals try the below code :-
public static double op(String operation, double number1, double number2) {
double x = 0;
if (operation.equals("+")) {
x = number2 + number1;
}
else if (operation.equals("x") || operation.equals("*")) {
x = number1 * number2;
}
else if (operation.equals("/") || operation.equals("÷")) {
x = number1 / number2;
}
else if (operation.equals("-")) {
x = number1 - number2;
}
else {
System.out.println("Error: Please re-execute the program and try again!");
}
return x;
}
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
System.out.println("Please enter a number...");
double x = input.nextDouble();
System.out.println("Please enter an operation.... +, -, /, *");
String y = input.next();
System.out.println("Please enter your other number...");
double z = input.nextDouble();
System.out.println(op(y, x, z));
}

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.

Java Beginner, Why does my Program keep terminating?

Trying To create a calculator, Done a lot of this before about 4 years ago and just getting back into java. It just keeps terminating, it doesn't print out anything, runs for approx 5 seconds then terminates. Any help would be much appreciated.
EDIT: The problem was with the main function. The problem is fixed, thank you!
Adding the OOJCalculation code for those wanting to laugh at my stupidity more
public class OOJCalculation {
int Calculation (int Num1, int Num2, String Function,int Num3){
if(Function == "+"){
Num1 += Num2 = Num3;
return Num3;
}
else if(Function == "-"){
Num1 -= Num2 = Num3;
return Num3;
}
else if(Function == "*"){
Num1 *= Num2 = Num3;
return Num3;
}
if(Function == "/"){
Num1 /= Num2 = Num3;
return Num3;
}
return Num3;
}
}
public class Main {
public static void main(){
int State = 0;
int Num1 = 0;
int Num2 = 0;
String Function = "";
Scanner reader = new Scanner(System.in);
OOJCalculation calc = new OOJCalculation();
while(State < 5){
if(State == 0){
System.out.println("Enter first number.");
Num1 = reader.nextInt();
State++;
}
if(State == 1){
System.out.println("Enter the function.");
Function = reader.next();
State++;
}
if(State == 3){
System.out.println("Enter the second number.");
Num2 = reader.nextInt();
State++;
}
if(State == 4){
calc.Calculation(Num1, Num2, Function);
System.out.println(calc);
}
}
}
}
As the jls state :
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:
public static void main(String[] args)
So your program is not running because it can't find the main.
EDIT :
Just saying about your code, the loops and conditon are not necessay.
public static void main(String[] args ) {
int State = 0;
int Num1 = 0;
int Num2 = 0;
String Function = "";
Scanner reader = new Scanner(System.in);
System.out.println("Enter first number.");
Num1 = reader.nextInt();
reader.nextLine(); //Read the <enter> key
System.out.println("Enter the function.");
Function = reader.nextLine();
System.out.println("Enter the second number.");
Num2 = reader.nextInt();
System.out.println(Num1 + Function + Num2);
}
Your main method is missing mandatory argument:
public class Main {
public static void main(String[] args){
....
}
}
Secondly it will be terminating, because it will reach the end of the block, and then have no more instruction to run.
Your OOJCalculation method is invalid:
int calculation(int num1, int num2, String function) {
if ( "+".equals(function)) {
return num1 + num2;
} else if ( "-".equals(function)) {
return num1 - num2;
} else if ( "*".equals(function)) {
return num1 * num2;
}else if ( "/".equals(function)) {
return num1 / num2;
}
throw new IllegalArgumentException("Unknown operator");
}
it should start with lowerCase. Use also lov\wwer case for variables. CamelCase are reserved for class names and constructors. You have also wrongly declared returned type. Above implementation is covorrected.

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