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

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?

Related

Tried to call method, it was skipped. //Used the same fromat from a working project. Java eclips

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
String input = "";
Scanner in = new Scanner(System.in);
System.out.println("math");
input= in.nextLine();
math(input);
System.out.println("end");
public static void math (String input)
{
if (input=="a" || input=="A")
{
System.out.println("4.0");
}
else if (input== "A-" || input== "a-")
{
System.out.println("3.7");
}
//etc
}
}
What is being printed out is this:
math
a (I entered "a" as input)
end
My method section is being skipped completely! I know that I am calling my method right cuz I did it for a different project last week and legit just copy and pasted the format over!
Try this snippet of code that I had just written for you below.
Ultimately, you should compare strings using variableName.equals(object).
As a tip, I would also recommend that you indent your code so that it looks more cleaner and to improve readability.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Math Letter Grade! \nPlease enter Letter Grade:");
String input = sc.next();
// This calls the method
// Passing what was entered into the Math Parameter.
Math(input);
System.out.println("Program Terminates.");
}
public static void Math(String input) {
if (input.equals("A") || input.equals("a")) {
System.out.println("Your GPA is 4.0");
} else if (input.equals("A-") || input.equals("a-")) {
System.out.println("Your GPA is 3.7");
} else {
System.out.println("More information to be outputted..." +
" But You did well!");
}
}

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

While loop wont stop looping with exception

probably missing something really silly, but my while loop will not stop printing the error message.
Could someone have a quick look and point me in the right direction?
package week5;
import java.util.*;
public class Week5 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
inputInt();
}
public static int inputInt(){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter number:");
int num;
boolean carryOn = true;
while (carryOn = true) {
{
try {
num = myKeyboard.nextInt();
carryOn = false;
}
catch (Exception e) {
System.out.println ("Integers only");
}
}
}
return 0;
}
This line is the problem
while (carryOn = true) {
Instead of using the comparison operator ==, you are using the assignment operator =. So essentially, you're setting carryOn to true every iteration, then automatically running the body of the loop since the condition essentially becomes
while (true) {
Just change that problem line to
while (carryOn == true) {
Apart from the infinite loop and the fact you always return 0; no matter what the user types, the code is far more complex than it needs to be.
// only create one scanner
private static final Scanner myKeyboard = new Scanner(System.in);
public static void main(String[] args) {
int num = inputInt();
// do something with num
}
public static int inputInt() {
System.out.println("Enter number:");
while (true) {
if (myKeyboard.hasNextInt()) {
int num = myKeyboard.nextInt();
myKeyboard.nextLine(); // discard the rest of the line.
return num;
}
System.out.println ("Integers only, please try again");
}
}
In your case:
while(carryOn==true)
or
while(carryOn)
will solve your problem

Palindrome Service Class and Client Class

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.

Looping Forever

I'm trying to loop an exception, but for some reason its not giving me the option to re write my scanner file:
I don't know how to use BufferedReader so that's why I'm using this. Any clues?
Here's my standard class with my method
package arrayExceptionsWithInput;
import java.util.*;
public class GetThoseNumbersBaby {
int firstInt;
int secondInt;
boolean error;
Scanner yourNumbers = new Scanner(System.in);
public void findNumbers()
{
System.out.println(" please enter your first number");
firstInt = yourNumbers.nextInt();
System.out.println(" pleas enter your second number");
secondInt = yourNumbers.nextInt();
int finalInt = (firstInt+secondInt);
System.out.println("total is: " + finalInt);
}
}
And here's my main class with the exception being implemeted with a loop:
package arrayExceptionsWithInput;
import java.util.*;
public class InputException
{
public static void main(String[] args)
{
boolean error = false;
GetThoseNumbersBaby zack = new GetThoseNumbersBaby();
{
do {
try
{
zack.findNumbers();
}
catch(InputMismatchException Q)
{
System.out.println(" one of your integers was incorrect, please try again");
Q.printStackTrace();
error = true;
}
} while (error == true);
}
error = false;
}
}
If anyone has any ideas on how to loop this differently I'm all ears.
Set error false before the action. That way you have the correct exit condition if the user gets it right.
error = false;
zack.findNumbers();
i decided too get rid of the method class
and just put the method into the try exception area.
used a .nextLine after scanner and it seems fixed.
this looks ok?
package arrayExceptionsWithInput;
import java.util.*;
public class InputException
{
public static void main(String[] args)
{
boolean error = false;
int firstInt;
int secondInt;
Scanner yourNumbers = new Scanner(System.in);
{
do{
try
{
System.out.println(" please enter your first number");
firstInt = yourNumbers.nextInt();
yourNumbers.nextLine();
System.out.println(" pleas enter your second number");
secondInt = yourNumbers.nextInt();
yourNumbers.nextLine();
int finalInt = (firstInt+secondInt);
System.out.println("total is: " + finalInt);
yourNumbers.nextLine();
}
catch(InputMismatchException Q)
{
Q.printStackTrace();
System.out.println(" one of your integers was incorrect, please try again");
error = true;
yourNumbers.nextLine();
}
}while (error == true);
}error = false;
}
}
You loop while 'error' variable has value 'true'. However, it becomes 'true' only when the is thrown (i.e. when 'catch' block is executed). Control flow doesn't reach it.

Categories