My goal is to determine, for a pair of integers, whether the second integer is a multiple of the first. My code is as follows:
import java.util.Scanner;
public class Multiples {
public static void main(String [] args) {
boolean run = true;
while(run) {
Scanner input = new Scanner(System.in);
System.out.print("Enter one number:");
int num1 = input.nextInt();
System.out.print("Enter a second number:");
int num2 = input.nextInt();
boolean result = isMultiple(num1, num2);
if(result) {
System.out.println(num2 + " is a multiple of " + num1);
} else {
System.out.println(num2 + " is not a multiple of " + num1);
}
System.out.print("Do you want to enter another pair(y/n)?");
run = YesOrNo(input.next());
}
}
public static boolean YesOrNo(String a) {
if(a.equals("y"))
return true;
else
return false;
}
public static boolean isMultiple (int x , int y) {
if(y % x == 0)
return true;
else
return false;
}
}
This is my output:
This is the expected output:
The expected output is confusing me.
Related
I would like to have some ideas on how I can make this code to keep asking for a number until the program finds a prime number. Thank you so much :)
import java.util.Scanner;
class SieteDosEjerSeis {
public static void main(String args[])
{
int temp;
boolean isPrime=true;
Scanner scan= new Scanner(System.in);
System.out.println("Enter a number:");
//capture the input in an integer
int num=scan.nextInt();
scan.close();
for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
//If isPrime is true then the number is prime else not
if(isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
}
}
Well, mainly what everyone said, you need a Loop that stops when the number typed in the scanner is a prime number.
In this case I would say is better to have another method to check if N is prime or not, for a cleaner code.
✓ Tested
import java.util.Scanner;
public class SieteDosEjerSeis {
public static void main(String[] args) {
boolean prime = false;
// loop until prime is true
while(prime == false){
Scanner s = new Scanner(System.in);
System.out.println("Enter a number:");
int n = s.nextInt();
s.close();
// is it prime?
prime = isPrime(n);
if (prime){System.out.println(n + " is a prime number.");}
else{System.out.println(n + " is not a prime number.");}
}
}
// method that returns true or false depending if N is prime or not
public static boolean isPrime(int num) {
if (num <= 1) {return false;}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {return false;}
}
return true;
}
}
You can extract the prime evaluation to a new method:
class SieteDosEjerSeis {
public static boolean isPrime(int num) {
for (int i = 2; i <= num/2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
// ...
}
Then, change your IO code to be based on the result of this method:
class SieteDosEjerSeis {
// ...
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for (;;) {
System.out.println("Enter a number:");
int num = scan.nextInt();
if (!isPrime(num)) {
System.out.println("The number is not prime!");
continue;
}
break;
}
// This will only be reached if the number is prime
System.out.println("The number is prime.");
}
}
You can use do while loop for this.
class SieteDosEjerSeis {
public static void main(String args[]) {
int temp;
boolean isPrime=true;
do {
Scanner scan= new Scanner(System.in);
System.out.println("Enter a number:");
//capture the input in an integer
int num=scan.nextInt();
scan.close();
for(int i=2;i<=num/2;i++) {
temp=num%i;
if(temp==0) {
isPrime=false;
break;
}
//If isPrime is true then the number is prime else not
if(isPrime)
System.out.println(num + " is a Prime Number");
else
System.out.println(num + " is not a Prime Number");
} while (!isPrime);
}
}
I'm a beginner java developer. I want to build a program that gets a number from the user, then say it's prime or not.
Java code:
import java.util.Scanner;
import static java.lang.System.out;
public class prime
{
public static boolean prime(int n)
{
for(int i = 2; i <n ; i++)
{
if(n % i == 0){
return false;
}
}
return true;
}
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
out.println("enter a number: ");
int x = input.nextInt();
if(prime(x)){
out.println(x + "is a prime number");
}else{
out.println(x + "isn't a prime number");
}
}
}
However, I want to declare a bool variable, then ask the user if they want to continue, the user then says yes or no. I have already written this code in C#:
C# code
class Program
{
static bool prime(int n)
{
for(int i = 2; i < n ; i++)
{
if(n % i == 0)
{
return false;
}
}
return true;
}
static void main(String[]args)
{
Bool permit = true;
While(permit)
{
Console.WriteLine(“enter a number”)
int x = int.Parse(Console.ReadLine());
if(prime(x))
{
Console.WriteLine(x + "is a prime number");
}
else
{
Console.WriteLine(x + " isn't a prime number");
}
Console.WriteLine(“do you want to continue”);
Permit = Console.ReadKey.Key() == ConsoleKey.Y?true:false;
}
}
}
How can I build it in Java?
You can't directly map your C# keyboard key press detection to Java.
AFAIK, checking which key is pressed can only be done via key listeners in Java AWT/Swing GUI programs [How to Write a Key Listener]. Your program, however, is a console program and Java doesn't have any mechanisms to detect which key was pressed in a console application. See this question for more info.
Now what you could do is read the String that a certain key press produced. Something like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean permit = true;
while (permit) {
// your existing code
out.println("do you want to continue?");
permit = input.next("y|Y").equalsIgnoreCase("y");
}
}
I also corrected prime method.
import java.util.Scanner;
import static java.lang.Math.abs;
import static java.lang.System.out;
public class Prime {
public static boolean prime(int n) {
for (int i = 2; i < n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
try {
out.println("enter a number: ");
int x = Integer.parseInt(input.nextLine());
if (prime(x)) {
out.println(x + " is a prime number");
} else {
out.println(x + " isn't a prime number");
}
} catch (NumberFormatException e) {
System.out.println("NumberFormatException");
}
out.println("do you want to continue");
if (!input.nextLine().equals("Y")) break;
}
}
}
Just check if the key pressed is the y (yes) and if yes it continues in the cycle.
static void main(String[] args)
{
ConsoleKey response;
do
{
Console.WriteLine("enter a number");
int x = int.Parse(Console.ReadLine());
if (prime(x)) {
Console.WriteLine(x + " is a prime number");
} else {
Console.WriteLine(x + " isn't a prime number");
}
Console.Write("do you want to continue? [y/n] ");
response = Console.ReadKey(false).Key;
}
while (response == ConsoleKey.Y);
}
I'm currently making a high-low guessing game in Java. I believe I have two issues hindering the game from functioning properly.
Firstly, I have a while-statement inside the playGame method that doesn't change as it is now, and I have trouble understanding how I can make it change if the correct guess is made. As I understand it I can't change the value of boolean bool = true; from the giveResponse method, it has to be done from the same method playGame? If there a better way of doing this than using a while-statement?
Secondly, when the correct guess is made and the playGame method return the value of parameter guessCount to the main method it should then be printed out. The instruction I have for this game says it should be printed in the main method after the return have been made.
import java.io.Reader;
import java.util.Scanner;
public class HiLo2 {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r"
+ "1. 1-10 \r"
+ "2. 1-100 \r"
+ "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n==1) {
playGame(10);
}
else if (n==2) {
playGame(100);
}
else if (n==3) {
playGame(1000);
}
else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int)(Math.random() * maxNumber) +1;
int guessCount = 0;
boolean bool = true;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
giveResponse(answer, guess);
}
return guessCount;
}
public static void giveResponse(int answer, int guess) {
if (guess == answer) {
System.out.println("Your guess is correct!\r");
}
else if (guess > answer) {
System.out.println("Your guess is too high, guess again:\r");
}
else if (guess < answer) {
System.out.println("Your guess is too low, guess again:\r");
}
}
}
I hope the questions are clear and specific enough. Any pointers in the right direction is appreciated.
You could have the giveResponse method return a boolean
static boolean giveResponse(...)
and put return false; inside the if (guess == answer){ case, and return true at the end of the method. Instead of calling giveResponse as a void method, use bool = giveResponse(answer,guess).
And for the second question, add a int numberOfGuesses in the main method before the if statement, and call playGame with numberOfGuesses = playGame(...), then System.out.println("You guessed " + numberOfGuesses + " times."); after the if-statements.
I think this is what you're trying to do.
public class HiLo2 {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r"
+ "1. 1-10 \r"
+ "2. 1-100 \r"
+ "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n==1) {
System.out.println("Guess count: "+playGame(10));
}
else if (n==2) {
System.out.println("Guess count: "+playGame(100));
}
else if (n==3) {
System.out.println("Guess count: "+playGame(1000));
}
else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int)(Math.random() * maxNumber) +1;
int guessCount = 0;
boolean bool = false;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (! bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
bool = giveResponse(answer, guess);
}
return guessCount;
}
public static boolean giveResponse(int answer, int guess) {
if (guess == answer) {
System.out.println("Your guess is correct!\r");
return true;
}
else if (guess > answer) {
System.out.println("Your guess is too high, guess again:\r");
return false;
}
else if (guess < answer) {
System.out.println("Your guess is too low, guess again:\r");
return false;
}
}
}
Here is your complete solution
import java.io.Reader;
import java.util.Scanner;
public class HereSOl {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r" + "1. 1-10 \r" + "2. 1-100 \r" + "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n == 1) {
System.out.println("Guesstcount : " + playGame(10));
} else if (n == 2) {
System.out.println("Guesstcount : " + playGame(100));
} else if (n == 3) {
System.out.println("Guesstcount : " + playGame(1000));
} else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int) (Math.random() * maxNumber) + 1;
int guessCount = 0;
boolean bool = true;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
boolean ans =giveResponse(answer, guess);
if (ans == true) {
break;
}
}
return guessCount;
}
public static boolean giveResponse(int answer, int guess) {
if (guess == answer) {
System.out.println("Your guess is correct!\r");
return true;
} else if (guess > answer) {
System.out.println("Your guess is too high, guess again:\r");
return false;
} else if (guess < answer) {
System.out.println("Your guess is too low, guess again:\r");
return false;
}
return false;
}
}
I think you should use enum, Here is my Solution.
import java.util.Scanner;
public class HiLo2 {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r" + "1. 1-10 \r" + "2. 1-100 \r" + "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n == 1) {
playGame(10);
} else if (n == 2) {
playGame(100);
} else if (n == 3) {
playGame(1000);
} else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int) (Math.random() * maxNumber) + 1;
int guessCount = 0;
boolean bool = true;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
Answer ans = giveResponse(answer, guess);
System.out.println(ans.getMessage());
if (ans == Answer.CORRECT) {
bool = false;
System.out.println("You took " + guessCount + " guess to get right number.");
}
}
return guessCount;
}
public static Answer giveResponse(int answer, int guess) {
if (guess == answer) {
return Answer.CORRECT;
} else if (guess > answer) {
return Answer.HIGH;
} else {
return Answer.LOW;
}
}
private enum Answer {
CORRECT("Your guess is correct!\r"), HIGH("Your guess is too high, guess again:\r"), LOW("Your guess is too low, guess again:\r");
private String message;
public String getMessage() {
return this.message;
}
Answer(String message) {
this.message = message;
}
}
}
So I've tried to make a Java calculator on console, and it's works decent, but when I get the result, I want it to restart like a loop, but I can't figure it out.
import java.util.Scanner;
public class calculator {
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x * y);
} else if (c.equals("+")) {
System.out.println("the total is " + (x + y));
} else if (c.equals("-")) {
System.out.println("the total is " + (x - y));
} else if (c.equals("/")) {
System.out.println("the total is " + (x / y));
} else {
System.out.println("you are an idiot");
}
} catch (Exception e) {
System.out.println("Please enter correct value.");
}
}
}
Use while + break. Below is the working version:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
while (true) {
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x * y);
} else if (c.equals("+")) {
System.out.println("the total is " + (x + y));
} else if (c.equals("-")) {
System.out.println("the total is " + (x - y));
} else if (c.equals("/")) {
System.out.println("the total is " + (x / y));
} else {
System.out.println("you are an idiot");
}
} catch (Exception e) {
System.err.println("Please enter correct value.");
}
System.out.println("Do you wish to continue(y/n)?");
if (test.next().equals("n")) {
break;
}
}
}
}
You can use a while loop:
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
while(true) {
....
}
When you want to stop the calculator, you need enter ctrl - c.
Another way, use a boolean flag and let user dicide whether to continue:
public static void main(String[] args0) {
boolean flag = true;
Scanner test = new Scanner(System.in);
while(flag) {
....
System.out.println("enter y for continue, n for exit");
c = test.next();
if (c.equals("n")) {
flag = false;
}
}
}
Insert while loop before try and put everything below in it.put while(true) and this will repeat infinitely. If you want to press some key to stop make if condition and put break in it.
Scanner sc=new Scanner(System.in);
while(true){
...
if(sc.next()=='q') break; //this is if you want to quit after pressing q
...
}
this executes, however it returns all answers as positive "8 is a multiple of 15" even if it is false. Not sure what I'm not seeing.
Here is what i have:
import java.util.*;
public class Multiples {
public static void main(String [] args){
boolean run = true;
while(run = true){
Scanner input = new Scanner(System.in);
System.out.print("Enter one number:");
int num1 = input.nextInt();
System.out.print("Enter a second number:");
int num2 = input.nextInt();
boolean result = isMultiple(num1,num2);
if(result = true){
System.out.println(num2 + " is a multiple of " + num1);
}
else{
System.out.println(num2 + " is not a multiple of " + num1);
}
System.out.println("Do you want to enter another pair(y/n)?");
String a = input.next();
if(YesOrNo(a)){
break;
}
}
}
public static boolean YesOrNo(String a){
if(a.equals("y"))
return false;
else if(a.equals("n"))
return true;
else
return true;
}
public static boolean isMultiple (int x , int y){
if(x % y == 0 || y % x == 0)
return true;
else
return false;
}
}
if(result = true){
replace with
if(result == true){
(or simply)
if(result){
You are assigning it instead of comparing.