Array for loops [closed] - java

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 wanted the output to be 1, 4, 9, 16, 25.... etc.
Here's my code:
public class ArrayDemo{
public static main(String[]args){
int [] value = new int[20];
int copy = value[1];
for(int i = 0; i <values.length; i+=3)
{
i = i + 1;
System.out.println(i);
}
I know I'm doing something wrong.. just can't seem to figure out what. It just prints out 1, 4, 7, .. etc. -___- any help would be greatly appreciated!

to print out squares of numbers try
for (int x = 1; x <= 5; x++) {
System.out.println (x*x);
}

Change this:
for (int i=0; i<value.length; i+=3)
{
i = i + 1;
System.out.println(i);
}
To This:
for (int i=1,j=3; i<value.length; i+=j,j+=2)
{
System.out.println(i);
}
Of course, you can run a standard loop and print i*i, but I suppose you wanted to do it differently.
By the way, you may as well get rid of that value array, and use 20 instead of value.length.

for ( int i = 0; i < 20; i++) {
System.out.println(i*i);
}
And that's all

First of all, it is not clean code, the array "value" and the variable "copy" don't have any real purpose.
Secondly, it will not even compile, as you have array named "value" and the "for" loop refers to "values".
Thirdly, you want to print squares of integers from 1 to 20. Better way to do it would be:
for (int i = 1; i <= 20; i++)
System.out.println (i * i);

Related

No code inside of my for loop is being run - Java 8 SE [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 3 years ago.
Improve this question
I've been working on a simple Java code where you are to give 5 numbers to the program through the console, which will then tell you what numbers you chose and give you an average. I noticed, however, after I started trying to test my code, that the for loop was basically 'skipping over' all of the code inside of the loop, and I have no idea why. Here's my code:
import java.util.Scanner;
public class numAv {
public static void main(String[] args) {
int num;
int[] numbers = new int[5];
boolean done = false;
Scanner scan = new Scanner(System.in);
System.out.println("Enter five integer numbers one at a time.");
for (int i = 0; i >= 5; i++) {
scan.nextLine();
num = scan.nextInt();
numbers[i] = num;
}
// The code inside the for loop is being skipped; I'm not getting any time to type in an integer.
System.out.println("Your numbers are:");
for (int i = 0; i >= 5; i++) {
System.out.print(numbers[i]);
}
// The same has also happened above; The code within the for loop is essentially being skipped.
num = 0;
for (int i = 0; i >= 5; i++) {
num += numbers[i];
}
num /= (float) 5;
System.out.println("The average of the chosen numbers is " + num);
}
}
Here's what the console outputs:
Enter five integer numbers one at a time.
Your numbers are:
The average of the chosen numbers is: 0
Here:
for (int i = 0; i >= 5; i++) {
i will have a really hard time being zero and bigger than 5 at the same time.
The real answer here: each and any character that you put into your source code matters. There is a big difference between <= and >=, and even between <= and < for that matter. So, when your code doesn't do what you expect it to do: take a piece of paper, and start "running" that code manually. Really write down the values within your variables, and carefully check what the code is doing with them.
Bad condition:
for (int i = 0; i >= 5; i++) {
This will never works, try this:
for (int i = 0; i < 5; i++) {

How to initialize this array so that it works in the while loop? [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 3 years ago.
Improve this question
I am trying to initialize an array above a while loop and then use the array set the values of the array in the while loop. But netbeans keeps giving me an error message.
public static void main(String[] args) {
int a=999;
int b=999;
int c=0;
int[] array = new int[5];
int[] array2= new int[6];
while(c<=998001){
c=a*b;
if(c<100000){
array[]={c%100000,c%10000,c%1000,c%100,c%10}
//netbeans keeps telling me that this array is "not a statement"
";" expected. Why does it tell me this?//
}
if(array[0]==array[5] & array[1]==array[3]){
int d=c;
}
}
}
Because your syntax isn't valid Java. It seems you want to create a new 5 element array with your statement. You could do so like
array = new int[] { c % 100000, c % 10000, c % 1000, c % 100, c % 10 };
But since you always have five elements, it would probably be more efficient to use a loop and re-use the same array. Like,
if (c < 100000) {
int fac = 100000;
for (int i = 0; i < array.length; i++) {
array[i] = c % fac;
fac /= 10;
}
}

Runtime error - Java [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 was trying to find sum of even fibonacci number for a given set of N inputs(obtained from stdin)
This code is working well for some test cases but printing runtime error(No details given) for a test case.
Link for question: https://www.hackerrank.com/contests/projecteuler/challenges/euler002
code
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.*;
public class Solution {
public static Integer[] convert(int[] chars) {
Integer[] copy = new Integer[chars.length];
Arrays.fill(copy, 0);
for(int i = 0; i < copy.length; i++) {
copy[i] = Integer.valueOf(chars[i]);
}
return copy;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int x, max;
int a[], sum[], fib[];
Scanner in = new Scanner(System.in);
x = in.nextInt();
a = new int[x];
sum = new int[x];
for(int i=0;i<x;i++)
{
a[i] = in.nextInt();
}
Integer[] b = convert(a);
max = Collections.max(Arrays.asList(b));
fib = new int[max];
if (max >1)
{
fib[0]=1;
fib[1]=1;
}
for(int i=2;i<max;i++)
{
fib[i] = fib[i-1]+fib[i-2];
}
for(int i =0;i<x;i++)
{
for(int j = 0;fib[j]<a[i];j++)
{
if(fib[j]%2 ==0)
sum[i] = sum[i] + fib[j];
}
}
for(int i=0;i<x;i++)
{
System.out.println(sum[i]);
}
}
}
Any help is appreciated.
I'll be more thankful if you can help me with an optimized version of the same.
Your code would throw ArrayIndexOutOfBoundsEception in some cases.
Let's consider what you are doing :
You are getting an input x from user
Then you create array a with x elements, input by user
Then you find the max element of a
You create an array fib of max elements, and calculate fib[i] for each i from 0 to max-1
Suppose the user inputs : 2 2 2
max would be 2, so fib would contain two elements : {1,1}
Now, the following loop will cause the exception :
for(int i =0;i<x;i++) // x is 3
{
for(int j = 0;fib[j]<a[i];j++) // both fib[0] and fib[1] < a[0]
// fib[2] would throw the exception
It is not clear what you are trying to do with this nested loop, but clearly it doesn't work.
i think the problem is that the Recursive call stack in java is so deep,so the java compiler will print RE. and to optimize this problem, frist,you can use the dp method to solve this problem。the dp method is to decrease the repeat count to the problem.
the link is http://zh.wikipedia.org/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92
hope to help you.

rolling dice using arrays [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
simple beginner Java question. I just learned how to use arrays and it's still a little confusing to me. My goal is to simply roll a number of dice a number of times and then project it as a sum, frequency, and percentage. I'm sure I'm doing something dumb, but I'm overlooking it!
import javax.swing.JOptionPane;
import java.util.Random;
public class Lab1 {
private static int N = 0;
private static int M = 0;
private static int total = 0;
private static Random rnd = new Random();
public Lab1(){
}
public static void main(String[] args) {
N = Integer.parseInt(JOptionPane.showInputDialog("How many dice would you like to roll?"));
System.out.println("Dice: "+N);
M = Integer.parseInt(JOptionPane.showInputDialog("How many times would you like to roll?"));
System.out.println("Rolls: "+M);
int total[] = new int[(6*Lab1.N)+1];
for (int i=0; i<=total.length; i++)
total[i] = 0;
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
System.out.printf("%3s%12s%12s\n", "Sum","Frequency", "Percentage " );
for(int k=2; k<total.length; k++);{
int percent = total[k]/(360);
System.out.printf("%3s%12s%12s\n", k, total[k], percent);
}
}
}
From what I can see the question is how can you store the previous roles of the dice. And I believe your problem is with this method:
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
I would change this to
for (int roll=1; roll<=M; roll++){
total[roll] = rnd.nextInt(6);
}
This will build up an array storing each dice roll - if that is of course what you are looking for...
Two things.
First, this loop will inevitably throw ArrayIndexOutOfBoundsException ("element" total[total.length] is out of bounds)
for (int i=0; i<=total.length; i++)
total[i] = 0;
You should use < instead of <=.
for (int i=0; i<total.length; i++)
total[i] = 0;
Second, this line here:
for(int k=2; k<total.length; k++);{
You have an empty loop here. You should remove the semicolon before the {:
for(int k=2; k<total.length; k++){
Now your code compiles, doesn't throw exceptions on the start, and prints a pretty table.
That's a start.
for(int k=2; k<total.length; k++);{
You need to remove the ; symbol from your loop as 'k' will not be resolved in the loop as you have terminated it. The format is for(x, x, x) {
The next thing to look at now is:
Dice: 1
Rolls: 1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at Lab1.main(Lab1.java:26)
Hint:
total[i] = 0; // this line is the problem.
Look at your <= in the loop.
for (int i=0; i<total.length; i++)
Simply chaging it to < results in this:
Dice: 1
Rolls: 1
Sum Frequency Percentage
2 1 0
3 0 0
4 0 0
5 0 0
6 0 0

Can't seem to get the right value in a for loop with and if-else statement [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
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
Improve this question
This is my code:
int numArray [] = {1, 7, 6, 4, 5, 9};
int high = 0,low = 0;
for (int count = 0; count < 2; count++) {
if (count == 0) {
for (int countA = 0; countA < numArray.length-1; countA++) { //The increment expression is invoked after each iteration/time through the loop.
high = numArray[countA];
if (high < numArray[countA+1]) {
high = numArray[countA+1];
}
}
}
else {
for (int countB = 0; countB < numArray.length-1; countB++) {
low = numArray[countB];
if (low > numArray[countB+1]) {
low = numArray[countB+1];
}
}
}
}
When I print the value for low from else block, it prints 5 instead of the expected value of 1. Why is this?
You could sort the array (or a clone of the array) like so
public static void main(String[] args) {
int numArray [] = {1, 7, 6, 4, 5, 9};
int [] copy = numArray.clone();
Arrays.sort(copy);
int high = copy[copy.length - 1],low = copy[0];
System.out.printf("Values = %s, Low = %d, High = %d\n",
java.util.Arrays.toString(numArray), low, high);
}
Which outputs
Values = [1, 7, 6, 4, 5, 9], Low = 1, High = 9
I know it's not really answering your question, but the code:
for (int count = 0; count < 2; count++) {
if (count==0) {
doSomething();
} else {
doSomethingElse();
}
}
does exactly the same as
doSomething();
doSomethingElse();
Always consider the KISS Principle
Other responders have given you a better way to write this, but to specifically address your original question, the reason you're getting an "unexpected" (to you) value of "low" is that you're assigning each entry of the array to "low" unconditionally. The entry with "5" is the last entry that you process, so that's the value you end up with.
To address this specific problem, you might assign the array entry value to a new local variable, called "newlow", perhaps. Then, compare "newlow" to the existing "low" value and then conditionally assign it, perhaps like this:
low = numArray[0];
for (int countB = 0; countB < numArray.length-1; countB++) {
int newlow = numArray[countB];
if (newlow < low) {
low = newlow;
}
}

Categories