Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 2 years ago.
Improve this question
I have recently started programming in Java for the first time (just as a hobby), and at the moment Im working with a book "Head First Java" that is very good, but I'm really struggling with understanding the exercises.
Like this for example:
class Output {
void go() {
int y = 7;
for(int x = 1; x < 8; x++) {
y++; // is y now 8?
if(x >4) {
System.out.println(++y + " "); // does this make y = 9?
}
if(y > 14) {
System.out.println(" x = " + x);
break; // how does the break key word affect the rest of the loop?
}
}
}
public static void main(String[] args) {
Output o = new Output();
o.go();
}
}
Can someone please explain to me what goes on in this code?
Variable y must be 15, because you increased it's value many times with the for loop.
++y increases it's value by 1. i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated.
break simply exists from the loop.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 6 years ago.
Improve this question
I am currently taking a HS course on java, so I am a novice at java to say the least. Right now, for my own use, I am writing a program to take a 2 digit number, and then add up it and all the odd numbers before it till 1. I have the Scanner, calculating whether the number is odd or even, and the runner methods done already(the basic bit), but am a bit confused on the logic. I am trying to use a recursion, and do this code, but am a bit stuck. It would be helpful if you could point me in the right direction, without giving the whole code away. Thanks, - A Novice Programmer
public static void main(String[] args)
{
MathRecursion tester = new MathRecursion();
tester.Method1Runner();
}
public void Method1Runner()
{
GetIntM1();
OddOrEven();
System.out.println("\n\n");
}
public void GetIntM1()
{
Scanner kb = new Scanner(System.in);
System.out.print("\n\n\nEnter a 2 digit integer: ");
twoDig = kb.nextInt();
}
public void OddOrEven()
{
if (twoDig % 2 == 0)
{
//This is even method
Method1a(twoDig);
}
else
{
//This is odd method
Method1b(twoDig);
}
}
public int Method1a(int a)
{
//if (a = 1)
int result = 0;
while (a<=b)
{
result+=a;
a++;
}
System.out.println("The sum of all numbers is "+result);
}
You don't need recursion. The sum of the first n odd numbers is n*n.
The number of odd numbers before a number x is floor(x/2) or in Java (int) x/2 or if x is an int, just x/2.
So the expression in Java that gives you "a 2 digit number, and then add up it and all the odd numbers before it till 1" where the number is stored in int x is:
x + (x/2) * (x/2)
or simplified:
x + x*x/4
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 7 years ago.
Improve this question
If this function is running:
public static void maximizeweight(int[] weight, int[] A){
Random r = new Random();
int random = r.nextInt(A.length);
for(int i=0;i<A.length;i++){
while(totalweight(weight,A) < 630){
if(A[random]==0)
A[random] += 1;
}
}
}
The output some times breaks a bit or freezes eclipse, totally at random, and sometimes it is able to give the whole result, other times it doesn't show the last part of the desired result.
If your A[random] != 0 and still your totalweight() returns < 630, the while loop would be infinite. One possible fix (and the one I think you need) is to move your int random = r.nextInt(A.length); inside your while loop.
public static void maximizeweight(int[] weight, int[] A){
Random r = new Random();
for(int i=0;i<A.length;i++){
while(totalweight(weight,A) < 630){
int random = r.nextInt(A.length);
if(A[random]==0)
A[random] += 1;
}
}
}
Note: This would still loop infinitely if the sum of weight array is still < 630. So you will need additional checks.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
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.
Improve this question
When I run it, computer counts only 1 3 5 7 9 ... indexes. For example, if I enter "Hello", computer counts 1-H,1-l and 1 o, it doesn't compute e and l(4th index).
What is wrong with it?
import java.util.*;
public class LetterCount {
public static void main(String[] args){
final int Numchars=26;
Scanner scan = new Scanner(System.in);
int[] upper=new int[Numchars];
int[] lower=new int[Numchars];
char current='a';
char current0='A';
int pox=0;
System.out.println("Enter a sentence");
String line=scan.nextLine();
for(int ch=0; ch<line.length(); ch++){
for(int other=0; other<26; other++){
if(line.charAt(ch)==(char)(current+other))
lower[other]++;
if(line.charAt(ch)==(char)(current0+other))
upper[other]++;
else
pox++;
}
ch++;
}
for(int another=0; another<lower.length;another++)
System.out.println((char)(another+'a')+" " +lower[another]);
for(int b=0; b<lower.length;b++)
System.out.println((char)(b+'A')+" " +upper[b]);
System.out.println("non alphabetic characters: "+pox);
}
}
It basically boils down to:
for (int ch = 0; ch < line.length(); ch++) { // Increment per iteration
doSomething();
ch++; // Increment within body
}
in which you increment ch twice!
You need to get rid of one of them and, since the usual way to do a for loop with known-in-advance number of iterations like this is to put the control variable modification into the for statement itself, I would suggest getting rid of the one in the loop body:
for (int ch = 0; ch < line.length(); ch++) {
doSomething();
}
I think you increments ch twice, at the end of for expression and at the end of for loop.
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 7 years ago.
Improve this question
I have a for loop in java like below,
for (int x = cell.getGridX() - 1; x >= 0 && compareCells(cell, getCell(x, cell.getGridY())); --x, ++matches[0]);
I need to add more validation to the condition so I changed it to,
for (int x = cell.getGridX() - 1; x >= 0; --x) {
if (compareCells(cell, getCell(x, cell.getGridY()))) {
++matches[0];
}
}
But now it doesn't behave as expected, I cannot figure out why, thanks.
In your original for loop, the --x and ++matches[0] were executed only when x >= 0 AND compareCells(cell, getCell(x, cell.getGridY())) resulted as true.
In your new for loop, --x is executed every time x >= 0, and ++matches[0] is only executed when the compareCells() function returns true. To match the original functionality, it'd look more like the following:
for (int x = cell.getGridX() - 1; x >= 0; ;) {
if (compareCells(cell, getCell(x, cell.getGridY()))) {
--x;
++matches[0];
continue;
}
break;
}
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
I have a task to write a simple Java program:
I have two integers a and b. If a>10 and b<10 then it should print out "balanced" and if not then print out "unbalanced"
I know how to make this with 1 variable, but i don't have clue how to make it with 2.
Here is something I have tried:
public static void main(String args[]) {
int a = 1;
int b = 15;
if (a > 10 && b <= 10)
{
System.out.println("balanced");
}
else
{
System.out.println("unbalanced);
}
}
Your code not even compile since there is syntax error. You can make your mistake correct as follows.
int a = 1;
int b = 15;
if (a > 10 & b <= 10) { // why <= by reading your question it should <
System.out.println("balanced");
} else {
System.out.println("unbalanced");
}
Now out put is unbalanced.
Now let's review your code. you have use &(non short circuit) and here. That's not good since always non short circuit operands evaluate both side of the expression.
So you should use && (short circuit)
int a = 1;
int b = 15;
if (a > 10 && b <= 10) {
System.out.println("balanced");
} else {
System.out.println("unbalanced");
}
What's wrong with non short circuit?
Consider following logic.
if(name!=null&name.getFirstName()=="same"){ // Now both side evaluate
}
what happen name==null?, name.getFirstName() will give you NullPointerException. If you use && short circuit you are same from this NPE
if(name!=null&&name.getFirstName()=="same"){ // if first case false not
evaluate second
}
Use && instead of & so that it does a logical and not a bitwise one.
You will find it clearer to read if you put brackets around (a > 10) && (b <= 10) as well.