Checking to see if a numbe is prime using methods - java

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.

Related

Continuous user input calculator

so I'm trying to create a simple calculator program that have these features:
Continuously calculating user input depending on the operation
Exit the program when user inputs 'x' in any part of the program
So far, I'm able to just calculate 2 numbers but what I need is for it to keep going until the user presses or inputs 'x'.
Sample output I want would be like this:
Num 1: 5
Operator: +
Num 2: 5
---------------
Result: 10
Operator: +
Number 3: 10
--------
Result: 20
and this keeps going until X is pressed
Here's my code so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
int num1 = 0;
int num2 = 0;
int result = 0;
String operator;
boolean isNumber;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter First Number: ");
if (scanner.hasNextInt()) {
num1 = scanner.nextInt();
isNumber = true;
} else {
System.err.println("Not a valid number");
isNumber = false;
scanner.next();
}
} while (!(isNumber));
System.out.println("Enter Operator ");
operator = scanner.next();
while (!operator.equals("+") && !operator.equals("-") && !operator.equals("*") && !operator.equals("/")) {
System.err.println("Invalid operator. Enter Correct Operation:");
operator = scanner.next();
}
do {
System.out.println("Enter Second Number: ");
if (scanner.hasNextInt()) {
num2 = scanner.nextInt();
isNumber = true;
} else {
System.err.println("Invalid Input. Enter Correct Number");
isNumber = false;
scanner.next();
}
} while (!(isNumber));
switch (operator) {
case "+":
addition(num1, num2, result);
break;
case "-":
subtraction(num1, num2, result);
break;
case "*":
multiplication(num1, num2, result);
break;
case "/":
division(num1, num2, result);
case "x":
System.exit(0);
}
}
public static void addition(int num1, int num2, int result) {
result = num1 + num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
public static void subtraction(int num1, int num2, int result) {
result = num1 - num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
public static void multiplication(int num1, int num2, int result) {
result = num1 * num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
public static void division(int num1, int num2, int result) {
result = num1 / num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
}

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

Im supposed to take a number entered from user to check if the input is a prime number or not.(I started very recently so please dont judge).)

Please try to base examples or explanations off of my code as I am a beginner there are many concepts that I do not understand.
import java.util.*;
public class Main{
public static void main(String[]args){
while(true) {
int i;
int x;
System.out.println("Enter a number.");
Scanner input = new Scanner(System.in);
int z = input.nextInt();
x=z/2;
}
for(int i=2; i <= int x ; i++)
if(z%i==0||z==0||z==1){
System.out.println("Not prime number");
}
else{
System.out.println("Prime Number");
}
}
Add isPrime() function that checks if the number is prime or not and print in the while-loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a number.");
int num = input.nextInt();
if (isPrime(num)) {
System.out.println("Prime Number");
} else {
System.out.println("Not prime Number");
}
}
}
private static boolean isPrime(int num) {
if (num == 0 || num == 1)
return false;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

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.

Trouble with loop and storing data in variables

The program I am trying to finish needs to read in three numbers from the user and then store them in the variables num1, num2 and num3 so that they can be used in steps 2 and 3. The problem I am having is that when the program loops through after the user inputs their numbers and tries to move on to step 2 or 3, it says must complete step 1 first.
This is my code as of right now:
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
int num3;
int input;
do {
boolean opt1Done = false;
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");
int answer = console.nextInt();
num1 = console.nextInt();
num2 = console.nextInt();
num3 = console.nextInt();
input = console.nextInt();
if (answer == 1) {
//do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
System.out.println("Enter a value for num2 between 1 and 100.");
System.out.println("Enter a value for num3 between 1 and 100.");
opt1Done = true;
} else if (answer == 2) {
if (opt1Done) {
//...... do whatever to order the numbers
int[] arraynum;
arraynum = new int[3];
arraynum[0] = num1;
arraynum[1] = num2;
arraynum[2] = num3;
Arrays.sort(arraynum);
int i;
for (i = 0; i < arraynum.length; i++) {
System.out.println("num:" + arraynum[i]);
}
} else {
System.out.println("you must complete Step 1 before Step 2");
}
} else if (answer == 3) {
if (opt1Done) {
//... do whatever to determine if triangle or not
if (num1 + num2 > num3 && num1 + num3 > num2 && num2 + num3 > num1) {
System.out.print("TRIANGLE");
} else {
System.out.print("NO TRIANGLE");
}
} else {
System.out.println("you must complete Step 1 before Step 3");
}
if (answer == 4) {
System.exit(0);
}
}
} while (input != 4);
}
}
Do I need to add another loop or change the one already have?
Move the boolean declaration opt1Done and the numbers outside the loop and read input after every user prompt.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
public class ReadChar {
public ReadChar() {
// TODO Auto-generated constructor stub
}
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1 = 0;
int num2 = 0;
int num3 = 0;
boolean opt1Done = false;
while (true) {
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out
.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");
int answer = console.nextInt();
if (answer == 1) {
// do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
num1 = console.nextInt();
System.out.println("Enter a value for num2 between 1 and 100.");
num2 = console.nextInt();
System.out.println("Enter a value for num3 between 1 and 100.");
num3 = console.nextInt();
opt1Done = true;
} else if (answer == 2) {
if (opt1Done) {
// ...... do whatever to order the numbers
int[] arraynum;
arraynum = new int[3];
arraynum[0] = num1;
arraynum[1] = num2;
arraynum[2] = num3;
Arrays.sort(arraynum);
int i;
for (i = 0; i < arraynum.length; i++) {
System.out.println("num:" + arraynum[i]);
}
} else {
System.out
.println("you must complete Step 1 before Step 2");
}
} else if (answer == 3) {
if (opt1Done) {
// ... do whatever to determine if triangle or not
if (num1 + num2 > num3 && num1 + num3 > num2
&& num2 + num3 > num1) {
System.out.print("TRIANGLE");
} else {
System.out.print("NO TRIANGLE");
}
} else {
System.out
.println("you must complete Step 1 before Step 3");
}
}
if (answer == 4) {
System.exit(0);
}
}
}
}
You don't loop over the instructions. Every time you have a step completed, the program then ends and the next time you run it, nothing you've done before is saved.
You need an outer loop to iterate over commands:
public static void main(String[] args) {
int num1;
int num2;
int num3;
boolean opt1Done = false;
while (true) {
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");
//rest of your code here
}
}
It seems that you must loop until the user choose the option 4. I don't see any loops that encompass the options asking questions.
Hope this helps
Introduced a while loop and opt1True should outside of the loop
check for is answer 4 is inside answer 3. So moved that in else if to be same level with other answer checks
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1 = 0;
int num2 = 0;
int num3 = 0;
boolean opt1Done = false;
while(true) {
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");
int answer = console.nextInt();
if (answer == 1) {
// do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
num1 = console.nextInt();
System.out.println("Enter a value for num2 between 1 and 100.");
num2 = console.nextInt();
System.out.println("Enter a value for num3 between 1 and 100.");
num3 = console.nextInt();
opt1Done = true;
} else if (answer == 2) {
if (opt1Done) {
// ...... do whatever to order the numbers
int[] arraynum;
arraynum = new int[3];
arraynum[0] = num1;
arraynum[1] = num2;
arraynum[2] = num3;
Arrays.sort(arraynum);
int i;
for (i = 0; i < arraynum.length; i++) {
System.out.println("num:" + arraynum[i]);
}
} else {
System.out.println("you must complete Step 1 before Step 2");
}
} else if (answer == 3) {
if (opt1Done) {
// ... do whatever to determine if triangle or not
if (num1 + num2 > num3 && num1 + num3 > num2
&& num2 + num3 > num1) {
System.out.print("TRIANGLE");
} else {
System.out.print("NO TRIANGLE");
}
} else {
System.out.println("you must complete Step 1 before Step 3");
}
} else if (answer == 4) {
System.exit(0);
}
}
}
you are putting condition in wrong place.
as i am thinking first check answer from user then take those 3 numbers inside first condition as
int answer = console.nextInt();
if (answer == 1) {
//do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
num1 = console.nextInt();
System.out.println("Enter a value for num2 between 1 and 100.");
num2 = console.nextInt();
System.out.println("Enter a value for num3 between 1 and 100.");
num3 = console.nextInt();
opt1Done = true;
}
and move this line outside of loop
boolean opt1Done = false;
All you had to do was add a while loop to your logic and reorder it.
boolean opt1Done = false;
int num1, num2, num3;
while(answer != 4){
System.out.println("Select your next step");
System.out.println("1: Enter three numbers between 1 and 100.");
System.out.println("2: Order your number in ascending order");
System.out.println("3: Determine if the three inputs form a triangle");
System.out.println("4: Exit");
int answer = console.nextInt();
if (answer == 1) {
//do whatever for option 1
System.out.println("Enter a value for num1 between 1 and 100.");
num1 = console.nextInt();
System.out.println("Enter a value for num2 between 1 and 100.");
num2 = console.nextInt();
System.out.println("Enter a value for num3 between 1 and 100.");
num3 = console.nextInt();
opt1Done = true;
}
...
if (answer == 4) {
System.exit(0);
}
}
}
}
Your problem was every time you were looping you were re-declaring and setting the boolean variable to false. Plus your console.nextInts() were in the wrong spot. Also do while is not necessary in this case because the starting value of answer is null and therefore is not equal to four.

Categories

Resources