Unknown error when printing solutions in for statment - java

I'm fairly new to java and I'm attempting to create a simple java program that checks for arithmetic and geometric sequences and lists the desired amount of terms from the sequence out. Everything in the program works properly until the printing of the next terms in the for statement occurs. There is no errors, and I can't find anything wrong. Any help is appreciated.
if(num2-num1 == num3-num2){
d = num2-num1;
System.out.println("This is a arithmetic sequence.\nCommon Difference = " + d);
System.out.println("How many terms of this sequence would you like?");
int a = scanner.nextInt();
for(int i = 1; i >= a; i++){
num3 += d;
System.out.println(num3);
}
suc = 1;
}

Please change i>=a to i<=a.

your for loop parameters are wrong :
change the for loop :
for(int i = 1; i >= a; i++)
to something like this :
for(int i = 1; i <= a; i++)

Related

Checking if values stored in an ArrayList are greater than a number

I'm attempting my first project in Java after learning the basics, so I apologize for what is likely a complete beginner question. I have been searching all afternoon for assistance, and my code is starting to look messy and broken.
I am attempting to create a dice roller that rolls a number of d10s, then proceeds to check how many are 7's or above and count/display them as successes. If none of the rolls are a success, I want it to display "Botch".
After some research, I found creating an ArrayList and going from there was (what seems to me as) the best option. But I've been stuck for some time now, with different errors and issues coming up, and each time I take one down, the code gets more confusing and my goal seems farther away. My buddy said "welcome to programming" and suggested I ask the community.
Here is what I'm working with:
import java.util.Scanner;
import java.util.ArrayList;
public class RollDie {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String numberOfDice;
// User input for number of dice to roll
System.out.print("How many dice? ");
numberOfDice = userInput.next();
System.out.println("Rolling " + numberOfDice + " dice!");
userInput.close();
Integer roll = 0;
int dice = Integer.parseInt(numberOfDice);
int sides = 10; // # of die sides
ArrayList<Integer> sux = new ArrayList<Integer>(); // Store results of roll
// print result
for(int d=0; d < dice; d++) {
// roll should be 1 through sides
roll = (int) (Math.random() * sides) + 1;
sux.add(roll);
}
System.out.println(sux);
// Count successes and print or check for botch
for(int s = 0; s < sux.size(); s++){
if(sux.get(roll) >= 7) {
s++;
System.out.println(s + " successes!");
} else {
System.out.println("BOTCH!");
break;
}
}
}
}
Everything after it prints the sux ArrayList is a mess. I know that the for loop is wrong, I just don't know how to make it right. The variable s seems out of place... Any help would be appreciated, and let me know if this post is against standards for the community in anyway. Thanks!
EDIT: To clarify my ramblings, my question is: how to check if the numbers that are being added to the ArrayList after rolling are greater than or equal to 7 (or any number)?
As #Aomine suggestion earlier you need a flag which helps you to find rather if any dice is >=7 or no dice reach this condition.
// Count successes and print or check for botch
boolean isBotch=false;
for(int s = 0; s < sux.size(); s++){
if(sux.get(s) >= 7) {
//s++; //no need to use this counter here again
System.out.println((s+1) + " successes!"); // s+1 gives you right location
} else {
isBotch = true; //flag variable
}
}
if(!isBotch){
System.out.println("BOTCH!");
}
How about this?
System.out.println(sux);
// Count successes and print or check for botch
int gtNumber = 0;
for(int s = 0; s < sux.size(); s++){
if(sux.get(s) >= 7) {
gtNumber++;
System.out.println(s + " successes!");
}
}
if(gtNumber == 0){
System.out.println("BOTCH!");
}
}
updated:
for(int s = 0; s < sux.size(); s++){
if(sux.get(roll) >= 7) { //here value of sux.get(roll) will be regardless to s. should be typo.
s++;// no need to change value of s, as it will be changed during for clause.
System.out.println(s + " successes!");
break;
} else {
System.out.println("BOTCH!");
}
should be
bool foundvalue = false;
for(int s = 0; s < sux.size(); s++){
if(sux.get(s) >= 7) {
System.out.println((s+1) + " successes!");
foundvalue = true;
break;
}
}
if (!foundvalue){
System.out.println("BOTCH!");
}

(Java) A search similar to Binary but using /3 instead of /2

I have created a program which compares different search methods which search for a random int value 0-999 from a sorted array which is 0-999. I have created a binary search which works perfectly and after doing this I decided to try to create a search which, instead of splitting the values into half, splits them into 1/3 and 2/3 depending.
So basically if I have
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
and I was looking for 10 I would go from above to
{6,7,8,9,10,11,12,13,14,15}
to
{10,11,12,13,14,15}
to
{10,11}
then
simple {10} and return the index of this value.
I currently have:
int loopTotal3 = 0;
for(int y = 0; y < 1000; y++){
System.out.println("Reference1");
int first = 0;
int last = array0Through999.length - 1;
int third = (array0Through999[0] + array0Through999[999]) / 3;
int findThis3 = rand.nextInt(1000);
int loop3 = 0;
while(first <= last){
System.out.println("Reference2");
loop3++;
if (array0Through999[third] < findThis3){
System.out.println("Reference3");
first = third + 1;
}
else if(array0Through999[third] == findThis3){
System.out.println("Reference4");
break;
}
else{
System.out.println("Reference5");
last = third-1;
}
third = (first + last) / 3;
}
loopTotal3 = loopTotal3 + loop3;
}
int loopAverage3 = loopTotal3 / 1000;
System.out.println("The average number of times for a Binary Search is: " + loopAverage3 + "\n");
The code is currently getting stuck running through the first if statement and I am not positive of why.
Any ideas about my issue or if this logic is close to correct?
Using the same algorithm on a smaller data set, I can see an issue. Use an array with only 3 members: 0 1 2. Try to find 2. Third will get stuck on 1, and never get up high enough to find 2.
This will infinitely loop never getting third up to 2. You may be hitting a similar window somewhere else in the code. Because it enters the first if, it does first = third + 1 which yields first = 2. third=(first+last)/3=4/3=1.
import java.util.Random;
public class weqfgtqertg {
public static void main(String args[]) {
int array0Through999[] = {0,1,...,999};
int loopTotal3 = 0;
Random rand = new Random();
for(int y = 0; y < 1000; y++){
//System.out.println("Reference1");
System.out.println(y);
int first = 0;
int last = array0Through999.length - 1;
int third = (first + last) / 3;
int findThis3 = rand.nextInt(1000);
int loop3 = 0;
while(first <= last) {
//System.out.println("Reference1");
loop3++;
if (array0Through999[third] < findThis3){
//System.out.println("Reference3");
first = third+1;
}
else if(array0Through999[third] == findThis3){
//System.out.println("Reference4");
break;
}
else{
//System.out.println("Reference5");
last = third-1;
}
int calc = last - first;
third = first + (calc/3);
}//end while
loopTotal3 = loopTotal3 + loop3;
}//end for
int loopAverage3 = loopTotal3 / 1000;
System.out.println("The average number of times for a Tertiary Search is: " + loopAverage3);
}
}
It has been a while since I posted this question but I finally got around to solving my issue. Here is the correct code for anyone who may stumble upon this.
edit: The array includes the "..." to make this not obnoxious to read or put out onto the screen. I had all 0-999 within my array hard coded.

can someone explain the steps to compute this equation? Java

Write a program that computes the following equation.
100/1+99/2+98/3+97/4+96/5...3/98+2/99+1/100
I am not asking for a solution. Yes this is a homework problem, but I am not here to copy paste the answers. I asked my professor to explain the problem or how should I approach this problem? She said "I can't tell you anything."
public static void main(String[] args){
int i;
for(i = 100; i >= 1; i--)
{
int result = i/j;
j = j+1;
System.out.println(result);
}
}
You can try to observe a "trend" or "pattern" when solving questions of this type.
Given: 100/1+99/2+98/3+97/4+96/5...3/98+2/99+1/100
We derived: Numerator/Denominator, let's call it n divide by d (n/d)
Pattern Observed:
n - 1 after every loop
d + 1 after every loop
So, if you have 100 numbers, you need to loop 100 times. Thus using a for-loop which loops 100 times will seemed appropriate:
for(int n=0; n<100; n++) //A loop which loops 100 times from 0 - 100
To let n start with 100, we change the loop a little to let n start from 100 instead of 0:
for(int n=100; n>0; n--) //A loop which loops 100 times from 100 - 0
You settled n, now d needs to start from 1.
int d = 1; //declare outside the loop
Putting everything together, you get:
int d = 1;
double result = 0.0;
for (int n=100; n>0; x--)
{
result += (double)n/d; //Cast either n or d to double, to prevent loss of precision
d ++; //add 1 to d after every loop
}
You are on the right track. You need to loop like you've done, but then you need to SUM up all the results. In your example you can try:
result = result + i/j;
or
result += i/j;
Note that the declaration of result needs to be outside the loop otherwise you are always initializing it.
Also think about the division (hint), you are dividing integers...
What you have is a series.
There is more than one way to define a series, but all things being the same it's more intuitive to have the index of a series increase rather than decrease.
In this case, you could use i from 0 to 99.
Which in java can be:
double sum = 0;
for (int i = 0; i < 100; i++) {
sum += (100 - i) / (double) (1 + i);
}
if you want the result in the same format then do :
int j = 100;
double sum=0;
for (int i = 1; i <= 100; i++) {
sum += ((double) j / i); // typecast as least one of i or j to double.
System.out.print(j + "/" + i+"+");
j--;
}
// here print the sum

Using java to find Happy Numbers: Nested while loop loops indefinitely

My assignment asks for a command-line input to be put through nested while loops to find if a number is a happy number or not. So far I have this:
int i = 0;
int sum = 0;
int dig2, dig1, dig3, dig4, dig1next, dig2next, dig3next;
int digit1sum, digit2sum, digit3sum;
happyNumber = number;
while (i < 500){
while (happyNumber > 0){
while (sum!=1){
dig3 = happyNumber / 100;
dig2 = happyNumber % 10;
dig1 = happyNumber / 10;
dig2next = dig2 % 10;
dig1next = dig1 % 10;
dig3next = dig3 % 10;
digit1sum = dig1next * dig1next;
digit2sum = dig2next * dig2next;
digit3sum = dig3next * dig3next;
sum = digit1sum + digit2sum + digit3sum;
happyNumber = sum;
}
System.out.println("It is a happy number.");
System.exit(0);
}
i++;
System.out.println(i);
System.exit(0);
}
I set i<500 so when i++ reaches 500, the loop should stop. I've pretty much tried putting i++ in every section of the code possible, it never works. what am i doing wrong here?
also: i am not allowed to use for loops or do-while loops on this assignment. i have to use nested while loops only
Happy number: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1(how long the loop will be: 500).
After a quick glance at your code:
while (sum!=1)
....
sum = digit1sum + digit2sum + digit3sum;
happyNumber = sum;
This while test is likely to be always true -> infinite loop -> stack overflow
You will never get out of your innermost while-loop in case of a number that loops endlessly (it is by no means stopped by the 500- limit and your logic is wrong here).
Secondly, something to think about:
digit1sum = dig1next*dig1next;
digit2sum = dig2next*dig2next;
digit3sum = dig3next*dig3next;
these (digitxsum) will always be positive.
sum = digit1sum + digit2sum + digit3sum;
sum will therefore always be positive
happyNumber = sum;
happynumber will always be positive
while (happyNumber > 0)
what is this for?

Java program terminating without error?

I'm trying to make a program that finds the largest palindrome that is a product of two 3-digit numbers. This is what I have right now (I am new to programming):
int num1 = 0;
int num2 = 0;
int product = 0;
int tempProd1 = 0;
int tempProd2 = 0;
int tempProd3 = 0;
int tempProd4 = 0;
int tempProd5 = 0;
int tempProd6 = 0;
String prodCheck1 = "";
String prodCheck2 = "";
while (num1 < 1000){
while (num2 < 1000){
product = num1 * num2;
prodCheck1 = Integer.toString(product);
tempProd1 = product % 10;
product = product / 10;
tempProd2 = product % 10;
product = product / 10;
tempProd3 = product % 10;
product = product / 10;
tempProd4 = product % 10;
product = product / 10;
tempProd5 = product % 10;
product = product / 10;
tempProd6 = product % 10;
product = product / 10;
prodCheck2 = "tempProd1" + "tempProd2" + "tempProd3" + "tempProd4" + "tempProd5" + "tempProd6";
if (prodCheck1 == prodCheck2){
System.out.println(prodCheck1);
}
num2++;
}
num1++;
}
Thing is, every time I try to run it, it terminates without an error. Could someone explain what I'm doing wrong?
Edit: Thanks everyone, finally fixed it. The answer is 853358, if anyone was wondering.
Edit: Actually, the number was 906609.
One thing I noticed immediately is that after the first iteration of the inner loop, num2 is 1000 and so the inner loop will just do nothing in the remaining 999 iterations of the outer loop. You have to reset num2 to 0.
Also consider using "for" loops instead; they're designed to prevent this kind of mistake:
for (int num1=0; num1<1000; num1++) {
...
}
Another problem is that the palindrome check is wrong. You cannot compare Strings with == (it tests for object identity, not string equality -- you'd have to use equals() instead). But even that is wrong because prodCheck2 is "tempProd1tempProd2..." and doesn't contain the actual numbers. The easiest way to check for a palindrome would be:
if (tempProd1 == tempProd6 && tempProd2 == tempProd5 && tempProd3 == tempProd$) {
...
}
Equals method for strings
There are several issues here. First == should not be used to compare strings. You should use string.equals(otherString);
Contatinating words
Second you appear to be combining words when you want to combine values
prodCheck2 = "tempProd1" + "tempProd2" + "tempProd3" + "tempProd4" + "tempProd5" + "tempProd6;
will give
prodCheck2 = "tempProd1tempProd2tempProd3tempProd4tempProd5tempProd6";
always. The fact that those words happen to have the same name as some of your variables makes no difference to java.
There are many better ways to concatenate integers. But the easiest is probably as follows
prodCheck2 = tempProd1 + "" + tempProd2 + "" +tempProd3 + "" +tempProd4 + "" +tempProd5 + "" +tempProd6";
Using while when for would be better
while (num1 < 1000){
while (num2 < 1000){
......
num2++;
}
num1++;
}
This code never decreases num2, which means num2 goes 1->1000 for num1=0 and then stays at 1000 from then on. I'm guessing this isn't what you want. We could fix the while loop but really this is what a for loop is for
for(int num1=0;num1<1000;num1++){
for(int num2=0;num2<1000;num2++){
//code as before, no need to inciment or reset num1 or num2 inside the loop
}
}
Issues that don't break your code
You're declaring all your variables with very large scope. For example tempProd1 is declared outside all the loops depite only being needed inside the inner loop. Declare variables in the smallest scope possible. This will catch bugs like those we've found here. Critically num2 couldn't have accidently been made non resetting if you'd delared it within the first loop
if (prodCheck1 == prodCheck2){
System.out.println(prodCheck1);
}
is a comparison that is based solely on the identity equality of prodCheck1 and prodCheck2. Rewrite that code as:
if (prodCheck1.equals()){
System.out.println(prodCheck1);
}
to use value equality that will return true for identical strings.

Categories