It's just supposed to print the prime numbers below 100 but it only gets the number '3' as an output. I'm only just starting to learn Java so it all looks right to me.
public class ClassesAndObjects {
public static void main(String[] args) {
Prime n = new Prime();
for (int i = 3; i < 100; i++){
n.Number = i;
n.factors();
}
}
}
class Prime{
long Number;
long fact;
boolean state = true;
void factors(){
for (fact = 2; fact < Number; fact++){
if (fact != Number){
if (Number % fact == 0){
state = false;
break;
}
}
}
if (state == true){
System.out.println(Number);
}
}
}
You have to reset the boolean state to true at the beginning of each call, otherwise it's always false except for the first call (when i =3 )
void factors(){
state = true;
for (fact = 2; fact < Number; fact++){
if (fact != Number){
if (Number % fact == 0){
state = false;
break;
}
}
}
if (state == true){
System.out.println(Number);
}
}
Add a statement like this:
if (state == true){
System.out.println(Number);
}
state = true; //reset the state variable
Here we are resetting the state variable to true for next iteration.
Well, you dont have state = true as default in your factor() method. So when it runs state = false for the first time (happens when Number = 4), then it is always false. Just add the bolded line in your code and you are good to go.
void factors(){
**boolean state = true;**
for (fact = 2; fact < Number; fact++){
if (fact != Number){
if (Number % fact == 0){
state = false;
break;
}
}
}
if (state == true){
System.out.println(Number);
}
}
Related
Im having trouble with my isUnique method. Either I'm making a logical error or a syntax error, or both. I have to make sure that every user input I get is Unique. Everything else I have done is correct but that method. I was using the debugger and I've noticed that the "number" doesn't change as the user input changes but I am new and kinda lost. Assigment: Enter 5 numbers and test for validity and uniqueness. If not valid do not count towards 5 numbers. If not unique count towards 5 numbers but count number of unique and print "not unique" if not unique.
import java.util.Scanner;
public class Assignment4Part2 {
public static void main(String[] args) {
int[] numbers = new int[5];
System.out.println("Enter an integer (50-100): ");
Scanner input = new Scanner(System.in);
int uniqueCount = 0;
for (int i = 0; i < numbers.length;) {
{
numbers[i] = input.nextInt();
if (isValid(numbers[i]) == true) {
i++;
if (isUnique(numbers, numbers[i]) == true) {
uniqueCount++;
System.out.printf("Unique so far: %d ", uniqueCount);
}
if (isUnique(numbers, numbers[i]) == false) {
System.out.println("That's not unique.\n");
}
}
}
}
for (int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i] + " ");
}
}
public static boolean isValid(int array) {
if (array <= 100 & array >= 50) {
return true;
} else {
System.out.println(" ***Invalid Number\n");
return false;
}
}
public static boolean isUnique(int[] array, int numbers) {
for (int i = 0; i < array.length; i++) {
if (array[i] == numbers) {
return false;
} else {
return true;
}
}
return false;
}
}
some things i notice:
for (int i = 0; i < numbers.length;) {
{
numbers[i] = input.nextInt();
if (isValid(numbers[i]) == true) {
//i++; // in case you increment here, you do it before is unqique is true... so next isUnique is of an emtpy (null) numbers[i]
if (isUnique(numbers, numbers[i]) == true) {
uniqueCount++;
System.out.printf("Unique so far: %d ", uniqueCount);
//continue here
i++;
}// why not an else?
//if (isUnique(numbers, numbers[i]) == false) {
else {
System.out.println("That's not unique.\n");
}
}
}
}
and the is unique....
public static boolean isUnique(int[] array, int numbers) {
// here the given number is already in the array, so never unique....
// this will always return false, because the input is already in the array
for (int i = 0; i < array.length; i++) {
if (array[i] == numbers) {
return false;
} else {
return true;
}
}
return false;
}
so use:
for (int i = 0; i < numbers.length;) {
{
// use a temp value before putting it in the array
int input = input.nextInt();
if (isValid(input) == true) {
//i++; // in case you increment here, you do it before is unqique is true... so next isUnique is of an emtpy (null) numbers[i]
if (isUnique(numbers, input) == true) {
uniqueCount++;
numbers[i] = input
System.out.printf("Unique so far: %d ", uniqueCount);
//continue here
i++;
}// why not an else?
//if (isUnique(numbers, numbers[i]) == false) {
else {
System.out.println("That's not unique.\n");
}
}
}
}
and in the is unique function....
if (array[i] == numbers) {
while not all numbers are filled in... this compares:
if(null == numbers){
so will be shorter to add in front:
if(array[i]==null){
break;
}
because the rest is still empty
The error is in the for in your method isUnique, during the first iteration you compare your the given number with the first value and if they dont match you already return true so the loop can't check any of the remaining numbers.
Just remove the else parte in that if and change the last return out of the loop to a true instead of false.
This way only until you checked the the whole array you will be sure the number is unique.
I would also sugest you send to that methis uniqueCount so you dont check the whole array, but just the amount of numbers already registered.
I'm trying to compare two BigInts that were manually created and did not use the built-in BigInt class. Right now I'm getting hung up trying to be able to determine how to find the bigger number of the 2. For example if I want to find which number is bigger between 123 and 134, and I pass in both BigInts I want to return a false if 123 is the first number passed or True if the second number is passed. Please see the code below:
private boolean thisBigIntGreaterThanOrEqualToOther(BigInt b1, BigInt b2){
boolean value = true;
if(b1.bigInt.size() >= b2.bigInt.size()){
for(int i = 0; i < b2.bigInt.size(); i++){
if(b1.bigInt.get(i) >= b2.bigInt.get(i)){
value = true;
}
else{
value = false;
}
}
}
else{
value = false;
}
return value;
}
As you can see in my code I thought about trying to compare each digit, but I run into an issue when I get to 1's for each number, it sets the value to true.
BigInt Class Below:
public class BigInt {
//Instance variables for the class, a boolean for the sign and an ArrayList to store the input String
private boolean pos = true;
private ArrayList<Integer> bigInt = new ArrayList<Integer>();
//No argument constructor, creates a big integer of value zero
public BigInt () {
this.pos = true;
}
//Constructor for big integers input as int
public BigInt (int newBigInt) {
String inputInt = Integer.toString(newBigInt);
inputInt = handleSign(inputInt);
inputInt = checkNumber(inputInt);
for(int i = inputInt.length() - 1; i >=0; i--) {
bigInt.add(Integer.parseInt(inputInt.substring(i, i+1)));
}
}
//Constructor for big integers input as strings
public BigInt (String newBigInt) {
newBigInt = handleSign(newBigInt);
newBigInt = checkNumber(newBigInt);
for(int i = newBigInt.length() - 1; i >=0; i--) {
bigInt.add(Integer.parseInt(newBigInt.substring(i, i+1)));
}
}
private String handleSign(String num) {
if(num.charAt(0) == '+' || num.charAt(0) == '-') {
if(num.length() == 1) {
throw new ErrorMessage("Invalid value: sign only, no integer.");
}
if(num.charAt(0) == '-') {
this.pos = false;
}
else {
this.pos = true;
}
num = num.substring(1);
}
return num;
}
// Private method to remove leading zeros from add/subtract methods
private BigInt removeZeros(BigInt result){
for(int i = 0; i < result.bigInt.size(); i++){
if(result.bigInt.get(i) == 0){
result.bigInt.remove(i);
}
}
return result;
}
//Private method to check the number; remove leading zeros and check for leading spaces (throw error message)
private String checkNumber(String num) {
if(num.charAt(0) == ' ') {
throw new ErrorMessage("Invalid value: leading blank space.");
}
if(num.charAt(0) == '0'){
while(num.length() > 1 && num.charAt(0) == '0') {
num = num.substring(1);
}
}
return num;
}
//toString method
public String toString() {
String answer = "";
for(int i = bigInt.size() - 1; i >=0; i--) {
answer = answer + bigInt.get(i);
}
if(this.pos == false){
return "-" + answer;
}
return answer;
The method to compare two BigInts is broken in several ways:
1. You iterate in the wrong direction:
for(int i = 0; i < b2.bigInt.size(); i++)
You start from the least significant digit which means 20 would be considered smaller than 11. Change it to
for(int i = b2.bigInt.size() - 1; i >= 0 ; i--)
2. You override the result of the comparison
If your code reaches the point where it sets value = false; it does not return or exit the loop. That means that in the next iteration the value gets overriden. That means suddenly 13 and 23 are considered equal.
BigInt c = new BigInt("13");
BigInt d = new BigInt("23");
System.out.println(BigInt.thisBigIntGreaterThanOrEqualToOther(c, d));
System.out.println(BigInt.thisBigIntGreaterThanOrEqualToOther(d, c));
The output is
true
true
Change value = false; to return false;
3. You do not check whether b1.bigInt.size() > b2.bigInt.size()
This results in your method returning that 131 is smaller than 23.
Change your code in the following way:
if(b1.bigInt.size() > b2.bigInt.size()){
return true;
} else if(b1.bigInt.size() < b2.bigInt.size()){
return false;
} else {
// the other comparison code
}
Some final remarks:
It is good design to implement the Comparable interface as it allows you to use many library methods with your class.
EDIT: code now does not use library functions anymore
public class BigInt implements Comparable<BigInt> {
...
#Override
public int compareTo(BigInt other) {
int c = this.bigInt.size() - other.bigInt.size();
if (c != 0) {
return c;
} else {
for (int i = this.bigInt.size() - 1; i >= 0; i--) {
c = this.bigInt.get(i) - other.bigInt.get(i);
if (c != 0) {
return c;
}
}
return 0;
}
}
}
So here's my code, I want the output to be like this:
Given two numbers, is the second input a multiple of the first?
For Example:
Input:
3
6
Output:
true
public boolean multiple(int m, int n){
int i = 0;
int j = 0;
boolean check = true;
if(n%m == 0){
i++;
return check;
}
else{
j++;
return false;
}
}
When I try it I get an error, I think it's because the return statement is within the if and else statements.
The code is perfectly fine .. Error must be Somewhere else
public class Test1 {
public static void main(String[] args) {
System.out.println(multiple(3, 9));
}
public static boolean multiple(int m, int n){
int i = 0;
int j = 0;
boolean check = true;
if(n%m == 0){
i++;
return check;
}
else{
j++;
return false;
}
}
}
Output
true
here is output see IDEONE
The easiest way is to return the result of your if statement.
return n % m == 0;
I'm not sure what i/j are doing. You don't use them except to increment, but they are local to the function and get GC'd after the return. What you have now is basically this:
boolean bool = some_calculation();
if (bool == true)
{
return true;
}
else
{
return false;
}
I've come across a problem. I'm trying to make a class which takes the maximum number that a user puts in and adds the integer before it until it gets to 0, however, when I run it, the numbers get larger and larger until it crashes. What seems to be throwing this into an infinite loop?
public class Summation {
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Debug? (Y/N): ");
char debug = console.readChar();
if ((debug!='Y')&&(debug!='N')){
System.out.println("Please enter Y or N");
main(null);
}
else{
System.out.print("Enter max range:");
int max = console.readInt();
int s = sum(max,debug);
System.out.print(s);
}
}
public static int sum(int m, char d){
int sm = 1;
boolean isRunning = true;
while ((isRunning == true)&&(d=='Y')){
if ((--m)==0) {
isRunning = false;
}
else{
sm = m+(--m);
System.out.println("sm is"+sm);
}
while ((isRunning == true)&&(d=='N')){
if ((--m)==0) {
isRunning = false;
}
else{
sm = m+(--m);
}
}
}return sm;
}
}
There's a scenario where your condition for exit
if ((--m)==0)
will never again be reached, because m is already less than 0, and it's never going back.
that scenario is whenever m is an even number.
while ((isRunning == true)&&(d=='Y'))
{
// this condition decriments `m` every time it runs, regardless of whether it evaluates to true
if ((--m)==0)
{
// if `m` was set to 0 on your last iteration, it will be set to -1
isRunning = false;
}
else
{
// if m is 1 before this line it will be 0 after it.
sm = m+(--m);
System.out.println("sm is"+sm);
}
while ((isRunning == true)&&(d=='N'))
{
// this code will never get executed
}
}
return sm;
Answer to your problem is very simple
Just modify the condition
if (m==0) {
isRunning = false;
}
When you are checking --m == 0, it is very much possible that m will be jumping over 0 and will enter negative territory without even setting this condition to be true.
Everything you are doing is wrong :).
First - FORMATTING. You maybe even dont know that, but the second while is INSIDE the first while cycle. If you use netbeans, its ALT+SHIFT+F.
The using of --m is not good for your example, cause it firsts decrease the "m" value and then it compares. So even when you asking at
(--m)==0
you decrease a value. And because you are using it again at
sm = m+(--m)
you can even skip the "0" value and get into negative numbers.
However if you want only "add numbers in reverse order from given number to 0 in while loop" it is not fibonacci and you can use this code (it could be done better, but this is using your code) :
public class Summation {
public static void main(String[] args) {
System.out.println(sum(10, 'Y'));
}
public static int sum(int m, char d) {
int sm = 0;
boolean isRunning = true;
while ((isRunning == true) && (d == 'Y')) {
sm += m;
if (m == 0) {
isRunning = false;
} else {
m--;
System.out.println("sm is" + sm);
}
while ((isRunning == true) && (d == 'N')) {
if ((--m) == 0) {
isRunning = false;
} else {
sm = m + (--m);
}
}
}
return sm;
}
}
Note that second while cycle couldnt be reached - it passes only when "d == Y" and then it starts only when "d == N"
I am trying to make a cee-lo program in simple, simple java. I'm just learning. However when I get to my instant w. (i have simplified it for the test) it just always returns false. I can't seem to figure out why. It even displays the correct data but when it compares it it fails.
public class ceeLo
{
public static void main (String [] args)
{
Scanner scan= new Scanner (System.in);
int [] die = new int [3];
int answer;
boolean roll = true;
boolean qualifed;
boolean instantW;
boolean instantL;
do
{
System.out.println("Roll the dice?");
answer = scan.nextInt ();
if (answer == 0)
roll= false;
else
{
int i;
for (i = 0; i < die.length; i++)
{
die[i]= rollin();
System.out.println(diceTxt(die[i]));
}
qualifed = (qualify (die));
System.out.println("Qualified = " + qualifed);
instantW = (easyW (die));
System.out.println("Instant win = " + instantW);
}
}
while (roll);
}
// Generate random numbers for the roll
public static int rollin ()
{
Random rand = new Random();
int die= rand.nextInt(6);
return die;
}
//Check if dice qualify with pair
public static boolean qualify (int [] die)
{
boolean qualify;
//Pair Qualifying roll
if (die[0] == die[1] || die[0] == die[2] || die[1] == die[2])
qualify = true;
else
qualify = false;
return qualify;
}
//Check if instant win
public static boolean easyW (int [] die)
{
boolean instantW;
// show contents of die [x] for testing
System.out.println (die[0] + "" + die[1] + "" + die[2]);
if (die[0] > 2 && die [1] > 2 && die[2] > 2)
instantW = true;
else;
instantW = false;
return instantW;
}
}
Remove semi-colon after else; it should be just else
I guess the reason is,
instantW = false; is being treated as separate statement not part of else block. Which is why instantW is always being assigned to false and returning false.
It is always better to use {} to define block even though they are single liners. It is my preference.
As Greg Hewgill suggested, using single statement instantW = die[0] > 2 && die [1] > 2 && die[2] > 2; would do good than if/else.
A better way to write boolean methods is really to do something like
boolean easyW(int[] die)
{
return (die[0] > 2 && die[1] > 2 && die[2] > 2);
}
Or even better (more general)
boolean easyW(int[] die)
{
for(int roll : die)
{
if(roll < 2)
{
return false;
}
}
return true;
}
But in your case, you have a ; after your else. Fixed version:
public static boolean easyW (int [] die)
{
boolean instantW;
// show contents of die [x] for testing
System.out.println (die[0] + "" + die[1] + "" + die[2]);
if (die[0] > 2 && die [1] > 2 && die[2] > 2)
instantW = true;
else
instantW = false;
return instantW;
}