java program with methods and boolean - java

import java.util.Scanner ;
public class ProcessNumbers
{
public static void main( String[] args )
{
Scanner in = new Scanner(System.in) ;
System.out.print("Please enter an integer between 6 and 12, inclusive: ") ;
int num = in.nextInt() ;
boolean result = shouldProcess(num);
String result1 = String.valueOf(result) ;
}
public static boolean shouldProcess(int n)
{
if (n>=6 && n<12)
{
return true;
}
else
{
return false;
}
}
public static boolean processInput(boolean result2)
{
if (result2 == true)
{
System.out.println("Yes") ;
}
else
{
System.out.println("No") ;
}
return result2 ;
}
}
now I am getting the output which is partially right but has forgot the yes or no output in the second method
Please enter an integer between 6 and 12, inclusive:
when it should also include the yes or not output

You are sending in a boolean value in the method parameter of processInput but you are catching it as a String. You need to change it to boolean. Further, you want to check if its value is true with equal signs like below:
public static void processInput(boolean result2)
{
if (result2 == true)
{
System.out.println("Yes") ;
}
else
{
System.out.println("No") ;
}
}
EDIT 2:
Also, you need to change String result1 = String.valueOf(result); to processInput(result);
EDIT 3:
If you want the number printed too that you just entered and then you want a "yes" or "no", then between int num = in.nextInt(); and boolean result = shouldProcess(num);, add this line: System.out.println(num);

There's apparently some code missing, so I'm guessing this is just part of the full thing. So I will only tackle your output issue.
I won't talk about the code in: public static boolean processInput(boolean result2), because you're not running it anywhere in your main method public static void main( String[] args ) anyway.
Now, in your code at:
public static boolean shouldProcess(int n)
if you look at your code, you are assigning the value of the boolean to the new String result1, so result1 now has the new value, but you are not running its output anywhere, so there's no way the program can guess you want to output that value. You need to assign the output:
System.out.print(result1);
However, if you only want to output the boolean, there's no need to assign that boolean value to a new String and then output the new String, you could just:
System.out.print(result);
Unless you're going to use that value somewhere else where creating a new variable would arguably be a good choice.
Also, it seems you want to return either a "Yes" or "No" on your class: public static boolean processInput(boolean result2).
Remember a class that does not return a value, but rather executes a code, has to be written as void. In other words, your:
public static boolean processInput(boolean result2)
should really be:
public static void processInput(boolean result2)
Because if not, you are just making your program return result2;, which in this case can only be either true or false. By adding void to the class, makes the class understand it will be executing your System.out.print code, rather than returning a value for you to use. But also, depends on what you want to afterwards.

Related

Call boolean method statically from separate class

I have a program that takes letters for input and then sums the numeric value of each letter.
I have it so that if I input "abc", my output is "6".
I ignore uppercase letters, so if I input "abC", my output is "3".
What I want to do now, is in a separate class, make a method, which if set to true will run my main program as is, but when it is set to false, it will treat uppercase letters as lowercase, giving an input of "abC", an output of "6".
I hope this makes sense, I've tried a few different things but they all run the programm as is, ignoring uppercase.
Here is my code, I appreciate any constructive feedback.
Thanks
EDIT: I would also appreciate if you didn't downvote me for asking a question, if you don't want to help dont', seems every question I asked gets downvoted for no obvious or fair reason. I didn't want to ask for help since I knew this would happen. We all start have to somewhere!
Main method:
Scanner scan = new Scanner(System.in);
System.out.println("\nPlease enter the letters you would like to use:");
String s, t = "";
scan.next();
s = scan.next();
boolean b = Converter.caseSensitive(false, s);
scan.close();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (!t.isEmpty()) {
t += ",";
}
if (ch >= 'a' && ch <= 'z') {
int n = ch - 'a' + 1;
t += String.valueOf(n);
}
}
Second method in separate class:
public class Converter {
public static boolean caseSensitive(Boolean b, String s) {
for (char c : s.toCharArray()) {
if (Character.isLetter(c) && Character.isLowerCase(c)) {
b = s.equalsIgnoreCase(s);
return false;
}
}
s = s.toLowerCase();
return true;
}
}
I believe your question is "how do I record a static boolean value in a class and then request it from another class?"
public class Configuration {
private static boolean convertToUppercase = true;
public static void setConvertToUppercase(boolean convert) {
convertToUppercase = convert;
}
public static boolean getConvertToUppercase() {
return convertToUppercase;
}
}
This can be used as:
StringConverter.caseSensitive(Configuration.getConvertToUppercase(), input);
Note that most coders (me included) would consider this poor design but explaining why is outside the scope of your question.
There are a lot of other issues with your code. For example your method call above will leave the input string unchanged. But I suggest you ask another question with just the relevant code when you get stuck.
String is immutable in Java. Please read following stackoverflow question for more information about this topic:
String is immutable. What exactly is the meaning?
public static void main(String[] args) throws Exception
{
String test = "abc";
toUpperCase(test);
System.out.println(test);
}
private static void toUpperCase(String test)
{
test = test.toUpperCase();
}
Please note that above code will output:
abc
In order to have "ABC" as result you need to use following code:
public static void main(String[] args) throws Exception
{
String test = "abc";
test = toUpperCase(test);
System.out.println(test);
}
private static String toUpperCase(String test)
{
return test.toUpperCase();
}
This one outputs:
ABC
So your Converter.caseSensitive method should return String.
I don't think you really need the Converter class. You can delete class and replace the line:
boolean b = Converter.caseSensitive(false, s);
with this
boolean shouldCountUppercaseLetters = false;
if (shouldCountUppercaseLetters) {
s = s.toLowerCase();
}

How to use boolean statements and return

I am trying to create a piece of code which will;
return true if given an int n, which is with in 10 of 100 or 200.
import java.util.Scanner;
class nearHundred{
public boolean nearHundred(int n){
Scanner input = new Scanner(System.in);
n = input.nextInt();
if(10>=Math.abs(100-n) || 10>=Math.abs(200-n)){
return true;
}
return false;
}
}
Where have I gone wrong?
From comments it looks like your main method is misplaced, wherever it is I hope it exists only once in a project. Call your class from that main() method, for example -
new nearHundred().nearHundred(100); // a call from main method
Now coming to your code there are several things to correct here. Your method should not take care about Scanner, its job is to take input and check for the logic.
For example;
public class Utils {
public static boolean isNearToHundered(int num) {
return Math.abs(num-100)<=10 || Math.abs(num-200)<=10;
}
}
Give the responsibility to main method for parsing the input, this is how it should work.
Now since I made method static, you can call like
Utils.isNearToHundred(105); // TRUE
Here is how the method should look:
public void mainMethod() {
Scanner input=new Scanner(System.in);
int val=input.nextInt();
boolean nearHundredBoolean=nearHundred(val);
//do something with nearHundredBoolean....
//Same logic, but passes the input to the method nearHundred
public boolean nearHundred(int n) {
if(Math.abs(100-n)<=10 || Math.abs(200-n)<=10)
return true;
else return false;
}
You should pass the value of the scanner input into this method's parameter requirement, instead of not using the parameter n in your current method. If there is a problem, it may be due to the 'input.nextInt()' method that overwrites the value of the parameter n.

Java String Scanner nextline input string not as expected

I have a simple program run in the console which accepts inputs, creates objects based on these and saves those objects into a list. If however a "x" is entered, the function stops.
public static void input(List<Things> slist) {
String strA = new java.util.Scanner(System.in).nextLine();
if(!xcheck(strA) {return;}
Things s = new Things(strA);
slist.add(s);
}
public static boolean xcheck(String xStr){
if(xStr == "x"){
return false;
} else {
return true;
}
}
The problem is that the function xcheck never returns false. It does recognise that the input string contains "x" (xStr.contains("x")), but it doesn't seem to think that the input is only "x", even though when ouptutting the string into the console, it definately only outputs the "x" without anything else and the length of the String is 1.
Strings are comared with equals not ==.
Try:
public static boolean xcheck(String xStr){
if("x".equals(xStr)){
return false;
} else {
return true;
}
}
Use xStr.equals("x") instead of xStr == "x".

Bool vals won't print out in console

I am interested in a very simple string verification problem to see if the starting character in a string starts with an upper case letter and then have the console to display true or false. From my understanding you wouldn't have to invoke something like System.console().printf("true", s) in order to make this happen. I could swear I've seen similar elementary implementations achieved using the following sample code:
public class Verify {
public static boolean checkStartChar(String s) {
if (s.startsWith("[A-Z]")) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
String str = "abCD";
checkStartChar(str);
}
}
but when I run this, nothing displays. If I make a slight modification by adding in conditional printouts before returning T/F, e.g.
public class Verify2 {
public static boolean checkStartChar(String s) {
if (s.startsWith("[A-Z]")) {
System.out.println("yep");
return true;
}
else {
System.out.println("nope");
return false;
}
}
public static void main(String[] args) {
String str = "abCD";
checkStartChar(str);
}
}
the issue is somewhat resolved, as the console displays either "yep" or "nope", yet unresolved because I just want the console to display true or false. That's it. Advice?
As the question has already been answered, I'd like to point out there is no need for RegExes to solve this (and they are expensive operations). You could do it simply like this:
static boolean startsWithUpperCase(String toCheck)
{
if(toCheck != null && !toCheck.isEmpty())
{
return Character.isUpperCase(toCheck.charAt(0));
}
return false;
}
yet unresolved because I just want the console to display true or false
Calling checkStartChar method will return value, that doesn't mean it will print value to console. You need to code how you would like to handle return value. If you want to print return value, then you should do:
System.out.println(checkStartChar(str));
Will print what ever the return of checkStartChar method
if(s.startsWith("[A-Z]")){
String.startsWith(prefix) doesn't take regex as a parameter, you should be using regex APi instead.
Pattern p = Pattern.compile("[A-Z]");
Matcher m = p.matcher(new Character(s.charAt(0)).toString());
if(m.find()){
return true;
}else{
return false;
}
String str = "AbCD";
System.out.println(checkStartChar(str));
Output:
true
In your code checkStartChar(str); is returning a boolean value which is not being used in your program.Then if you want to display true or false then you can use.
System.out.println(checkStartChar(str));

How do I go about writing a loop that's supposed to be boolean yet the answer can be an integer using JOptionPane?

How do I go about writing a loop that's supposed to be boolean, yet the answer can be an integer using JOptionPane?
boolean promptMenu( int menu )
This will represent the core of your code.
Should be in the body of a loop inside main().
Returns true if it should continue running.
Returns false if it is time to quit.
Notice that promptMenu takes in an int parameter:
0 - Prints the Main Menu.
So far this is what I got:
import javax.swing.JOptionPane;
public class BankSystem {
//Fields
static boolean question = true;
static String q ;
static int qt;
//Methods
public static void main(String[]args)
{
while(question = true)
{
promptMenu (qt) ;
}
}
static int promptMenu( int qt )
{
q = JOptionPane.showInputDialog ("Gen's Bank" + "\n \n Print main menu? 0-> YES\n\n") ;
qt = Integer.parseInt(q);
if (qt != 0)
{
question = false;
}
return (qt);
}
}
If you press anything that isn't 0 it still loops. Any Suggestions would help.
Read the question carefully. The question asks you for a method:
boolean promptMenu( int menu )
What you have written is a different method:
int promptMenu( int menu )
You instructor wants you to write a method returning a boolean but you are writing a method that returns an int. You are not answering the question that was asked.
To return a boolean you need:
return true;
return false;
or something like:
boolean boolVar;
boolVar = // Your code here.
return boolVar;
What you got:
public static void main(String[]args)
{
while(question = true)
{
promptMenu (qt) ;
}
}
What you need:
public static void main(String[]args)
{
while(question == true)
{
promptMenu (qt) ;
}
}
If you want to check conditions you have to use one of the following parameters (<, <=, >, >=, !=, ==). One single = is used to assign values to a variable.

Categories

Resources