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
Here is my code to display smallest and largest integer by taking 5 inputs from user...it works for smallest values but not for largest and I cant figure out the problem...please help
import java.util.Scanner;
public class LargestAndSmallestIntegers {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int a,b,c,d,e;
int small,large;
System.out.println("Enter five integer values...");
a=input.nextInt();
small=a;
large=a;
b=input.nextInt();
if (small<b)
{
large=b;
}
else
{
small=b;
}
c=input.nextInt();
if (small<c)
{
large=c;
}
else
{
small=c;
}
d=input.nextInt();
if (small<d)
{
large=d;
}
else
{
small=d;
}
e=input.nextInt();
if (small<e)
{
large=e;
}
else
{
small=e;
}
input.close();
System.out.printf("%d is smallest and %d is largest", small,large);
}
}
private int a = input.nextInt(),
b = input.nextInt(),
c = input.nextInt(),
d = input.nextInt(),
e = input.nextInt();
private int small, large;
small = min(a,b);
small = min(small,c);
small = min(small,d);
small = min(small,e);
large = max(a,b);
large = max(large,c);
large = max(large,d);
large = max(large,e);
private int min(int a, int b) {
if (a < b) return a else return b;
}
private int max(int a, int b) {
if (a > b) return a else return b;
}
I think this works ;)
it works for smallest values but not for largest
As lared pointed out, comparing against small to determine large is flawed. You must include something like this in your comparison logic:
if (large < b)
{
large = b;
}
in addition to your existing comparison:
if (small > b)
{
small = b;
}
you always just check for the smallest value. you also need to check
if (small<e)
{
if(large < e)
{
large=e;
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Sum s = new Sum();
Sum.SetToZero z = new Sum.SetToZero();
Scanner input = new Scanner(System.in);
String read = input.nextLine();
while (!read.equals("end")) {
if (read.equals("add")) {
s.add()
}
else if (read.equals("get")) {
System.out.println(s.returnTotal());
}
else if (read.equals("zero")) {
z.zero();
}
read = input.nextLine();
}
class:
public class Sum {
int total = 0;
public void add() {
total += 1;
}
public int returnTotal() {
return total;
}
public static class SetToZero extends Sum {
public void zero() {
total = 0;
}
}
}
input:
add
add
zero
add
get
add
get
end
output:
3
4
output wanted:
1
2
Shouldn't the subclass inherit the total and set it to zero? What am I doing wrong? I know I could just move the zero into the main class but I want it to be in a separate class. thx for your help.
By making your total variable static, you can get the desired output.
class Sum {
static int total = 0;
public void add() {
total += 1;
}
public int returnTotal() {
return total;
}
public static class SetToZero extends Sum {
public void zero() {
total = 0;
}
}
}
Apart from things pointed out in names like not using lowecase letters to start your class name; I think the reason why it's not working is because you're using two different variable instances for Sum and Sum.SetToZero. You don't need to create a new variables since SetToZero has all the attributes of Sum. I think you should change this:
Sum s = new Sum();
Sum.SetToZero z = new Sum.SetToZero();
Sum.SetToZero s = new Sum.SetToZero(); // use s for all operations
Here is how your modified main method would look:
public static void main(String[] args) {
Sum.SetToZero s = new Sum.SetToZero();
Scanner input = new Scanner(System.in);
String read = input.nextLine();
while (!read.equals("end")) {
if (read.equals("add")) {
s.add();
}
else if (read.equals("get")) {
System.out.println(s.get());
}
else if (read.equals("zero")) {
s.zero();
}
read = input.nextLine();
}
}
When I ran this, I saw expected output:
src : $ java Sum
add
add
zero
add
get
1
add
get
2
end
I am writing a program in my AP java class and I am very confused. The program is supposed to read a data file using another program called EasyReader. The program consists of an Object class that finds the largest number, medium number, and smallest number. The Test class is supposed to read the data file (numbers.bat) that gives a set of numbers and the program is supposed to print the largest, medium, and smallest of all lines of the data file. However, it is reading only one line of the data file (the middle one) instead of all three. It is displaying
Largest = 7.3 Medium = 5 Smallest = 3.2
Please help. Thank you!
Here is the Object class:
public class Numbers
{
double small;
double medium;
double large;
public Numbers(double A, double B, double C)
{
if(A>=B && A>=C)
{
large = A;
if(B>=C && B<=A)
{
medium = B;
small = C;
}
else
{
medium = C;
small = B;
}
}
else if(B>=A && B>=C)
{
large = B;
if(A>=C && A<=B)
{
medium = A;
small = C;
}
else
{
medium = C;
small = A;
}
}
else
{
large = C;
if(A>=B && A<=C)
{
medium = A;
small = B;
}
else
{
medium = B;
small = A;
}
}
}
public double large()
{
return large;
}
public double medium()
{
return medium;
}
public double small()
{
return small;
}
}
Here is the Test class:
public class NumbersTest
{
public static void main(String[] args)
{
EasyReader file = new EasyReader("numbers.dat");
double value1 = file.readDouble();
double value2 = file.readDouble();
double value3 = file.readDouble();
value1 = file.readDouble();
value2 = file.readDouble();
value3 = file.readDouble();
Numbers nums = new Numbers(value1, value2, value3);
System.out.println("Largest = " + nums.large() + " Medium = " + nums.medium() + " Smallest = " + nums.small());
}
}
And last the data file (numbers.bat)
4 9 2.5
3.2 5 7.3
12 8.2 9.1
The output right now:
Largest = 7.3 Medium = 5.0 Smallest = 3.2
The expected output:
Largest = 12.0 Medium = 7.3 Smallest = 2.5
Your numbers constructor only does anything if your value1 (A) is larger or equal to the other two. If it isn't it will leave small,medium and large at 0.
Edit: Expanding the answer here as it looks cleaner.
So in your number constructor
public Numbers(double A, double B, double C)
{
if(A>=B && A>=C)
{
large = A;
if(B>=C && B<=A)
{
medium = B;
small = C;
}
else
{
medium = C;
small = B;
}
}
}
You only have one main if statement checking if A is the largest, and the rest are nested into it. You would also need an if statement for if B or C are the largest.
public Numbers(double A, double B, double C)
{
if(A>=B && A>=C)
{
large = A;
if(B>=C && B<=A)
{
medium = B;
small = C;
}
else
{
medium = C;
small = B;
}
} else if if(B>=A && B>=C)
{
//B is the largest, add code to determine medium and small as you did before
} else {
//C is the largest, add code to determine medium and small as you did before
}
}
As part of my AP computer science project, I decided to get a polynomial from a user and it will be able to find the derivative of the equation using the power rule.
For example, if the user enters 2X^3+5x^2 it should output 6x^2+10x^1, so the coefficient and degree multiplied together and then the degree is just minus one. This is what I have so far but it's giving me a lot of errors, and tried following the code but don't see anything wrong with it. Thanks for your help.
import java.util.ArrayList;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
//input of polynomial
System.out.println("Enter polynomial:");
Scanner sc = new Scanner(System.in);
String polynomialEquation = sc.nextLine();
//A string array list is created with the polynomial
ArrayList<String> equationArr = new ArrayList<String>();
for (int i = 0; i<polynomialEquation.length(); i++) {
equationArr.add(polynomialEquation.substring(i, i+1));
}
ArrayList<String> intStrings = new ArrayList<String>();
//separate the numbers from the list
for(int i =0; i<equationArr.size(); i++) {
if (equationArr.get(i).equals("1") || equationArr.get(i).equals("2") || equationArr.get(i).equals("3") ||equationArr.get(i).equals("4") ||equationArr.get(i).equals("5") ||
equationArr.get(i).equals("6") || equationArr.get(i).equals("7") || equationArr.get(i).equals("8") || equationArr.get(i).equals("9") || equationArr.get(i).equals("0"))
{
String addVal = equationArr.get(i);
intStrings.add(addVal);
equationArr.remove(i);
}
}
//convert string integers to integers
ArrayList<Integer> deriveInt = new ArrayList<Integer>(intStrings.size());
for (String myInt : intStrings)
{
deriveInt.add(Integer.valueOf(myInt));
}
//derive coefficiants
for (int i = 0; i<deriveInt.size()-1;i +=2) {
deriveInt.set(i, deriveInt.get(i)*deriveInt.get(i+1));
}
//derive exponent
for(int i = 1; i< deriveInt.size(); i +=2) {
deriveInt.set(i,deriveInt.get(i)-1);
}
//convert integer back to string
ArrayList<String> stringDerive = new ArrayList<String>();
for (Integer myInt2 : deriveInt)
{
stringDerive.add(String.valueOf(myInt2));
}
//get the signs from the original equation
ArrayList<String> sign = new ArrayList<String>();
for(int i =0; i<equationArr.size(); i++) {
if(equationArr.get(i).equals("+") || equationArr.get(i).equals("-")) {
sign.add(equationArr.get(i));
}
}
int totalSize = stringDerive.size() * 2 + equationArr.size();
for (int i = 0; i<totalSize-1; i=+2) {
int countSign= 0;
System.out.print(stringDerive.get(i));
System.out.print("x^");
System.out.print(stringDerive.get(i+1));
System.out.print(equationArr.get(countSign));
}
}
}
Polynomials are composed of monomials. In your example these are 2X^3 and 5x^2. One of approach to solving your problem is writing the Monom class and Polynom class. I'll give you a skeleton so you can practice.
public class Helper {
private class Monom{
private int coefficient;
private int degree;
public Monom(int coefficient, int degree){
this.coefficient = coefficient;
this.degree = degree;
}
public Monom(String input){
//TODO parse input. E.g Monom("6x^2) --> this.coefficient = 6...
//TODO validate input
}
public Monom derivate(final Monom monom){
return new Monom(monom.getCoefficient() * monom.getDegree(), monom.getDegree() - 1);
}
public int getCoefficient() {
return coefficient;
}
public int getDegree() {
return degree;
}
#Override
public String toString(){
return this.coefficient + "x^" + this.degree;
}
}
//skeleton
private class Polynom{
private List<Monom> polynom; //holder of monoms
//TODO rest of code including constructors, validate, derivate...
public Polynom(List<Monom> monoms){
this.polynom = monoms;
}
public Polynom derivate(Polynom input){
List<Monom> temp = new ArrayList<>();
for (Monom monom: polynom){
temp.add(monom.derivate(monom));
}
return new Polynom(temp);
}
}
public static void main(String[] args) {
//TODO test code
List<Monom> monoms = new ArrayList<>();
//TODO rest of code like:
// Polynom myPolynom = new Polynom(List<Monom> monoms);
//...
}
}
Like I said, this is just a code you have to upgrade... Good luck.
welcome to Stack Overflow and the wonderful world of programming! On a personal note, I started coding in high school with APCS too :)
Your question is arguably a bit too broad for this site. For example, you mentioned the code is "giving me a lot of errors": a better question would include the inputs you've tried and the specific output you're seeing and what you expected instead. I still want to help you though, so I'll give you some feedback and we can work through a few revisions.
First, I see that you've divided your program into sections using comments. This is a great instinct! You've decomposed the larger problem into smaller problems in a way that communicates your intent.
input of polynomial
A string array list is created with the polynomial
separate the numbers from the list
convert string integers to integers
derive coefficiants
derive exponent
convert integer back to string
get the signs from the original equation
However, it still leaves us with the problem of having a large main method to understand. So for your next revision, you should fix that by breaking it up into smaller methods. You can start by moving each of these "steps" into its own method, then call each of them from main. To help you get started, here's what it would look like with your first "step" extracted:
public class Practice {
public static String readPolynomial() {
System.out.println("Enter polynomial:");
Scanner sc = new Scanner(System.in);
String polynomialEquation = sc.nextLine();
return polynomialEquation;
}
public static void main(String[] args) {
String polynomialEquation = readPolynomial();
//A string array list is created with the polynomial
...
}
}
I think you'll find that this really improves your understanding of both your code and the problem you're trying to solve. Don't be afraid to change the steps based on that new understanding. It's no coincidence that the buggy or unfocused areas of your code are the areas you'll struggle the most to name. Try to focus on the problem, rather than your implementation. For instance, my first step would probably be a combination of your first few. Things like parsing the input String and then converting from Strings to Integer don't have much to do with polynomials or derivatives. So for readPolynomial I would prefer:
public static ArrayList<Integer> readPolynomial() {
The other big benefit of this refactor is that it will be much easier for you to test that each step is working the way you want it to. It gives you much more fine-grained control because you can test each method individually, rather than only being able to test by running the entire program. It will be much easier to isolate, understand, and fix each individual bug.
Another big thing: please provide some more sample inputs! Not only will this help clarify requirements, but we can use them as test cases later.
Here's some functioning code to help you, please don't just take it for granted but read it and understand what is happening. If you have any questions on it please ask. It could use some cleanup but hopefully it's still understandable.
One minor thing to note is that sign is attached to the expressions (as it kinda should be) so you could just + all the expressions together and it would be valid. But if you want to avoid having an answer like 6x^2 + -10y^4 and would rather have 6x^2 - 10y^4 then you'd have to check if the expressions are negative when building the answer with them.
public class Test {
public static void main(String[] args) {
// input requires all constants to be fully resolved
// eg. no '3^2^1^3', instead it should be '9'
// eg. no '5*2x', instead it should be '10x'
// mess around with the input to test
String s = "2x^3+5x^2";
List<DerivableExpression> list = parseDeriveableExpressions(s);
List<DerivableExpression> derivatives = new ArrayList<>();
for(DerivableExpression de : list)
derivatives.add(de.getDerivative());
System.out.println(String.join("+", derivatives)); // 6x^2+10x^1
}
private static List<DerivableExpression> parseDeriveableExpressions(String s) {
// remove all spaces and lowercase everything
s = s.replace(" ", "");
List<DerivableExpression> list = new ArrayList<>();
char var = ' ';
StringBuilder constBuff = new StringBuilder();
StringBuilder powerBuff = new StringBuilder();
boolean parsingPower = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '+' || c == '-') {
if (parsingPower && powerBuff.length() == 0) {
// at the start of the power expression
if (c == '-')
powerBuff.append(c);
} else {
// either not parsing a power or not at the start of the power
// this is a +/- after the power, terminating the expression
parsingPower = false;
int constant = 1;
if (constBuff.length() > 0) {
constant = Integer.parseInt(constBuff.toString());
constBuff.setLength(0);
}
if (var != ' ' && constant != 0) {
int power = 1;
if (powerBuff.length() > 0)
power = Integer.parseInt(powerBuff.toString());
list.add(new VariableExpression(constant, var, power));
} else {
list.add(new ConstantExpression(constant));
}
powerBuff.setLength(0);
var = ' ';
// append the sign for the next expression
if (c == '-')
constBuff.append(c);
}
} else if ('0' <= c && c <= '9') {
if (parsingPower)
powerBuff.append(c);
else
constBuff.append(c);
} else if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')) {
if (constBuff.length() == 0 ||
(constBuff.length() == 1 && constBuff.charAt(0) == '-'))
constBuff.append("1");
var = c;
} else if (c == '^') {
parsingPower = true;
}
}
// add the last expression
int constant = 1;
if (constBuff.length() > 0) {
constant = Integer.parseInt(constBuff.toString());
constBuff.setLength(0);
}
if (var != ' ') {
int power = 1;
if (powerBuff.length() > 0) {
power = Integer.parseInt(powerBuff.toString());
powerBuff.setLength(0);
}
list.add(new VariableExpression(constant, var, power));
var = ' ';
} else {
list.add(new ConstantExpression(constant));
}
return list;
}
private static interface DerivableExpression {
public abstract DerivableExpression getDerivative();
}
private static class VariableExpression implements DerivableExpression {
private final int constant;
private final char variable;
private final int power;
public VariableExpression(int constant, char variable, int power) {
this.constant = constant;
this.variable = variable;
this.power = power;
}
#Override public VariableExpression getDerivative() {
return new VariableExpression(constant * power, variable, power - 1);
}
#Override public String toString() { return constant + "" + variable + "^" + power; }
}
private static class ConstantExpression implements DerivableExpression {
private final int constant;
public ConstantExpression(int constant) {
this.constant = constant;
}
#Override public DerivableExpression getDerivative() { return this; }
#Override public String toString() { return Integer.toString(constant); }
}
}
Im sorry if this question has been asked a lot. Im still pretty new to programming and obviously have some issues in phrasing questions/searching for answers.
I want to do the following:
My algorithm includes 2 methods. One has the task to find out how many of the numbers between 0 to 30 are even and which one are not. I want those even numbers to be somehow stored and redirected to my second method to get added. How can I store those even numbers?
My code looks currently like this: (not even close to being finished)
public class Add
{
static long method(long end)
{
long number = even;
return;
}
static long even() {
if (i%2 == 0) { // even
}
else { // uneven
}
}
public static void main(String[ ] args)
{
int number = method(30);
System.out.println("");
}
}
edit:Im having formating problems... Im sorry the code looks even harder to understand. Im trying to fix it this instant.
Like it was said in the comments, add them to a list, then iterate the list while updating a variable that will be the sum of the even numbers.
public class Add {
private static ArrayList<Integer> evenNums = new ArrayList<>();
private static void evenNumbers(int max) {
for (int i = 0; i < max; i++) {
if (i % 2 == 0) {
evenNums.add(i);
}
}
}
private static int sum(ArrayList<Integer> array){
int sum = 0;
for(int i = 0; i < array.size(); i++){
sum = sum + i;
}
return sum;
}
public static void main (String[]args){
evenNumbers(30);
int sum = sum(evenNums);
System.out.println(sum);
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am trying to write a program in java which takes decimal number as an int parameter and prints to the screen the binary equivalent of that decimal number ...
In short decimal to binary conversion using only int parameters ...
Solution will be much appreciated ... i have tried some steps but i am not successful ..
Thanks
Integer.toString(input, 2);
OR
Integer.toBinaryString(input);
You might also want checkout:
Integer.toHexString
Integer.toOctalString
INPUT : 10 (decimal)
RESULT: 1010 (binary)
Hope this helps :)
Or you can write program like this (modify it):
import java.util.Scanner;
public class DecToBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int broj;
System.out.print("Enter number that you want to conver to binary: ");
broj = input.nextInt();
convert(broj);
}
public static void convert(int a) {
String obrnuti = "";
while (a > 0) {
int x = a % 2;
obrnuti += x;
a /= 2;
}
System.out.println(reverse(obrnuti));
}
public static String reverse(String a) {
String novi = "";
for (int i = a.length() - 1; i >= 0; i--) {
char c = a.charAt(i);
novi += c;
}
return novi;
}
}
conversion from decimal to binary :
Integer.toBinaryString(Int_variable)
conversion from binary to decimal:
Integer.parseInt(string_binary_variable,2)
public class DecimalToBinary
{
// 5 = 101
public static void main(String[] args)
{
int d2b = dec2Bin(5);
System.out.println(d2b);
}
public static int dec2Bin(int num){
int a = num;
int binary=0;
int i=1;
while(a != 0){
binary = binary+i*(a%2);
a = a/2;
i=i*10;
}
return binary;
}
}
public class BinaryToDecimal {
public static void main(String[] args) {
String binary = "110";
System.out.println(binToDec(binary));
}
public static int binToDec(String binary){
int decimal=0;
for(int i=0;i<binary.length();i++){
decimal = 2*decimal + Integer.parseInt("" + binary.charAt(i));
}
return decimal;
}
}