Palindrome Service Class and Client Class - java

I have several questions I need help with.
I'll add both my code and source code (I guess what assignment asks for clarification) in here.
Service Class
public class Palindrome
{
private String pal;
public Palindrome()
{
pal = " ";
}
public Palindrome(String newPal)
{
pal = newPal.toUpperCase();
}
public void setPal(String initPalin)
{
pal = initPalin.toUpperCase();
}
public String getPal()
{
return pal;
}
public boolean isPalindrome()
{
int left = 0;
int right = pal.length() -1;
while (pal.equals(toUpperCase))
{
if (pal.charAt(left) != pal.charAt(right));
{
return false;
}
left++;
right--;
}
return true;
}
public String toString()
{
return "Palindrome" + isPalindrome();
}
}
Client Class
import java.util.Scanner;
public class Palindromeclient
{
public static void main(String[]args)
{
String pal;
boolean isS = false;
Scanner scan = new Scanner(System.in);
System.out.println("Enter statement press[enter]:");
String userinput = scan.nextLine();
Palindrome statement = new Palindrome(pal);
isS = statement.isPalindrome();
if (isS)
System.out.println(userinput + "is a palindrome");
else
System.out.println(userinput + "is not a palindrome");
}
}
My coding is giving me a
Palindrome.java:34: error: cannot find symbol
while (pal.equals(toUpperCase))
^
symbol: variable toUpperCase
location: class Palindrome
1 error
I don't get why though, can I simply add uppercase to the set or second constructor instead, which might be able to fix my service class.
That's my question, number one

Answer to question 1:
toUpperCase is a method of the String and should be invoked as one.
pal.toUpperCase()
Just like you did in the setPal method.
Answer to question 2:
The boolean in the main method is not needed, because you could ask your Palindrome object if it is a palidrome directly in de System.out.
statement.isPalindrome()
Beware though, your program won't work as you don't pass the user input to the Palindrome Constructor.

Related

(';' expected boolean checkBinary(String num) {^) Need help finding the error

i keep getting a ';' is expected at the checkBinary(String num) { ^ error, yet i can't find any place for a ";". I have only been studying java for a few days so the problem could be something obvious i haven't learnt yet. Please provide a detailed explanation in way i could use it to prevent the problem in later projects. Thank you in advance!
import java.io.*;
import java.util.Scanner;
public class checkbinary
{
public static void main(String[] args)
{
String num;
System.out.println("Enter a number:");
Scanner sc = new Scanner(System.in);
num = sc.nextLine();
if(checkBinary(num)) {
System.out.println("The number is: Binary");
} else {
System.out.println("The number is: Not Binary");
}
boolean checkBinary(String num) {
for(i=0;i<num.length();i++) {
digit = Integer.parseInt(num.substring(i,i+1));
if(digit > 1) {
return false;
}
}
return true;
}
}
You need to move your checkBinary method outside of the main method. You cannot nest methods in java without declaring an inner class.
This should work:
import java.io.*;
import java.util.Scanner;
public class checkbinary
{
public boolean checkBinary(String num) {
for(i=0;i<num.length();i++) {
digit = Integer.parseInt(num.substring(i,i+1));
if(digit > 1) {
return false;
}
}
return true;
}
public static void main(String[] args)
{
String num;
System.out.println("Enter a number:");
Scanner sc = new Scanner(System.in);
num = sc.nextLine();
if(checkBinary(num)) {
System.out.println("The number is: Binary");
} else {
System.out.println("The number is: Not Binary");
}
}
}
If you want to know how to go about solving this with a nested class, there are numerous other questions/examples on SO. Like this one Can methods in java be nested and what is the effect? or In java what are nested classes and what do they do?

How to invoke multiple method signatures within a main method?

So I have three required codes I have already figured out. They are the codes for a quadratic formula, codes for an ISBN checker, and a code for Newtons Method. I'm supposed to make a menu with options 1, 2, and three each containing these codes respectively.
I guess this means I need different methods for this right? I was never really taught - I was told we had to always put in public class void main (String []args){ for everything, and I was just told there were variations to this?
For Quadratics formula, the information is : Return - void and parameters of three doubles, Newtons method: Return - double and parameters of 1 double, and ISBN checker: Return: Boolean and Parameters of 1 string. I don't really understand the parameters thing either. Help would be appreciated. I know this aesthetically looks horrible, but because my codes for now are relatively short I just edit the style when I' done. I know a lot of things are wrong in this too and I've spent time trying to figure them out.
import Java.util.Scanner;
public class HelperMethod{
public static void main(String[] args) {
Scanner userInputScanner = new Scanner (System.in);
System.out.println ("You have three options. press one for the quadratic Formula, 2 for the newtons Method, and 3 for an ISBN checker.");
int input = userInputScanner.nextInt();
if (input = 1){
}else if (input = 2) {
private class NewtonsMethod {
public static void NewtonsMethod(String[] args) {
Scanner userInputScanner = new Scanner (System.in);
double guess, fX, fPrimeX, newGuess;
System.out.println ("enter in a value give");
guess = userInputScanner.nextDouble();
System.out.println ("Your guess is " + guess);
while (true) {
fX = (6 * Math.pow (guess,4)) - (13 * Math.pow (guess,3)) - (18 * Math.pow (guess,2)) + (7 * guess) + 6;
fPrimeX = (24 * Math.pow (guess,3)) - (39 * Math.pow (guess,2)) - 36 * guess + 7;
newGuess = guess - (fX / fPrimeX);
System.out.println ("A possible root is " + newGuess);
if (Math.abs(newGuess - guess) < 0.00001) {
break;
} else {
guess = newGuess;
}
}
System.out.println ("The root is: " + newGuess);
}
}
}else{
private class BookNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char f;
int e, g, h;
int result = 0;
System.out.println ("Pleas enter a thirteen digit number");
String a = scanner.nextLine();
if (a.length() == 13){
for (int i = 0; i < 13; i ++) {
f = a.charAt(i);
e = Character.digit(f, 10);
if (i % 2 == 0) {
g = e * 1;
result = result + g;
} else {
g = e * 3;
result = result + g;
}
}
System.out.println ("The added sum of you numbers is " + result);
if (result % 10 == 0) {
System.out.println ("This combination IS a ISBN number");
} else {
System.out.println ("This is NOT an ISBN number");
}
} else {
System.out.println ("This combination is not thirteen digits long");
}
}
}
}
}
}
First of all, right now you're setting input to 1 in your first if statement. To compare input to 1 instead, use the == operator, i.e. if (input == 1) {.... Secondly, you don't really need to use classes, you can simply have methods NewtonsMethod(), BookNumber() etc. and run them when the input is correct.
public class HelperMethod{
public static void main(String[] args) {
int input;
//Handle user input
switch (input) {
case 1:
newtonsMethod();
break;
case 2:
bookNumber();
break;
case 3:
anotherMethod();
break;
}
}
public static void newtonsMethod() {
//Your code
}
public static void bookNumber() {
//Your code
}
public static void anotherMethod() {
//Your code
}
}
Methods should never be inside one another. That is what classes are for. A method is an element within a class. For example, in your case your class was named "HelperMethod". Your methods need to begin after the main method's code block is closed with a curly brace "}"
as an example
// This would be your main method.
public static void main(String args[]) {
// Your method is CALLED here.
someMethod();
{
// Then this is where your next method would start.
public static void someMethod() {
// Your code for the method of course goes here.
}
Of course you need your class setup and needed imports ABOVE the main method but you have that setup correctly already. With this setup, it makes it easy to call public methods that are in other classes. Your private methods are not really needed unless you intend to use more than one class, at which point you will need to import that class and then call the method like so
SomeClass.someMethod();

How can I check if an input is a integer or String, etc.. in JAVA?

I am wondering how I can check if a user's input is a certain primitive type (I mean integer, String, etc... I think it's called primitive type?). I want a user to input something, then I check if it's a String or not, and do a certain action accordingly. (JAVA)
I have seen some codes like this:
if (input == (String)input) { (RANDOM STUFF HERE) }
or something like
if input.equals((String) input)
And they don't work. I want to know how I can Check for only a String? (EDITED OUT)
I was wondering if there was a function that can do that? Thanks for the answers
EDIT: With the help of everyone I have created my fixed code that does what I want it to:
package files;
import java.util.*;
public class CheckforSomething {
static Scanner inputofUser = new Scanner(System.in);
static Object userInput;
static Object classofInput;
public static void main(String[] args){
try{
System.out.print("Enter an integer, only an integer: ");
userInput = inputofUser.nextInt();
classofInput = userInput.getClass();
System.out.println(classofInput);
} catch(InputMismatchException e) {
System.out.println("Not an integer, crashing down");
}
}
}
No need for answers anymore, thanks!
Use instanceof to check type and typecast according to your type:
public class A {
public static void main(String[]s){
show(5);
show("hello");
}
public static void show(Object obj){
if(obj instanceof Integer){
System.out.println((Integer)obj);
}else if(obj instanceof String){
System.out.println((String)obj);
}
}
}
You may try this with Regex:
String input = "34";
if(input.matches("^\\d+(\\.\\d+)?")) {
//okay
} else {
// not okay !
}
Here,
^\\d+ says that input starts with a digit 0-9,
()? may/or may not occur
\\. allows one period in input
Scanner input = new Scanner (System.in);
if (input.hasNextInt()) System.out.println("This input is of type Integer.");
else if (input.hasNextFloat()) System.out.println("This input is of type Float.");
else if (input.hasNextLine()) System.out.println("This input is of type string.");
else if (input.hasNextDouble()) System.out.println("This input is of type Double.");
else if (input.hasNextBoolean()) System.out.println("This input is of type Boolean.");
else if (input.hasNextLong())
System.out.println("This input is of type Long.");
Hate to bring this up after 6 years but I found another possible solution.
Currently attending a coding bootcamp and had to solve a similar problem. We introduce booleans and change their values depending on the result of the try/catch blocks. We then check the booleans using simple if statements. You can omit the prints and input your code instead. Here's what it looks like:
import java.io.IOException;
import java.util.Scanner;
public class DataTypeFinder {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
String input = "";
while (true) { //so we can check multiple inputs (optional)
input = scan.nextLine();
if ("END".equals(input)) { //a way to exit the loop
break;
}
boolean isInt = true; //introduce boolean to check if input is of type Integer
try { // surround with try/catch
int integer = Integer.parseInt(input); //boolean is still true if it works
} catch (NumberFormatException e) {
isInt = false; //changed to false if it doesn't
}
boolean isDouble = true; //same story
try {
double dbl = Double.parseDouble(input);
} catch (NumberFormatException e) {
isDouble = false;
}
if (isInt) {
System.out.printf("%s is integer type%n", input);
} else if (isDouble) {
System.out.printf("%s is floating point type%n", input);
} else if (input.length() == 1) { //this could be useless depending on your case
System.out.printf("%s is character type%n", input);
} else if ("true".equals(input.toLowerCase()) || "false".equals(input.toLowerCase())) {
System.out.printf("%s is boolean type%n", input);
} else {
System.out.printf("%s is string type%n", input);
}
}
}
}
class Main{
public static void main(String args[]){
String str;
Scanner sc=new Scanner(System.in);
int n,
boolean flag=false;
while(!flag){
try{
str=sc.nextLine();
n=Integer.parseInt(str);
flag=true;
}
catch(NumberFormatException e){
System.out.println("enter an no");
str=sc.nextLine();
}
}
}
}
Is this ok?
class Test
{
public static void main(String args[])
{
java.util.Scanner in = new java.util.Scanner(System.in);
String x = in.nextLine();
System.out.println("\n The type of the variable is : "+x.getClass());
}
}
Output:
subham#subham-SVE15125CNB:~/Desktop$ javac Test.java
subham#subham-SVE15125CNB:~/Desktop$ java Test
hello
The type of the variable is : java.lang.String
But Zechariax wanted an answer with out using try catch
You can achieve this using NumberForamtter and ParsePosition.
Check out this solution
import java.text.NumberFormat;
import java.text.ParsePosition;
public class TypeChecker {
public static void main(String[] args) {
String temp = "a"; // "1"
NumberFormat numberFormatter = NumberFormat.getInstance();
ParsePosition parsePosition = new ParsePosition(0);
numberFormatter.parse(temp, parsePosition);
if(temp.length() == parsePosition.getIndex()) {
System.out.println("It is a number");
} else {
System.out.println("It is a not number");
}
}
}
Try instanceof function with Integer instead of int.. each primitive also have a class

Connecting boolean method from another class to main

Beginner to Java here. I've been researching how to do this, but I guess I'm researching the wrong thing..
My program inputs numbers and calculates what the user inputted. I figured out how to connect a different class (the one that calculates everything) to the main class (the one that will just output everything).
What I'm finding difficulty on is how to connect a boolean, not a void, method to the main class.
public class Driver
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in); //forgot to add scanner
ExampleClass ex = new ExampleClass();
System.out.println("Enter numbers <enter -1 to stop>");
number = in.nextInt(); //user inputs a number
boolean inputData = true; //researched about this, but it doesn't work
ex.inputData(); //doesn't work either
}
}
second class:
public class ExampleClass
{
int numberOfThings = 0;
int number = 0;
int sum = 0;
public ExampleClass()
{
// constructor
}
public boolean inputData(int number)
{
if(number >= 0)
{
numberOfThings++;
}
else if (number <= 0)
{
System.out.println("Out of range");
return false;
}
return true;
}
}
I'm pretty sure my if statement needs work, my only question is how do I connect the boolean method to my main class (Driver)? I'm trying to piece together how to connect methods and such before I start my real project.
boolean inputData = true;
ex.inputData();
does not work.
I just provided an example, my coding isn't complete yet.
update: this worked, posting this in case anyone searching needs this.
boolean inputData = true;
while (inputData)
{
Scanner in = new Scanner(System.in);
number = in.nextInt();
inputData = ex.inputData(in.nextInt());
}
You nearly have it, instead of:
boolean inputData = true;
ex.inputData();
do
Scanner in = new Scanner(System.in);
boolean inputData = ex.inputData(in.nextInt());
Possibly loop until the input is false? I don't really know what you want:
System.out.println("Enter numbers <enter -1 to stop>");
ExampleClass ex = new ExampleClass();
boolean inputData = true;
while (inputData) { // loop until it's false to keep gaining numbers
Scanner input = new Scanner(System.in); // to get input
inputData = ex.inputData(input.nextInt()); // equals the return of inputData
}

How to invoke a java method

I am very new at java coding. I am having difficulty finding out how to link my main method with the method that determines if a value is prime. When I run the code below in eclipse, the method doesn't seem to execute at all. Does anyone know what I did wrong?
Also, for the last part I was thinking of having System.out print whether the input value is prime or not. ie true or false would be fine.
import java.util.*;
class IsPrime {
public boolean isprime(int n) {
Scanner input1= new Scanner(System.in);
System.out.println("input single integer?");
int n1 = input1.nextInt();
int i,c=0;
for(i=1;i<=n1;i++) {
if(n1%i==0){
c++;
}
}
if(c==2) {
return true;
} else {
return false;
}
System.out.println("Your number is:")
}
}
The line
System.out.println("Your number is:")
is unreachable as you have an
else {
return false;
}
before it.
First of all, what it's said by Strawberry and appclay is right.
In the other hand, your method isprime is an instance method whilst your main (I guess you talk about the method of your main class) is a class (static) method.
Try the following:
public static void main(String[] args) {
int possiblePrime = // initialise your parameter
IsPrime isPrime = new IsPrime();
boolean primeOrNot = isPrime.isprime(possiblePrime);
System.out.println("Your number is prime: " + primeOrNot);
}
Change your method to static and you can reference it without creating an instance of that class
public static boolean isprime(int n) {
If I understand what you're looking to is implement an isprime method and call it in a main.
class IsPrime {
public boolean isPrime(int n) {
int i,c=0;
for(i=1;i<=n;i++) {
if(n%i==0){
c++;
}
}
if(c==2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Scanner input1= new Scanner(System.in);
System.out.println("input single integer?");
int n = input1.nextInt();
IsPrime isPrime = new IsPrime();
System.out.println("Your number is prime: " + isPrime.isPrime(n));
}
}
That should do what you want to do. However, there is a bug in your code.
What you have will return true for all numbers not just prime numbers. I'll leave it up to you to spot the bug and the fix.
EDIT: No bug. See below comments.

Categories