Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm creating a program. This code below is the Java program. Checking if the value of B and H, input by the user is equal to zero. If it is true, then a math formula will execute which is p = b*h then if it is false, a string will be shown on the console. But the thing is, it keeps on giving me an error that string cannot be converted to int or int cannot be converted to string.
Here is the code:
import java.util.Scanner;
public class StaticProject{
static {
Scanner input = new Scanner (System.in);
int B = input.nextInt();
int H = input.nextInt();
int P;
int solution = B>=0 && H>=0 ? P = B*H : "java.lang.Exception: Breadth and height must be positive";
}
How can I improve my coding when it comes in doing this oneline bi-conditionals statement? Any tips?
your solution variable Type is int, and your else statement returns an String, this is the cause of error.
you can change your code to this:
Scanner input = new Scanner (System.in);
int B = input.nextInt();
int H = input.nextInt();
int P;
if (B >= 0 && H >= 0) {
P = B*H;
} else {
throw new Exception("Breadth and height must be positive");
}
System.out.println(P);
}
You are trying to assign string to an int variable, if your statement is evaluated as false.
You need to use if/else condition, which both sides have the same type.
In your case, it's not possible.
another possibility is use System.out.println() command, to print the result of whatever resulted by the condition.
There is no virtue in writing code in as few lines as possible. By all means, don't write unnecessary code, but just don't think that concise code is objectively "better".
The best type of code to write is simple code. Maybe it's a little more verbose; but if you write code that people can understand at a glance, they know what it does straight away.
Here is how I would write it:
if (B < 0 || H < 0) {
// Actually, non-negative, rather than positive.
throw new Exception("Breadth and height must be positive");
// Or, maybe, don't even use exceptions at all:
// System.out.println("The message");
// return;
}
// No need for `solution` variable.
P = B * H;
System.out.println(P);
Of course, you might argue this isn't code everybody will understand at a glance. Sure. Readability is subjective; but I assert that anybody with just a little bit of experience in Java can work it out.
You can write a conditional ?: expression which results in an exception being thrown in the case of the condition being false.
// Define a method which does the throwing.
static int justThrow(String message) throws Exception {
throw new Exception(message);
}
// In the main method:
int solution = B>=0 && H>=0 ? P = B*H : justThrow("Breadth and height must be positive");
I emphasize that you can, but you shouldn't do this. It's obscure. It's trying to be "a bit too clever". It will have people reading your code and scratching their heads, because they will wonder why you wrote a method for something so simple; what is the solution variable for, given that it will have the same value as P etc.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying here to measure how many white spaces there are in text typed in a JTextArea. I am getting an outofbounds exception. Why so?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:658)
at ClassTest.main(ClassTest.java:11)
import javax.swing.*;
public class ClassTest {
public static void main(String [] args) {
JFrame frame = new JFrame();
JTextArea textarea = new JTextArea();
frame.setSize(300, 300);
frame.add(textarea);
frame.setVisible(true);
String text=textarea.getText();
int count = 0;
for(int i=0;i>=text.length();i++) {
char spacecount = text.charAt(i);
if(spacecount==' ') {
System.out.print(count++);
}
}
}
}
I believe it should be < not >= for the 'for' loop condition.
Your for loop is as follows:
for(int i=0; i>=test.length();i++){
char spacecount = test.charAt(i);
if(spacecount==' '){
System.out.println(count++);
}
}
Let us take a walk through the for loop. The first part says, we create an int called i and initialize it to 0;
i = 0;
Next part says, keep looping while this condition is true. So it will loop while
i >= test.length()
The next part says, after each iteration, let us add 1 to i. The only reason it could possibly run is
if test.length() == 0;
if test.length() == 1;
0 is not >= 1 so it won't run. That means, the only reason it could run is if the length is 0. Now if the string is of length 0, it would be "".
What is the charAt(0)? Nothing. There is no 0 index. If the String were "a". Then charAt(0) would return "a". It is reaching for something that does not exist and therefore will not run. So one of the problems is that you need to change the condition to < instead of >=. Next, it is recommended to use camel case for fields (such as spacecount) which means you should change it to spaceCount.
Lastly, it may not occur in this case but let us say, test = null. What happens? What is null.length()? Is that even possible? Well actually it will compile in the case that test = null; and then test.length() is executed. However, you cannot call such a method on a null value so you will get the dreaded runtime error, the "NullPointerException". This says, uh oh. We have a string that points to null. Well we cannot do anything with it. Here comes the exception. So in future code, it is recommended to be able to account for such cases. So what do we do? How do we check if a String == null? Well... String == null. So in the future, if it is possible for something to be null, put the for loop in an if statement that says:
if(test != null){
//put for loop here
} else{
//do something else
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have this code...
class Test {
public static void main(String[] args) {
Boolean mySuperBoolean = Boolean.FALSE;
System.out.print("a");
if (mySuperBoolean = Boolean.TRUE) {
System.out.print("b");
}
System.out.print("c");
}
}
I am new to Java, but I knew single equal (=) is used to assign. And double equals (==) is used to check if object is referred to the same location in memory. However, in this case I do not understand how the 'b' is being printed with a single equals, but I understand changing it to a double equals sign will not print it out
if (mySuperBoolean = Boolean.TRUE) will assign Boolean.TRUE to your mySuperBoolean variable and the condition will evaluate to true, hence whatever is inside your if it will always execute
The result of the assignment operator = will be the assigned value. So if (mySuperBoolean = Boolean.TRUE) will always evaluate to true.
Assignment is an expression which resolves to whatever was assigned, in this case(mySuperBoolean = Boolean.TRUE) is an expression which resolves to Boolean.TRUE.
This is really only useful in a few specific situations. One such case is the following idiom:
String line;
while ((line = readLine()) != null) {
//...
}
Or even
i = j = k = 0; // equal to: i = (j = (k = 0))
It's a controversial feature because it allows probable bugs such as yours to compile successfully. To mitigate this, some people will invert the operands (a "yoda condition"):
if (Boolean.TRUE == mySuperBoolean)
This works because if I forget the second equals then the compiler will throw an error because Boolean.TRUE is final and cannot be assigned to.
In essence, what happens here boils down to:
if (Boolean.TRUE) {
System.out.print("b");
}
That assignment puts TRUE into the variable, the variable is boolean, and checked for its current value, end of story.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Edit: I have found a way to work with CompareTo to help with this problem, but for some reason I cannot get the count down to work.
It's a negative number that needs to get more negative to meet the requirements, but I am missing something here. When I execute the down section it closes the program. So to me this means that I have something messed up and the program isnt seeing the problem and closing.
We are supposed to:
Ask the user for an integer then ask the user if he/she wants to count
up or down. Display a table of numbers where the first column contains
the counter, the second column contains the counter plus 10, and the
third column contains the counter plus 100. Make it so each number
takes up 5 spaces total.
If counting up, the first column should contain numbers 1 through the
user input; If counting down, the first column should contain numbers
-1 through the the negative of the user input;
Do user input validation on the word "up" and "down". Allow for any
case.
import java.util.Scanner;
public class ps1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//Comparision string already declared
String up = "up";
String down = "down";
//initialize the counters sum
int sum = 0;
//ask the user for a number
System.out.println("Enter an ending value");
int num1 = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Count up or down?");
String input = keyboard.nextLine();
while (input.equalsIgnoreCase(up) || input.equalsIgnoreCase(down)) {
System.out.println("Count up or down?");
input = keyboard.nextLine();
}
if (input.compareToIgnoreCase(up) == 0) {
if (num1 >= 0)
for (int c = 1; c <= num1; c++) {
sum = sum + c;
System.out.printf("%5d%5d%5d\n", c, c + 10, c + 100);
else
System.out.println("Up numbers must be positive");
if (input.compareToIgnoreCase(down) == 0) {
for (int c1 = -1; c1 <= num1; c1--) {
sum = sum + c1;
System.out.printf("%5d%5d%5d\n", c1, c1 + 10, c1 + 100);
}
}
}
}
}
I see you have figured out core logic. BTW, your code will not compile, there is a syntax error.
Your code would look like this:
print(a a+10 a+100)
I know that it's not valid syntax but you would be able to figure out the correct way to write the code.
To print data properly, you will need following:
https://dzone.com/articles/java-string-format-examples
I would recommend visualizing the output first. In your case, it would look like following: (_are spaces)
Enter an ending value: 2
Direction: Up
____1___11__101
____2___12__102
Also, think about error cases. What will happen in following:
Enter an ending value: -10
Direction: Up
Error: Improper data
You are allowing user to enter a positive num1 and count down using for (int counter1 = -1; counter1 >= num1; counter1--). This makes no sense as counter1 >= num1 resolves to -1 >= 1 which is never true. When direction is down the number must be negative and when direction is up the number must be positive.
You might need to loop until user provides a valid direction. Currently you go down for any input that is not up. A possible solution would be to:
String input;
do {
input = keyboard.nextLine();
} while (!input.equalsIgnoreCase("up") && !input.equalsIgnoreCase("down"));
Please use shorter variable names. counter1 is scoped just to the for loop block so call it i. It's easier to read.
Whichever editor you are using configure auto formatting :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is my first time doing java and I am am trying to get the largest number from an array of x numbers using a method called bigNum(). Can anyone tell me why this doesn't work?
class project3
{
public static void main(String args[])
{
int total =0;
int b;
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for (int i=0; i < maxItems; i++)
{
b = EasyIn.getInt();
}
bigNum(b);
}
public static void bigNum(int maxItems)
{
for (int i = 1; i >= maxItems; i++)
{
if (bigNum(b) >= maxItems)
bigNum(b) = maxItems;
}
return bigNum(b);
}
}
You're probably getting compiler errors at this point due to unmatched braces. You want your program to have matched braces, and you also want to avoid having methods inside of other methods.
You want to have something that has the following form
class project3
{
public static void main(String args[])
{
...
}
public static int bigNum(int maxItems[])
{
...
return someInt;
}
}
// capital letter for the class (convention)
public class Project3 {
public static void main(String args[]) {
//int total = 0; // you never used this number
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for(int i = 0; i < maxItems; ++i) {
int newNumber = EasyIn.getInt();
/* you want to put the numbers into an array,
so don't call "bigNum" but put them there: */
numbers[i] = newNumber;
}
// now find the big number:
int bigNumber = bigNum(numbers);
System.out.println("The biggest number: " + bigNumber);
}
// first: change the return type to get the biggest number
// second: pass the reference to the array, not a single number
// public static void bigNum(int maxItems) {
public static int bigNum(int[] items) {
// create big number, assume it's very small:
int bigNumber = Integer.MIN_VALUE;
// this for loop will never run, change it a bit:
//for(int i = 1; i >= maxItems; i++) {
for(int i = 0; i < items.length; i++) {
// your idea is correct, but you can not use the
// method here, see explanations below
// Also don't check for the number of Items, but for
if(items[i] > bigNumber) {
bigNumber = items[i];
}
}
return bigNumber;
}
}
Explanations and further readings
Class name: Java has lots of different naming conventions, but the most common rules are: ClassNames/Types in CamelCase with a Capital at the beginning, variableNames following a similar convention but with a leading small letter. This makes it much easier to read code.
Indentation: Try to use a more consistent indentation. Also supports readability. Actually some other programming languages even rely on correct indentation.
Try to understand what variables and what methods are and how to use them (and return from them, you can not assign values to a method in Java. While you read the latter tutorial focus on return types and how to call methods correctly, you can not return an int when your method is of type void. Also the parameters need to be exactly defined.
Apart from that try to compile your code before you post it. As your code went, it should have thrown lots of compile errors, e.g. bigNum(b) = maxItems; should tell you that the left-hand side of an assignment needs to be a variable. This can help you a lot while tracking down mistakes.
Another error is that for most people EasyIn will not be defined (as it is for me, so the code I posted above might actually not be working, I didn't try). I suppose it's a learning library (we had our AlgoTools back in our first Java lectures). Still it would be nice to tell us what it is and what other imports you use (common mistake when I let my IDE decide my imports for me: java.util.Date and java.sql.Date).
Also try to make clear to yourself what you want to achieve with your program and how. Your algorithm actually looks like you didn't think too much about it: You try to find a biggest number and always check "a big number" against the number of expected items, which then might become "the big number" as well. Or something like that.
Programming is being concise and exact, so make a plan before. If it's too hard for you to think about a solution directly, you can maybe draw it on paper.
And if you then have problems, after compiling, asking your program, asking google, asking stack overflow: provide us with as many details as you can and we will be able to help you without just posting some code.
Good luck!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm having a problem in one of my methods. Please keep in mind that I am learning Java in college so I might not be up to speed on simple things. Below is a method that is made to add expressions. The problems I'm running into is found where x = x.substring.(1, x.length() - 1); I'm getting an exception that reads:
Exception in thread "main" java.lang.NullPointerException
I have no idea what that means and/or how to fix it. If you could point me in the right direction, that'd be great.
Thanks.
public static int adder(String x){
int total = 0;
x = x.substring(1, x.length() - 1);
sopln(x);
String[] nums = x.split("\\+");
for(int i = 0; i < nums.length; ++i){
if(nums[i].charAt(0) == ' ' || nums[i].charAt(nums[i].length()-1) == ' '){
sopln("ERROR: Excess whitespace identified.");
nums[i] = nums[i].trim();
}
nums[i] = nums[i].replaceAll(" ", "");
if(nums[i].charAt(0) == '-')
total -= Integer.parseInt(nums[i]);
else
total += Integer.parseInt(nums[i]);
}
return total;
}
It probably means that your String x is null and not actually set to an Object of a String.
How are you calling the method?
Does it happen when you call it with a hard coded string like
int num = adder("string checking in");
if not, then somewhere upstream in your code, that String variable you are passing into the adder method is null.
you are passing a null value when you call adder(the_string), where the_string is null
The problems I'm running into is found where x=x.substring.(1,x.length() - 1);
This means that at some point you are calling adder with an argument that is null. That's the only way you can get an NPE at that point.
Find out where and why the argument is null, and then fix it.
(It could be an explicit null, but it is more likely to be coming from an uninitialized field, or from some method that returns a null to indicate something; e.g. BufferedReader.readLine() returns null when the reader reached the EOF position.)