Logic errors within java segment [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
The following Java code segment is supposed to print, as a double, the mean average of a sequence of non-negative integers entered by the user. A negative input signals the end of the sequence (it is not itself part of the sequence). However, the code is not working. I am supposed to find 4 logic errors within this segment. Please help me find the 4 logic errors?? I know one is its integer division.
public class practice
{
public static void main (String[]args)
{
int sum = 0;
int numVals = 0;
Scanner scan = new Scanner(System.in);
System.out.println(("enter next integer (-ve to stop): "));
int i = scan.nextInt();
while (i > 0)
{
sum = sum + i;
numVals = numVals + 1;
}
System.out.println("average = " + sum / numVals);
}
}

I won't give you full solution, however, it'll be helpful if you pay attention to:
int division as you said,
does your loop terminate? Is someone changing i? Hint: No, and
how do you ask for input? Do you see any loops there? Why it's asking you for only one input?
Not an error, but pay attention to Java Naming Conventions, class name should begin with upper case

Since the homework is for logic errors, I could point out other errors.
the class name should start with upper case letter.
the println doesn't need two nested parenthesis.
the sum should be a long rather than an int to avoid overflows.

Related

If else loop not adding valuing to variable using +=? [closed]

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 2 years ago.
Improve this question
I have a 1D matrix with data and another with scores. I'm trying to loop across all of the elements in the data and find the element in the same position in the score matrix, and keep adding these values together during each loop. For some reason, my script keeps starting from sum = zero instead of retaining and adding to the sum from the previous loop. For the below example, I expect sum = 1 in the first loop, 3 after the second loop (since 1+2=3) and 6 after the third loop (3+3=6). Instead, sum just yields the last value retrieved from scores. What am I doing wrong here?
public static int calc_score( )
{
String [] dat = {"A", "B","C"};
int [][] scores = new int [1][3];
scores[0][0] = 1;
scores[0][1] = 2;
scores[0][2] = 3;
int sum = 0;
for (int i = 0; i < dat[0].length(); i++)
{
if (dat[i].equals("A")) {
sum = sum + scores[i][0];
// scores[i][0] returns the expected value of 1 in the first loop
}
else if (dat[i].equals("B")) {
sum = sum + scores[i][1];
}
else if (dat[i].equals("C")) {
sum = sum + scores[i][2];
}
}
System.out.println(sum);
return sum;
}
I tried modifying sum = sum + scores[i][1]; to sum+=scores[i][1] but that doesn't fix this. I have to be missing something simple.
Learn to debug. Add println statements, or use a debugger, and track, on paper if you prefer, what you think the program should do. Where the computer does something different from what you thought: Voila. You found a bug; there may be more.
If you can't figure out why something is happening, go back and re-check assumptions.
Had you done that here, for example, you might have eventually noticed: Huh, that for loop really is only running exactly once, that's bizarre. Eventually you'd check what dat[0].length() returns and then realized it returns, mysteriously, 1, and perhaps then you'd have one of those slap yourself on the forehead moments: dat[0] refers to the first entry in the dat array, so, the string "A". Then you ask that string about length, which dutifully returns 1.
I assume you wanted dat.length instead.
Note that scores[1][0] is 0 too, you have more than one problem here.

JAVA Project Euler P. #8, Find greatest product from 1000 digit number [closed]

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
https://projecteuler.net/problem=8 link to problem
Find the thirteen adjacent digits in the 1000-digit number that have the greatest product.(number is in the code as String num)
The answer i am getting is "9205903071867879424" (wrong answer)
Please point out the mistakes in my code and also suggest your solution to solve the problem efficiently as possible.
I read the other threads about this problem but couldn't understand them and also there weren't enough efficient solutions.
public static void main(String[] args){
String num = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
long product=1;
long greatestp=0;
long limit=13;
for (int i=0; i<num.length()-13; i++){
product = 1;
for (int j=0; j<limit; j++ ){
product = (long) (product * (int) (num.charAt(j+i)));
}
if (greatestp<product){
greatestp = product;
}
}
System.out.println(greatestp);
}
P.S. I'm a beginner at JAVA, I would appreciate if you explain your solution in detail.
charAt gives you the ascii charcode, not the actual digit. Therefore the fastest way is to subtract the value of '0' from it:
product = product * (num.charAt(i+j) - '0');

Using functions in Java Programming [closed]

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 doubt in using functions in java. I have wrote code for sum of natural numbers using a recursive function but I don't understand the error I am getting. I know it's a silly question though I'm a beginner and I need a brief explanation.
Here is the code
import java.util.Scanner;
public class natural {
public static int main(String args[]){
int a, s = 0,y;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number:");
int x = in.nextInt();
public static int SN(y)
{
if(x==1)
{
return 1;
}
else{
int N = SN(x-1) + x;
return N;
System.out.println("THE SUM IS :"+x);
}
}
Several problems:
You cannot declare a method within a method. Your SN method must be declared outside of the main method.
The parameter y in your SN method must have a type. Based on usage, it is probably supposed to be an int, so the method signature should look like SN(int y).
Despite the method parameter being called y, you appear to be using x everywhere. You should change x to y in the SN method, since that is the label of the data being passed to the method.
As others have pointed out, statements after the return line are unreachable, and as Matt Coubrough said, your IDE is likely warning you about this. Place it before the return line.
Well, one problem here is that you have an unreachable statement. Your System.out.println("THE SUM IS...") is never reached.

Java, Methods? Or constructors ? I am not sure what to call it [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am not sure if you see what I am trying to do here but basically I have a few questions and problems
1)The part that is called public MethodPractice() ... what is this called? is this considered a constructor a method or what?
2)The part named MethodPracticeDiff() . . . is this allowed and if so how do I insert it into the main method for execution...
Do you guys see what I am trying to do here? Basically I want to split the program up into different pieces for example let say I wanted my own space for a calculation method to add to numbers up
and another method to define the numbers like give them a value
and a last method with a for loop making the numbers printout 10times
Any who before I make this more confusing than what it is, my question is how do I make this program execute
public class MethodPractice {
public static void main (String[]args){
MethodPractice add = new MethodPractice();
//MethodPracticeDiff add2 = new MethodPracticeDiff();
}
public MethodPractice() {
int x = 0;
int y = 99 ;
int total = x + y;
System.out.println(total);
}
public void MethodPracticeDiff(){
int z = 10;
int k = 25;
int total = z + k;
System.out.println(total);
}
}
(1) If it's in class MethodPractice, it's a constructor.
(2) Yes, this is allowed. But it's a method not a constructor. Standard practice is to begin it with a lowercase letter.
As follows in the main() method:
MethodPractice add = new MethodPractice();
add.methodPracticeDiff();
MethodPractice() is a constructor -- it has no return value and matches the name of the class.
MethodPracticeDiff() is a method -- it has a return value and does not match the name of a class.
You call methods once you have an instance of the class. e.g.
MethodPractice add = new MethodPractice();
add.MethodPracticeDiff();

drawString in loop writes only once instead of multiple times [closed]

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
What would this code do?
for(int i = 0; i < enemysno; i++){
g.drawString("\nArray size: " + i, 200, 200);
}
enemysno is a random number between 0 and 10, and works fine. Problem is, it loops once, but then stops adding new lines after the first iteration.
As Psuedo code, I though the i starts as 0. Then compares the condition, if its false, does the code, then makes the ++ iterations, then repeats the loop?
Ultimatly, I want to add n objects to an array, but I can quite get this to work simple array to work!
A simple test proves the loop indeed works as intended:
public static void main(String[] args)
{
int enemysno = 5;
for (int i = 0; i < enemysno; i++)
{
System.out.println("lalala " + i);
}
}
this works fine producing
lalala 0
lalala 1
lalala 2
lalala 3
lalala 4
It was kind of obvious, but via debugging or such a test you could determine that the loop itself is entered the desired numer of times. The problem must be in your string display: most probably your drawString method overwrites the printed string each time.
It should be obvious if you checked the numbers on your output.
The solution?
use a string builder to concatenate the partial strings and then draw the final string using your drawString method

Categories