Find perfect squares - java

I am trying to write a loop that calls a method to determine if a number entered is a perfect square. It compiles just fine so I must have a logic error, for the life of me though I can't find it. No matter the number I put in it seems to always return false, leading me to believe the problem lies inside the isPerfect() method. I however, do not know enough about java yet to know where to go from here. Here's the code I've got so far:
public class Square
{
public static void main(String[] args)
{
int input = 0; //The default value for input
Scanner keyboard = new Scanner(System.in);
while (input != -1)
{
System.out.println("Please enter a number, or enter -1 to quit");
input = keyboard.nextInt();
if (isPerfect(input) == true) //Call isPerfect() to determine if is a perfect square
{
System.out.println(input + " is a perfect square.");
}
else if(input == -1) //If equals exit code, quit
{
break;
}
else //If it is not a perfect square... it's not a perfect square
{
System.out.println(input + " is not a perfect square.");
}
}
}
public static boolean isPerfect(int input)
{
double num = Math.sqrt(input); //Take the square root of the number passed
if (((num * num) == input) && (num%1 == 1)) //If the number passed = it's roots AND has no remainder, it must be a perfect sqaure
{
return true; //Return true to the call
}
else
{
return false; //Return false to the call
}
}
}

Two potential issues.
arithmetic with doubles is inaccurate. You probably want
int num = Math.round(Math.sqrt(input));
Your test for no remainder doesn't do what you think ... (num%1 == 1) just tests whether n is odd. And you dont really need it .. all you need is if( num*num == input) { ... }

So with the program fixed, here is the entirety of the code:
import java.util.Scanner;
public class Square
{
public static void main(String[] args)
{
int input = 0; //The default value for input
Scanner keyboard = new Scanner(System.in);
while (input != -1)
{
System.out.println("Please enter a number, or enter -1 to quit");
input = keyboard.nextInt();
if (isPerfect(input) == true) //Call isPerfect() to determine if is a perfect square
{
System.out.println(input + " is a perfect square.");
}
else if(input == -1) //If equals exit code, quit
{
System.out.println("Breaking!");
break;
}
else //If it is not a perfect square... it's not a perfect square
{
System.out.println(input + " is not a perfect square.");
}
}
System.out.println("Main complete!");
}
/**
The isPerfect() method returns whether or not a number is a perfect square.
#param input The input from the keyboard scanner, passed as an argument
*/
public static boolean isPerfect(int input)
{
int num = ((int)Math.sqrt(input)); //Take the square root of the number passed, as an integer
if (num*num == input) //If the number passed = it's roots AND has no remainder, it must be a perfect sqaure
{
return true; //Return true to the call
}
else
{
return false; //Return false to the call
}
}
}

import java.util.Scanner;
class perfect
{
public static void main(String args[])
{
int count=0;
System.out.println ("enter any number");
Scanner in =new Scanner(System.in);
int n=in.nextInt();
for(int i=1;i<n;i++)
{
if(n>i*i)
{
count++;
System.out.println( i*i);
}
}
System.out.println("there are "+ count + " perfect numbers");
}
}

Related

how can i Use bets(if) for ReadKey in java

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

How do I simplify this integer validation?

I'm new to Java, and I'm working on a method in my program that checks the users input to be within bounds, not a null value (zero), not a letter, and a positive number. So originally I incorporated two while loops within this method to check for the validity of these inputs, but I would like to simplify it in one loop. I'm getting an error when I input a letter (ex. a) after a few inputs, and I believe it is due to the two different while loops making it more complicated. Can someone help me with this please?
public static void valid(String s, int max)
{
while(sc.hasNextInt() == false) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
}
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
sc.nextLine();
return;
}
You have:
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
Which is doing sc.nextInt() twice, so value does not necessarily have the same value in these two cases and it is also asking you for a number twice.
A fix would be something like this:
int value;
while((value = sc.nextInt()) > max || value <= 0) {
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
which would make it better but you still have issues. If value is bigger than max, then the loop will iterate again calling nextInt() but this time you have not checked for hasNextInt(). This is why you'd better have everything in one loop. Something like this:
public static void valid(String s, int max) {
while(true) {
if(!sc.hasNextInt()) { //this is the same as sc.hasNextInt() == false
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop again
} else {
int value = sc.nextInt();
if(value > max || value <= 0) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop from the top - important!
} else {
extendedValidation(value, s);
return;
}
}
}
}
Try something more like (pseudo code):
while valid input not yet received:
if input is an integer:
get integer
if in range:
set valid input received
skip rest of line
extended validation
With a little thought, you should be able use one "print error message" statement. But using two could be arguably better; it can tell the user what they did wrong.
What is the purpose of the String s parameter? Should you be checking that instead of a Scanner input?
Also, don't be surprised by mixing nextInt() and nextLine(). -- Source
I prefer using do-while loops for input before validation.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int max = 1000;
int val = -1;
String in;
do {
// Read a string
System.out.print("Enter a number: ");
in = input.nextLine();
// check for a number
try {
val = Integer.parseInt(in);
} catch (NumberFormatException ex) {
// ex.printStackTrace();
System.out.println("That is not correct. Try again.");
continue;
}
// check your bounds
if (val <= 0 || val > max) {
System.out.println("That is not correct. Try again.");
continue;
} else {
break; // exit loop when valid input
}
} while (true);
System.out.println("You entered " + val);
// extendedValidation(value, in);
}
I would say that this is a lot closer to what you're looking for, in simple terms...
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
final int MIN = 0;
final int MAX = 10;
Scanner sc = new Scanner(System.in);
int value = -1;
boolean valid;
do {
valid = sc.hasNextInt();
if (valid) {
value = sc.nextInt();
valid = value > MIN && value < MAX;
}
if (!valid) {
System.out.println("Invalid!");
sc.nextLine();
}
} while (!valid);
System.out.println("Valid Value: " + value);
}
}
You should be able to abstract this code to suit your requirements.

Simple Java Guessing program. Continuing

I am just playing around with java and wanted to make a simple program where the user; me has to guess/type in the correct number until it's correct. What can I do so the program can keep running, printing out "Make another guess" until the user/me puts in the correct number. Maybe a boolean? I'm not sure. This is what I have so far.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
input.nextInt();
}
}
You might want to use a while loop to repeat some code:
while (value != myInt) {
System.out.println("Not yet! You entered: " + value + ". Make another guess");
value = input.nextInt();
}
System.out.println("You discovered me!");
This program would do the trick:
public static void main(String [] args){
int myInt = 2;
int value = 0;
Scanner input = new Scanner(System.in);
boolean guessCorrect = false;
while(!guessCorrect){
System.out.println("Not yet! You entered:" + value + " Make another guess");
value = input.nextInt();
if(value == myInt){
guessCorrect = true
}
}
System.out.println("You discover me!");
}
Simply introduce a loop.
import java.util.Scanner;
public class iftothemax {
public static void main(String[] args) {
int myInt = 2;
// Create Scanner object
Scanner input = new Scanner(System.in);
for(;;) {
//Output the prompt
System.out.println("Enter a number:");
//Wait for the user to enter a number
int value = input.nextInt();
if(value == myInt) {
System.out.println("You discover me!");
break;
}
else {
//Tell them to keep guessing
System.out.println("Not yet! You entered:" + value + " Make another guess");
}
}
}
}

Need help w/ java code

Problem "Write a method isMultiple that determines, for a pair of integers , whether the second integer is a multiple of the first. The method should take two integer arguments and return true if the second is a multiple of the first and false otherwise. [Hint: Use the remainder operator .] Incorporate this method into an application that inputs a series of pairs of integers (one pair at a time) and determines whether the second value in each pair is a multiple of the first.har()"
Keep getting "The value of your output is incorrect." Have tried doing multiple things to fix but not sure what's wrong. When I click for feedback I get
Expected Output:
·Enter·one·number:Enter·a·second·number:9·is·a·multiple·of·3↵
Do·you·want·to·enter·another·pair(y/n)?Enter·one·number:Enter·a·second·number:99·is·a·multiple·of·11↵
Do·you·want·to·enter·another·pair(y/n)?Enter·one·number:Enter·a·second·number:7·is·a·multiple·of·7↵
Do·you·want·to·enter·another·pair(y/n)?Enter·one·number:Enter·a·second·number:3·is·not·a·multiple·of·9↵
Do·you·want·to·enter·another·pair(y/n)?↵
Actual Output:
·Enter·one·number:Enter·a·second·number:9·is·a·multiple·of·3↵
Do·you·want·to·enter·another·pair(y/n)?↵
Enter·one·number:
Any help will be GREATLY appreciated ^_^
Code I have so far:
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;
}
}
When you are checking you have to do it like this:
if(result == true){

Java SecretWord Code

I am making basic java program to hold a secret word (mouse) and allow a user to guess letters. The program will end either when the user guesses all the letters in the word, or when they guess 7 wrong letters. Whenever I type any letter into the program, it will run through it without giving the user an option to enter another letter. What should I add so that it will only run the program once per letter entered? Also if it wasnt quite obvious I am new to coding.
import java.util.Scanner;
public class GuessWord
{
String Secretword="mouse";
String letter;
int index;
private int number;
private int counter;
private String guesses;
Scanner scan = new Scanner(System.in);
public GuessWord()
{
String Secretword="";
String letter = "";
String guesses = "";
int number = 0;
int counter = 0;
int index = 0;
}
public String getLetter(){
System.out.println("Please enter a letter");
letter = scan.next();
return letter;
}
public void calc(){
guesses=letter;
while(number <= 7 && counter<5)
{
if(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
guesses=guesses+" " +letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if(number == 7){
System.out.println("You lose");
}else
{
System.out.println("You win");
}
}
}//class
public class GuessWordR
{
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
g1.getLetter();
g1.calc();
}//class
}//main
You should use a while loop.
So while some condition is not met keep asking the user to enter a new key.
Perhaps add a new method to the GuessWord Class
public void startGuessing() {
while(hasGuesses /* some boolean flag */) {
getLetter()
getCalc()
}
}
And then call that method in your main method instead of getLetter() and getCalc().
You will need to add a boolean variable to your class to indicate when to exit this while loop and the logic to keep count of the number of failed guesses etc.
Use a boolean flag and run it in a loop. but for that you need to restructure your code as well. First fix the calc() method
public boolean calc() {
guesses = letter;
if (number <= 7 && counter < 5) {
if (Secretword.indexOf(letter) != -1) {
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
} else {
System.out.println("You entered an incorrect letter");
number++;
}
guesses = guesses + " " + letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if (number == 7) {
System.out.println("You lose");
return true;
} else if (counter == 5) {
System.out.println("You win");
return true;
} else {
return false;
}
}
Your main method should be update like this
public static void main(String[] args) {
GuessWord g1 = new GuessWord();
boolean completed = false;
while (!completed) {
g1.letter = g1.getLetter();
completed = g1.calc();
}
}
you ask user for input unless condition get satisfied instead of asking and calculating once. And read char by char input instead of reading whole string.
something like:
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
while(number <= 7 && counter<5){
g1.getLetter();
g1.calc();
}
}//class

Categories