I'm new to programming, I'm not sure where I'm going wrong with this one.
Here is my main method:
import java.util.*;
public class DisplayFactors
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter a integer: ");
String input1 = scan.nextLine();
int input = Integer.parseInt(input1);
FactorGenerator factor = new FactorGenerator(input);
System.out.print(factor.getNextFactor());
while (!factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
}
}
Here is my class:
public class FactorGenerator {
private int num;
private int nextFactor;
public FactorGenerator(int n)
{
num = nextFactor = n;
}
public int getNextFactor()
{
int i = nextFactor - 1 ;
while ((num % i) != 0)
{
i--;
}
nextFactor = i;
return i;
}
public boolean hasMoreFactors()
{
if (nextFactor == 1)
{
return false;
}
else
{
return true;
}
}
}
Currently if I enter 15 as the integer I only get one factor back, which is 5, but I need it to display all the factors: 15, 5, 3 and 1. Where am I going wrong?
When you use
while (!factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
you say that while there aren't any more factors, print them on the screen, but you need
to print the factors as long as they exist in the list.
So in Java you will have:
while (factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
while (!factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
must be
while (factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
Related
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 2 years ago.
Improve this question
Question:
Write a Number class that can be used to determine if a number is odd, even, or
perfect. Then, use this Number class to determine how many numbers in the list are odd, even, and perfect.
Number Class:
public class Number
{
private Integer number;
public Number(int n)
{
number=n;
}
public boolean isEven()
{
if(number % 2 == 0)
return true;
else
return false;
}
public boolean isOdd()
{
if(number % 2 != 0)
return true;
else
return false;
}
public boolean isPerfect()
{
int count = 0;
for(int i = 1; i<number; i++)
{
if(number % i == 0)
count += i;
}
if(number == count)
{
return true;
}
else
return false;
}
public String toString()
{
return "" +number;
}
}
My number class is running good there is no problem in my Number class. But in my number analyzer class where i find the number of odd,even and perfect.
Number Analyzer class:
public class NumberAnalyzer
{
private ArrayList<Number> list;
public NumberAnalyzer(int l)
{
list=l;
}
public int countOdds()
{
int odd = 0;
for(int i=0; i<list.size(); i++)
{
if(list.isOdd() == true)
return odd++;
}
}
public int countEvens()
{
int even = 0;
for(int x = 0; x<list.size(); x++)
{
if(list.isEven() == true)
return even++;
}
}
public int countPerfects()
{
int perfect = 0;
for(int z = 0; z<list.size(); z++)
{
if(list.isPerfect() == true)
return perfect++;
}
}
public String toString()
{
return "" + list;
}
}
Please make correction on this class so my program run perfectly. I do not understand the problem please make change in this so program work perfectly.
Runner of program:
import static java.lang.System.*;
public class Runner
{
public static void main( String args[] )
{
int[] r = {5, 12, 9, 6, 1, 4, 8, 6 };
NumberAnalyzer test = new NumberAnalyzer(r);
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
}
}
Correct answers with this Runner:
[5, 12, 9, 6, 1, 4, 8, 6]
odd count = 3
even count = 5
perfect count = 2
Thank you
I didn't understand how it could work if it even didn't complile but nevermind. You need to change 2 classes: NumberAnalyzer and Runner. Please have a look:
public class Runner {
public static void main(String args[]) {
Number[] r = {new Number(5), new Number(12), new Number(9), new Number(6),
new Number(1), new Number(4), new Number(8), new Number(6)};
NumberAnalyzer test = new NumberAnalyzer(r);
out.println(test);
out.println("odd count = " + test.countOdds());
out.println("even count = " + test.countEvens());
out.println("perfect count = " + test.countPerfects() + "\n\n\n");
}
}
and
import java.util.Arrays;
import java.util.List;
public class NumberAnalyzer {
private List<Number> list;
public NumberAnalyzer(Number[] l) {
list = Arrays.asList(l);
}
public int countOdds() {
int odd = 0;
for (Number value : list) {
if (value.isOdd() == true) {
odd++;
}
}
return odd;
}
public int countEvens() {
int even = 0;
for (Number value : list) {
if (value.isEven() == true) {
even++;
}
}
return even;
}
public int countPerfects() {
int perfect = 0;
for (Number value : list) {
if (value.isPerfect() == true) {
perfect++;
}
}
return perfect;
}
public String toString() {
return "" + list;
}
}
in that case it returns a correct output.
Your approach for resolving this problem has a lot of problems, especially in NumberAnalyzer class.
1) You should call the isOdd(), isEven() etc. on an element of the list, not on the list itself -> list.get(i).isEven()
2) The return even++ will exit the loop and return 1 if the condition is met, and the method is not even working since you don't have a return statement in case if the if statement from the for loop doesn't get executed.
3) Not a big problem, but the x and z can be declared as i too -> more intuitive ( i ndex)
4) The isPerfect() method is not correct, an easy solution to solve this problem could be using Math.sqrt() and Math.floor()
5) You're trying to pass an int[] array and the constructor expect an int. And after this, you have an ArrayList<Number> inside the NumberAnalyzer class and you're trying to assign to this list an int value.
Solutions:
1) + 2) + 3) :
public class NumberAnalyzer {
private List<Number> list; //Changed the ArrayList<> to List<>
public NumberAnalyzer(List<Number> l) {
list = l;
}
public int countOdds() {
int odd = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).isOdd())
odd++;
}
return odd;
} // SAME FOR THE OTHER METHODS.
}
4)
public boolean isPerfect()
{
int square = Math.sqrt(number);
return (square - Math.floor(square)) == 0;
}
5) The static void main method should now look like this:
Integer[] r = {5, 12, 9, 6, 1, 4, 8, 6};
List<Integer> rList = Arrays.asList(r);
List<Number> numberList = rList.stream().map(Number::new).collect(Collectors.toList());
NumberAnalyzer test = new NumberAnalyzer(numberList);
Trying Code as follows But it not working as per requirement printing 0 if armstrong number and 1 if not armstrong number
Suggest correction for implementing this program
import java.util.Scanner;
class Example {
public static boolean solution(int N) {
boolean isNumber = false;
#SuppressWarnings("unused")
int i=1;
int c=0,a,temp;
temp=N;
while(N>0) {
a=N%10;
N=N/10;
c=c+(a*a*a);
}
if(temp==c) {
i = isNumber ? 1 : 0;
}
System.out.println(isNumber);
return isNumber;
}
}
class Arm {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
int N = s.nextInt();
#SuppressWarnings("unused")
Example ex= new Example();
Example.solution(N);
}
}
#Sanjyukta you have not assigned isNumber=true if the number is armstrong, so everytime it will return false and 0 and It will not update the value of i and isNumber.
Below code will update the isNumber and i values.
if (temp == c) {
isNumber = true;
i = isNumber ? 0 : 1;
}
System.out.println(isNumber + "\t" + i);
Answer of my question: It is possible by using Ternary operator
public static void solution(int N)
{
int c=0,a,temp;
temp=N;
while(N>0)
{
a=N%10;
N=N/10;
c=c+(a*a*a);
}
if(temp == c)
{
boolean b = true;
c = (b) ? 1 : 0;
}
else
{
boolean b = false;
c = (b) ? 1 : 0;
}
System.out.println(c);
}
class Arm
{
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
int N = s.nextInt();
#SuppressWarnings("unused")
Example ex= new Example();
ex.solution(N);
}
}
I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?
How to use if else condition in searching (only using one loop and if else if condition) if array is already given e.g {12,13,14,15,16}
if user input 13 so it show it found and if user input 20 it shows not found.
My try :-
import java.util.Scanner;
/** * * #author Waseem */
public class Sear {
public static void main(String[] args) {
int index[] = {12, 13, 14, 15, 16};
Scanner a = new Scanner(System.in);
System.out.println("enter the number");
b = a.next();
for (int i = 0; i < index.length; i++) {
if (b == index[i]) {
System.out.println("found");
break;
} else
System.out.println(index[i]);
}
}
}
The problem you have in your code is that you do not have declared what a type of next is.
When you call
Scanner a = new Scanner(System.in);
System.out.println("enter the number");
b = a.next();
Method Scanner#next() by documentation result with a String type.
When you call b == index[i], you try to compare the references with value. That is not allowed operation and you will get a compile error.
To read a integer from Scanner use method nextInt(), then your program should run.
Regarding the algorithm, whenever you used a brake to control logic of your program should be a hint that this part should be moved to separate method.
Your problem can be divided in two like:
Find the number in array
Display message according to result in step one.
First we will have to write a method that will search an int in arrays of ints.
static int indexOf(int value, int[] values) {
for(int i = 0; i < value.length; i++)
if(value == values[i]) return i;
return -1;
}
The logic is simple, if a value is found then result with it index if not then result -1.
Now we can apply this method in the logic of our program.
public static void main(String[] args) {
int index[] = {12, 13, 14, 15, 16};
Scanner inputReader = new Scanner(System.in);
System.out.println("Enter the a integer:");
int value = inputReader.nextInt();
int position = indexOf(value, index);
if(position > 0) {
System.out.println("found");
} else {
System.out.println("not found");
}
}
Your method has correct logic implemented!I am unsure why are you printing the array values if the user-entered element doesn't match array element...There is no need! Also,to print NOT FOUND,you need to have a variable set for that purpose,say flag variable of type boolean in my code!
Also,what you're missing is end-braces to close the loop,main() and the class. We always have a corresponding closing brace for each respective opening brace!
try this :-
import java.util.Scanner;
/**
* #author Waseem
*/
public class Sear {
public static void main(String[] args) {
int index[] = {12, 13, 14, 15, 16};
boolean flag = false;
Scanner a = new Scanner(System.in);
System.out.println("enter the number");
int b = a.nextInt();
for (int i : index) {
if (flag = b == i) {
break;
} else {
System.out.println(i); // No need for this,but,even then this is fine!
}
} // to close for-loop
if (flag) {
System.out.println("Number Found");
} else {
System.out.println("Number not Found!!!");
}
} // to close main() method
} /// to close class Sear
import java.util.Scanner;
/**
* #author Davide
*/
public class test {
public static void main(String[] args) {
int index[] = {12, 13, 14, 15, 16};
Scanner a = new Scanner(System.in);
System.out.println("enter the number");
int b = a.nextInt();
// one if and else
if (find(index, 0, b)) {
System.out.println("Number Found");
} else {
System.out.println("Number not Found!!!");
}
}
// one loop
public static boolean find(int[] array, int index, int value) {
return index < array.length && (array[index] == value || find(array, ++index, value));
}
}
You got one for-each loop and one if statement
public String findInArray(int[] arrValues, int userInput){
for(int element : arrValues) {
if(element == userInput) {
return "it found";
}
}
return "not found";
}
import java.util.Scanner;
public class Ifelse {
public static void main(String[] args) {
int[] a={12,13,14,15,16};
int b;
for(int i=1;i<=a.length;i++)
{
Scanner input = new Scanner(System.in);
System.out.println("Input Number");
b = input.nextInt();
if (b <= a.length) {
System.out.println("Number Found");
break;
}
else {
System.out.println("Number Not Found");
}
}
}
}
Hi I am having trouble with Scanner to get user input two separate ArrayList. When I run this code I get an IndexOutOfBounds exception after entering the two arrays.
The code adds two binary numbers together using logic of a ripple adder. An example of intended user input would be
Enter A array: 1 0 1 0
Enter B Array: 0 0 0 1
producing: 1 0 1 1
The code works when arrays are hard coded, how can I get the user to enter the arrays?
Code is shown below
import java.util.*;
public class AdderApp {
public static void main(String[] args) {
Scanner inputA = new Scanner(System.in);
ArrayList<Integer> aList = new ArrayList<Integer>();
ArrayList<Integer> bList = new ArrayList<Integer>();
int c = 0;
System.out.println("Enter A array");
aList.add(inputA.nextInt());
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
bList.add(inputB.nextInt());
Adder bit1 = new Adder(parseInput(aList.get(3)), parseInput(bList.get(3)), parseInput(c));
Adder bit2 = new Adder(parseInput(aList.get(2)), parseInput(bList.get(2)), bit1.getCout());
Adder bit3 = new Adder(parseInput(aList.get(1)), parseInput(bList.get(1)), bit2.getCout());
Adder bit4 = new Adder(parseInput(aList.get(0)), parseInput(bList.get(0)), bit3.getCout());
if (bit4.getCout() == false) {
System.out.println(bit4.toString() + " " + bit3.toString() + " " + bit2.toString() + " " + bit1.toString());
} else {
System.out.println("overflow!");
}
}
public static boolean parseInput(int i) {
if (i == 1) {
return true;
} else {
return false;
}
}
}
Code for Adder class:
public class Adder {
private boolean a, b, cin, cout, s;
/**
* Full Adder contructor
*/
public Adder(boolean a, boolean b, boolean cin) {
this.a = a;
this.b = b;
this.cin = cin;
s = nand(nand(a, b), cin); //sum bit
cout = or(and(nand(a, b), cin), and(a, b)); // - carry bit
}
/** Half adder constructor */
// public Adder (bloolean a, boolean b) {
//
// this.a = a;
// this.b = b;
//
// s =
//}
/**
* NAND gate
*/
public boolean nand(boolean a, boolean b) {
return a ^ b;
}
/**
* AND gate
*/
public boolean and(boolean a, boolean b) {
return a && b;
}
/**
* OR gate
*/
public boolean or(boolean a, boolean b) {
return a || b;
}
public boolean getCout() {
return cout;
}
public String toString() {
if (s == true) {
return "1";
} else {
return "0";
}
}
public String toStringCout() {
if (cout == true) {
return "1";
} else {
return "0";
}
}
}
Your entire AdderApp class can be simplified and improved to accept any bit length by accepting the input in a slightly different way and then using a for loop to add each bit. The parseInput function can be replaced with a simple boolean comparison:
import java.util.*;
public class AdderApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter A array");
char[] aIn = input.nextLine().replace(" ", "").toCharArray();
System.out.println("Enter B array");
char[] bIn = input.nextLine().replace(" ", "").toCharArray();
StringBuilder result = new StringBuilder();
Adder bit = new Adder(false, false, false);
for (int i = aIn.length - 1; i >= 0; --i) {
bit = new Adder((aIn[i] == '1'), (bIn[i] == '1'), bit.getCout());
result.append(bit + " ");
}
System.out.println(bit.getCout() ? "overflow!" : result.reverse());
}
}
Scanner.nextInt gets the next integer in the input, and then stops. Each of your lists only contains 1 element.
Use something along these lines instead:
String[] input = inputA.nextLine().split(" ");
for (String s : input)
{
try { aList.add(Integer.parseInt(s)); }
catch(NumberFormatException nfe) { /* handle exception as desired */ }
}
Alternatively, you should be able to use something like:
while (inputA.hasNextInt())
{
aList.add(inputA.nextInt());
}
You should be having a for loop to have an input into your ArrayList.
System.out.println("Enter A array");
for (int i = 0; i < 4; i++) {
aList.add(inputA.nextInt());
}
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
for (int i = 0; i < 4; i++) {
bList.add(inputB.nextInt());
}
The user should input 4 numbers, your one just allow the user to enter 1 number:
int count = 0;
Scanner inputA = new Scanner(System.in);
System.out.println("Enter A array");
while(count < 4){
count++;
aList.add(inputA.nextInt());
}
count = 0;
Scanner inputB = new Scanner(System.in);
System.out.println("Enter B array");
while(count < 4){
count++;
bList.add(inputB.nextInt());
}
If you want to use hasNextInt():
while(inputA.hasNextInt()){
count ++;
aList.add(inputA.nextInt());
if(count == 4){
count = 0;
break;
}
}