I am trying to write a class with all the methods I need for my main, but am having trouble figuring out how to ascertain the desired values using the methods. The ones I am having trouble with are getAverageLength and getCount.
Current Output:
The length of Line 1 is 1.0
The length of Line 2 is 10.0
There are 0 lines and the average length is 0
The length of Line 1 is 1.0
The length of Line 2 is 10.0
The length of Line 3 is 7.0
There are 0 lines and the average length is 0
Expected Output:
The length of Line 1 is 1
The length of Line 2 is 10
There are 2 lines and the average length is 5.5
The length of Line 1 is 7
The length of Line 2 is 10
The length of Line 3 is 7
There are 3 lines and the average length is 8.0
This is the portion of my main method that I am using.
public class TestParts {
public static void main(String[] args) {
MyLine ml1 = new MyLine();
MyLine ml2 = new MyLine(10);
System.out.println("The length of Line 1 is " + ml1.getLength());
System.out.println("The length of Line 2 is " + ml2.getLength());
System.out.println("There are " + MyLine.getCount() +
" lines and the average length is " + MyLine.getAverageLength());
MyLine ml3 = new MyLine(7);
ml1.setLength(7);
System.out.println("The length of Line 1 is " + ml1.getLength());
System.out.println("The length of Line 2 is " + ml2.getLength());
System.out.println("The length of Line 3 is " + ml3.getLength());
System.out.println("There are " + MyLine.getCount() +
" lines and the average length is " + MyLine.getAverageLength());
}
}
And the following is the seperate class that I am writing to calculate the values.
class MyLine {
private double getLength;
MyLine() {
getLength = 1;
}
double getLength() {
return getLength;
}
MyLine(double setLength) {
getLength = setLength;
}
public void setLength(int i) {
getLength = getLength();
}
public static int getCount() {
return 0;
}
public static int getAverageLength() {
return 0;
}
}
For getCount, make a static int that is incremented by each constructor.
For getAverageLength, make a static int with the sum of the lines that is added to by each constructor and divide it by the count.
There are several problems with the code.
First, recommend documenting what the methods are supposed to do in comments.
This will help you and others.
Second, these methods:
public void setLength(int i) {
getLength = getLength();
}
The getLength private member variable is probably badly named.
I suspect the intent was a noun like length whereas getLength() is a method intended to return the current length.
This method takes a primitive int datatype to set a type of double.
Was this intentional?
Looks like a misconception.
Moreover, it has no function as it just sets the getLength (again, should be length) variable to the return value of the method getLength(), which in turn returns the value of getLength. This is a remedial logic and basic math problem:
A = 1 = getLength() = A = 1
public static int getCount() {
return 0;
}
Why would anything other than zero be expected to be returned from this method?
public static int getAverageLength() {
return 0;
}
Same here ... fundamental logic problem.
I would not post this kind of question on the forum as it lacks doing basic homework before posing the question.
build a HashMap<MyLine, Integer>
Integer is the length of the MyLine.
you just put those MyLine objects you want to count into that map.
{ml1:0,
ml2:10,
ml3:7}
then you could calculate everything you want.
Related
I'm trying to learn java, and I can't seem to understand recursion. I can understand how recursion can be used to add and do other basic math operations but how can recursion be used to reverse manipulate integers and individual integer digits.
example:
a method takes a single positive integer argument and displays its base five equivalent. 231 returns 1411 but the code below returns 1141. how would I reverse the order of integers put out?
public void base5(int n){
int rem=n%5;
int vis=n/5;
if(n!=0){
// System.out.print(rem/*+"|"*/);
//
// rem=(rem+rem)*10;
// System.out.print("\n||"+n+"||\n");
System.out.print(rem);
base5(vis);
}
else{
return;
}
}
The algorithm for getting individual digits of an integer, from right to left, is well known. See How to get the separate digits of an int number?.
I won't "explain" recursion, but I'll give you one possible solution for first problem:
a method takes a single positive integer and displays it with commas
inserted every three digits
import java.util.Scanner;
class Main {
public static void main( String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your positive integer: ");
long number = sc.nextLong();
String result = addCommas(number);
System.out.println(result);
}
public static String addCommas(long num) {
return addCommas(num, 1);
}
public static String addCommas(long num, int counter) {
if (num == 0) {
return ""; // base case ends recursion
}
else {
long digit = num % 10;
num = num / 10;
String comma = (counter%3==0 && num>0) ? "," : "";
// recursive call below because we call addCommas() again
return addCommas(num, counter+1) + comma + digit;
}
}
}
Here's a compact solution to the second problem:
a method takes a single positive integer and displays the result of
reversing its digits
public static String reverseDigits(long num) {
if (num == 0) {
return "";
}
else {
return String.valueOf(num % 10) + reverseDigits(num / 10);
}
}
I am creating a scrabble game, where the characters get the same values as scrabble,(q & z =10),(k=5), etc, and the main issue that I am having is that I am asking the user to input 2 ints after the word, the first being the index of the bonus tile, and the second being the multiplier to multiply the word with. The value without the multiplier is correct, but the multiplier is not working.
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String word = kb.next();
int bonusI = kb.nextInt();
int bonusMult = kb.nextInt();
int score=0;
for (int i=0; i<word.length();i++){
int letterScore;
String letter=word.substring(i,i+1);
if (letter.equals("d")||letter.equals("g")){
letterScore=2;
}
else if (letter.equals("k")) {
letterScore=5;
}
else if (letter.equals("j")||letter.equals("x")){
letterScore=8;
}
else if (letter.equals("q")||letter.equals("z")) {
letterScore=10;
}
else {
letterScore=1;
}
for (int j=0;j<1;j++){
if (word.substring(i,i+1).equals(bonusI)){
letterScore*=bonusMult;
}
}
score+=letterScore;
}
System.out.println(score);
}
}
For example, if the input is dog 2 3 then the correct output would be 9,(d is 2 points,o according to scrabble is 1 point, and g is 2 points, but since the 1st int inputted was 2, and g has an index of 2, it is then multiplied by the bonus of 3, which makes g=6, adding them 2+1+6=9) but instead my output is 5 because the multiplier for g is not working.
Looks like you have a mistake here.
word.substring(i,i+1).equals(bonusI)
word.substring(i,i+1) is String and gives one letter
bonusI is an int and tives one number
This will never be true
if (word.substring(i,i+1).equals(bonusI)) - This condition will be always false as you can't compare a string with int value.
Instead you can just replace the internal for loop with below code
if (bonusI == i)
{
letterScore*=bonusMult;
}
This question already has answers here:
When do you use varargs in Java?
(8 answers)
Closed 6 years ago.
I am faced with probably a very simple dilemma. I am trying to create a program that computes the averages, sums, and count of all numbers inputed to the calculator. The problem with this is that I can only accept one input or three (dependent on number of variables listed in my method parameters). How do I make my add() method actually accept n number of inputs as opposed to a predefined set?
Main Class
public class Calculator
{
public static void main (String [] args)
{
AverageCalculator calculation1 = new AverageCalculator();
AverageCalculator calculation2 = new AverageCalculator();
calculation1.add(13);
System.out.println("Sum: " + calculation1.getSum());
System.out.println("Count: " + calculation1.getCount());
System.out.println("Average: " + calculation1.getAverage());
System.out.println();
calculation2.add(3, 7, 12); // Error due to method parameters
System.out.println("Sum: " + calculation2.getSum());
System.out.println("Count: " + calculation2.getCount());
System.out.println("Average: " + calculation2.getAverage());
}
}
I get an error when compiling this:
Calculator.java:28: error: method add in class AverageCalculator cannot be applied to given types;
calc2.add(3, 7, 12);
I am then running into how am I going to deal with my add() method's functionality. I know what it must do, I am sure I must add a for Loop. However, there is no given length for it to parse. Do I have my i = 0; i < calculation 2; i++? See comments in this portion
Secondary Class
public class AverageCalculator
{
private int sum;
private int count;
public AverageCalculator () {}
public void add (int newNum) // One input due to single parameter
{
// How to accept the multiple input from main class with this mutator
// and successfully manipulate data in this method
sum += newNum;
count++;
}
public int getSum()
{ return sum; }
public int getCount()
{ return count; }
public double getAverage()
{ return (double) sum / count; }
}
Java supports this. Is is called "varargs". If you add "..." to your type, you can repeat it as many times as you want (including 0 times) and then, in your function, process it as an array. This could like this (this code is completely untested):
public void add(int... newNums) {
for (int num : newNums) {
sum += num;
count++;
}
}
A you can read a bit more here.
I'm working on a recursive method that will return and print in my main method a String that will count down by 1 for N. Deleting one letter for each recursion for the string. Until N becomes 1 or until the string has 1 letter. (N being a int on the commandline)
For example if my command lines aruments are: 5 valentine
It should output too:
5 valentine, 4 alentine, 3 lentine, 2 entine, 1 ntine,
So far I managed to count down the number inputted on the commandline argument. I just don't know how to go about deleting one letter from the string? :o
My code so far:
public static void main(String[] args){
int number = Integer.parseInt(args[0]);
String word = new String("");
word = args[1];
String method = recursive.method1(number);
System.out.println(method);
}
public static String method1(int number){
if (number < 0){
return "";
}
else{
return number + ", " + method1(number - 1);
}
}
You can read through subString() documentation to understand how to go about taking the portions of a String.
Change your method definition to include the word
Add the word to your return statement: return number + " " + word +...
Call substring of the original word from the 1st index
Check for <=0 rather than <0
Code:
public static void main(String[] args){
int number = 5;
String word = new String("");
word = "Valentine";
String method = Recurcive.method1(number, word);
System.out.println(method);
}
public static String method1(int number, String word){
if (number <= 0){
return "";
}
else{
return number + " " + word + ", " + method1(number - 1, word.substring(1));
}
}
Gives,
5 Valentine, 4 alentine, 3 lentine, 2 entine, 1 ntine,
Please see my comments in the code to better explain things. Basically having issues with the methods below. I can get the load method to run but I am unsure whether the numbers entered by the user are actually being stored in the array.
In addition, the search method has been throwing things off and i think its going in a loop.
See below for more. Thank you in advance.
import java.util.Scanner;
public class MyContainer {
private int[] values;
private int size;
public MyContainer(){
values=new int[50];
size=0;}
//Load Method - Display a message to the user
//and get positive intergers from user
public void load()
{
int input;
Scanner in = new Scanner(System.in);
System.out.println("Enter a series of positive integers (Negative to Terminate): ");
input=in.nextInt();
while (input >=0) {
values[size]=input;
size++;
input=in.nextInt();
}
}//End Load
//Compute Average from the above entered numbers
public double computeAverage() {
double avg= 0.0;
int count = 0;
while(values[size] >=0)
{avg = avg + values[size];
count++;
}
size = size + 1;
avg = avg / size;
return avg;
}
//Get user input to search for a number in the array
public boolean search(int myInt){
while(values[size] >=0) {
if (values[size] == myInt){
return true;}
else{
size++;}
}
return false;
}
//print the position of the number
public void print(){
for(int i=0;i>=size;i++) {
System.out.println("The number at position " + i + " is " + values[i]);
}
}
}
That is what I have so far. I also have created a tester class for the above container.
class Tester {
public static void main(String[] args) {
MyContainer in = new MyContainer();
in.load();
in.computeAverage();
in.search(); //i know for a fact this is wrong just stuck
in.print();
}
}
Any advise/help would be greatly appreciated. My professor is terrible at teaching and the book only partially explains things.
Your search() method has parameters that you aren't passing.
you declare it as...
public boolean search(int myInt) {
while (values[size] >= 0) {
if (values[size] == myInt) {
return true;
} else {
size++;
}
}
return false;
}
but call it with...
in.search();
This code won't even compile. For argument sake I set this to 5.
In your computeAverage() method, this is an infinite loop...
while (values[size] >= 0) {
avg = avg + values[size];
count++;
}
The main problem I believe you are running into is the reuse of your size variable. In the load function it will work as expected say for loading in 10 numbers size will be 10 and elements 0->9 in values will have numbers in them. However when you get to computeAverage size will still be 10. So you are in an infinite loop.
while(values[size] >= 0) {
avg = avg + values[size];
count++;
}
First iteration you will check values[10] (which is wrong remember valid elements are only in 0->9 if size is 10). Next iteration avg and count are increased but size remains the same so you will add the same number to avg and continue in the loop. You should use a different conditional for your while loops in computeAverage and search. The last negative number entered to quit will not be in the array; you will need to use something else. As a hint it will involve count and size.