While/if Loop is not working in class - class

I'm learning java and I'm having an issue with my if code not running.
In the following code I'm trying to determine if a number (variable num) is a triangle number (1,3, 6, 10 etc). The code should run through and give the "Is Triangle". However it keeps spitting out Null.
I understand this is not the most effective way to do this code, but I am trying to learn how to use Classes.
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 45;
int tri = 0;
int triplus = 0;
String triresult;
public String triangle() {
while (tri < num) {
if (tri == num) {
triresult = "Is a Triangle";
System.out.println("Is a Triangle");
} else if (tri + (triplus + 1) > num){
triresult = "Is Not a Triangle";
} else {
triplus++;
tri = tri + triplus;
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Thanks for any help provided.

Try this code :
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 10;//Try other numbers
int tri = 0;
int triplus = 0;
int res = 0;
String triresult = "Is Not a Triangle";
int[] tab= new int[num];
public String triangle() {
//to calculate the triangle numbers
for(int i = 0; i<num; i++){
res = res + i;
tab[i]=res;
}
//To check if num is a triangle or not
for(int i = 0; i<tab.length; i++){
System.out.println(">> " + i + " : " + tab[i]);
if(tab[i]== num){
triresult = num + " Is a Triangle";
break;//Quit if the condition is checked
}else{
triresult = num + " Is Not a Triangle";
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Hope this Helps.

Step through the loop carefully. You'll probably see that there is a case where
(tri < num)
fails, and thus you fall out of the loop, while
(tri == num)
and
(tri + (triplus + 1) > num)
both fail too, so no text gets set before you fall out.
You probably want to do your if-tests within the method on just tri, not a modification of tri, so as to reduce your own confusion about how the code is working.

Related

Eclipse: The selection cannot be launched, and there are no recent launches

So, I know that there are many people with this problem and many questions about it, but I just couldn't fin a solution for this, every other thing I try to execute works, but this doesn't and I can't figure out why...
package prob3;
public class LargestPrimeFactor {
double num = 600851475143D;
double LargestPrimeFactor;
public void getLargestPrimeFactor(String [] args){
double prevPrimeFactor = 0;
do {
for(double i = 0; i < num/2; i++){
if((num % i == 0) && (num / i != 1)){
prevPrimeFactor = num;
LargestPrimeFactor = num / i;
} else {
continue;
}
}
} while(prevPrimeFactor != LargestPrimeFactor);
System.out.println("The biggest prime factor of " + num + " is " + LargestPrimeFactor);
}
}
you should define a main function to run your program. Something like:
public static void main(String[] args) {
getLargestPrimeFactor(args);
}

mergsort printing a strange result

I am having an issue with my merge sort, when I print out my sortedArray it only returns [ 0.0, 0.0.....] Im not sure if there is an error in my sort code or in my print line or if it has to do with doubles. The code I am us posted below.
By calling System.out.println(toString(sortedArray) I get an even more obscure answer.
Thanks for any help.
package mergesort;
import java.util.Arrays;
import java.util.Random;
public class mergesort {
public static void main(String[] args) {
double[] array = getIntArray();
long before = System.nanoTime();
double[] sortedArray= mergeSort(array);
System.out.println("Sorting took "+ (System.nanoTime() - before) +" nanoseconds ");
System.out.println(toString(array) + "\n\n" + toString(sortedArray) + "\n main method completed in: " + (System.nanoTime() - before) + " nanoseconds.");
}
private static String toString(double[] array) {
StringBuilder sb = new StringBuilder("[ ");
double len = array.length;
for(int i = 0; i < len - 1; i++) {
sb.append(array[i] + ", ");
}
sb.append(array[(int) (len - 1)] + " ]");
return sb.toString();
}
public static double[] mergeSort(double[] array) {
if (array.length <= 1) {
return array;
}
int half = array.length / 2;
return merge(mergeSort(Arrays.copyOfRange(array, 0, half)),
mergeSort(Arrays.copyOfRange(array, half, array.length)));
}
private static double[] merge(double[] ds, double[] ds2) {
int len1 = ds.length, len2 = ds2.length;
int totalLength = len1 + len2;
double[] result = new double[totalLength];
int counterForLeft =0,counterForRight=0,resultIndex=0;
while(counterForLeft<len1 || counterForRight < len2){
if(counterForLeft<len1 && counterForRight < len2){
if(ds[counterForLeft]<= ds2[counterForRight]){
result[resultIndex++] =(int) ds[counterForLeft++];
} else {
result[resultIndex++] =(int) ds2[counterForRight++];
}
}else if(counterForLeft<len1){
result[resultIndex++] = (int) ds[counterForLeft++];
}else if (counterForRight <len2){
result[resultIndex++] =(int) ds2[counterForRight++];
}
}
return result;
}
private static double[] getIntArray() {
double[] array = new double[10000];
Random random = new Random();
for(int i = 0; i < 10000; i++) {
array[i] = (random.nextDouble() * .99999);
}
return array;
}
}
In the merge method, when copying from one of the input arrays to the results, you cast to int. For example:
result[resultIndex++] =(int) ds[counterForLeft++];
All your doubles are in the range [0...1), so the result of casting any of them to int is zero. Just get rid of those casts, and you will keep your numbers in the merge result.
As an additional tip, it is much easier to debug small problems than large ones. It failed for any size greater than 2, so you should have been debugging with size 2, not 10000.

issue in my if statement to make comparison in my java program

any help please, so i already wrote the prog but my if statement in my for loop is not working. the prog need to generate 6 random nos,then apply bubble sort which i already did.then the user must enter 6 numbers and these numbers must be compared against the random numbers and must say whether numbers are found in the random numbers or not. here's the code. something is wrong with the if statement ` public static void main(String[] args) {
try {
int numbers[] = new int[6]; //random numbers will be stored in new array
//2 loop will be created to avoid duplication of numbers
System.out.println("Array before Bubble sort");
for (int i = 0; i < 6; i++) {
numbers[i] = (int) (Math.random() * 40);
if (i > 0) {
for (int b = 0; b < i; b++) { //
if (numbers[b] == numbers[i]) {
i--; //decrement to continue the for loop if the integer has been repeated
}
}
}
System.out.print(numbers[i] + ","); //random numbers will be printed before using sorting bubble sort
}
//sort an array using bubble sort
bubbleSort(numbers);
System.out.println(" \nArray after bubble sort");
for (int i = 0; i < 6; i++) {
System.out.print(numbers[i] + ",");
}
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\ninput 6 number between 1 and 40");
int inputNumber = Integer.parseInt(input.readLine());
for (int b = 0; b < 6; b++) {
System.out.println("number:");
int outcome=Integer.parseInt(input.readLine());
if(outcome==numbers){
System.out.println("found in random numbers");
}else{
System.out.println("not found in random numbers");
}
}
} catch (Exception e) {
System.out.println("error");
}
}
public static void bubbleSort(int[] numbers) {
int n = numbers.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numbers[j - 1] > numbers[j]) { //swap the element
temp = numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = temp;
}
}
}
}
}`
System.out.println("\ninput 6 number between 1 and 40");
//Scanner is specifically designed for getting an input purpose and introduced in Java 5,so better use it
Scanner s = new Scanner(System.in);
//you need to have nested loop here
//But the best way to search is use binary search,as you have already sorted the array
while (s.hasNextInt()) {
//one at a time from the input is put to outcome
int outcome = s.nextInt();
boolean found = false;
for (int b = 0; b < 6; b++) {
found = false;
if (outcome == numbers[b]) {
found = true;
//remember to break the inner loop if a match is found
break;
} else {
found = false;
}
}
if (found == true) {
System.out.println("found in random numbers");
} else {
System.out.println("not found in random numbers");
}

User input with linear and binary searching in java

I'm trying to write a program that asks the user to input the size of the array the user wants to create, and then asks the user to fill the array with elements, and then it should display the array with its elements and, ask the user to conduct a search for an integer. It should conduct a linear and binary search, while displaying how many probes it took to determine is the element is in the array. So far the only output i have gotten is that the element has not been found. If you could look at my code and see what the problem is, because i have tried for hours and i have changed everything i can think of. Any help would be greatly appreciated.
import java.util.Scanner;
public class Searching
{
public static int[] anArray = new int[100];
private int numberOfElements;
public int arraySize = numberOfElements;
public String linearSearch(int value)
{
int count = 0;
boolean valueInArray = false;
String indexOfValue = "";
System.out.print("The Value was Found in: ");
for(int i = 0; i < arraySize; i++)
{
if(anArray[i] == value)
{
valueInArray = true;
System.out.print(i + " ");
indexOfValue += i + " ";
}
count ++;
}
if(!valueInArray)
{
indexOfValue = " None found";
System.out.print(indexOfValue);
}
System.out.println("\nIt took " + count + " probes with a linear search to find");
return indexOfValue;
}
public void binarySearch(int value)
{
int min = 0;
int max = arraySize - 1;
int count = 0;
while(min <= max)
{
int mid = (max + min) / 2;
if(anArray[mid] < value) min = mid + 1;
else if(anArray[mid] > value) max = mid - 1;
else
{
System.out.println("\nFound a Match for " + value + " at Index " + mid);
min = max + 1;
}
count ++;
}
System.out.println("It took " + count + " probes with a binary search to find");
}
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.println("Input the number of elements in your Array");
int numberOfElements = scan.nextInt();
if(numberOfElements <= 0)
{
System.exit(0);
}
int[] anArray = new int[numberOfElements];
System.out.println("\nEnter " + numberOfElements + " Integers");
for(int i = 0; i < anArray.length; i ++)
{
System.out.println("Int # " + (i + 1) + ": ");
anArray[i] = scan.nextInt();
}
System.out.println("\nThe integers you entered are: ");
for(int i = 0; i < anArray.length; i ++) // for loop used to print out each element on a different line
{
System.out.println(anArray[i]);
}
System.out.println("Which element would you like to find?");
int value = scan.nextInt();
Wee3Q2JOSHBALBOA newArray = new Wee3Q2JOSHBALBOA();
newArray.linearSearch(3);
newArray.binarySearch(value);
}
}
hmm I am not sure you are using an array the correct way, you see an Array is a set size and I dont think you can expand like they way you are doing...
Instead try setting the size of the array to certain length.
Or use vectors

Fibonacci Sequence error

I am coding a Fibonacci sequence in Eclipse and this is my code-
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
It is showing an error in the return value; line saying value cannot be resolved to a variable. I don't see any other errors.
Where is value defined? You return something that was not defined anywhere.
You don't have a "value" defined, this is your error. I don't remember the thing exactly, but I think you don't need a and b, I found this in my code archive, hope it helps.
public class Fibonacci
{
public static long fibo(int n)
{
if (n <= 1) return n;
else return fibo(n - 1) + fibo(n - 2);
}
public static void main() {
int count = 5; // change accordingly, bind to input etc.
int N = Integer.parseInt(count);
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fibo(i));
}
}
In case you want to stay with your own code, try returning "b" as value.
Your method is returning an int variable so you would have to define and return value as an int
I am not sure what you trying to do.
If you have "getValue" method I think "increment" method should be void.
When you want current Fibonacci value use "getValue" method.
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public void increment() {
int temp = b;
b = a + b;
a = temp;
}
public int getValue() {
return b;
}