What should I use for the while loop? - java

This is my coding so far - instructor asked me to create a program that creates triangles and specifies them.Here are the actual instructions for clarity:
*Write a program that creates sets of random triangle sides using integer values between 3 and 13. The user will specify how many triangles they would like created by entering an integer value between 1 and 10 (you may assume that they will enter an integer in this range).
For each triangle the user has requested, your program should:
Generate a set of 3 random integers between 3 and 13.
Display the 3 numbers
Decide if the numbers represent the sides of a valid triangle. (For example, 5, 5, and 13 do NOT create a triangle).
--- If the numbers do not represent a valid triangle, display an appropriate error message.
--- If the numbers are valid, the program should determine, and display, the
a) side classification of the triangle – equilateral, isosceles, or scalene, and
b) the angle classification of the triangle – right, acute, or obtuse*
// I need to figure out what to use in the while loop. I haven't written all of the coding yet, but there is an empty while loop (which im trying to use to calculate the userInput x apple and orange (yes I did use fruits as ints)
// Writing all coding here:
// Declaring maximum and minimum values for user input:
int maxValue = 13;
int minValue = 3;
userInteger = (int) (maxValue * Math.random()) + minValue;
userInteger2 = (int) (maxValue * Math.random()) + minValue;
userInteger3 = (int) (maxValue * Math.random()) + minValue;
String banana = (userInput.getText());
{
while()
outcomeLabel.setText("Your numbers are: " + userInteger + ", " + userInteger2 + " and " + userInteger3 + "." +
"\n" + "The number of triangles requested is" + banana + "so the result is");
}
int apple = (userInteger + userInteger2);
int orange = (userInteger3);
{
if (apple == orange)
outcomeLabel.setText("Your numbers are: " + userInteger + ", " + userInteger2 + " and " + userInteger3 + "." +
"\n" + "The number of triangles requested is" + banana + "\n" + "The numbers make a triangle.");
else
outcomeLabel.setText("Your numbers are: " + userInteger + ", " + userInteger2 + " and " + userInteger3 + "." +
"\n" + "The number of triangles requested is" + banana + "\n" + "The numbers do not make a triangle - try again.");
}
{
if(userInteger == userInteger2 && userInteger == userInteger3)
outcomeLabel.setText("Your numbers are: " + userInteger + ", " + userInteger2 + " and " + userInteger3 + "." +
"\n" + "The number of triangles requested is" + banana + "\n" + "The numbers make a triangle." + "\n" + "This triangle is an equilateral triangle.");
}
{
if (userInteger == userInteger2) {
}
}
}

From the look of your code, your while loop might not be in the right place... Ignoring the while loop, your code just generates a single set of three numbers and prints whether they would make a triangle, right? So where would you put the while loop to do this single action multiple times? In the middle of the provided code doesn't make too much sense...
A few other things: I don't believe your code to determine whether the generated sides can make a triangle works. What happens if userInteger = userInteger2 = 5, and userInteger3 = 4? And if you want to generate a number of triangles with the number provided by the user, you need some way to convert the inputted String into an integer. For that, checkout the Integer.parseInt() method: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
Finally, you probably want to check out the Java tutorials: http://docs.oracle.com/javase/tutorial/java/index.html
I don't believe your code would work as expected when you first run it. Blocks of code inside plain braces in your class are called "initialization blocks", and are run at object creation every time your class is instantiated. What you probably want is to place everything into a method, which will allow you to run the code on command as many times as you want.

Related

When my loop repeats, why isn't the random value assigned to a certain variable changing?

System.out.println("Composition Statistics for Families with Two Children: \n");
System.out.println("Total Number of Families: ");
FamilyNumber = Integer.parseInt(in.nextLine());
List<String> list = Arrays.asList(boy, girl);
while (RunCount < FamilyNumber) {
randNum = (int)(Math.random() * 1 + 0);
randNum2 = (int)(Math.random() * 1 + 0);
FirstGender = list.get(randNum);
SecondGender = list.get(randNum2);
GenderValues = FirstGender + SecondGender;
if (GenderValues == "BG" || GenderValues == "GB") {
BGCount++;
}
else if (GenderValues == "GG") {
GGCount ++;
}
else {
BBCount++;
}
RunCount++;
}
GGPercent = ((double)(GGCount/FamilyNumber)*(100));
BGPercent = ((double)(BGCount/FamilyNumber)*(100));
BBPercent = ((double)(BBCount/FamilyNumber)*(100));
System.out.println("Number of Families with: \n");
System.out.println("\tTwo Boys: " + BBCount + " Represents " + BBPercent + "%");
System.out.println("\tTwo Girls: " + GGCount + " Represents " + GGPercent + "%");
System.out.println("\tOne Boy and One Girl: " + BGCount + " Represents " + BGPercent + "%");
This is the segment of code the issue is in. I already initialized all the variables and imported everything necessary. The problem is, whenever I run the program, I get this output:
Composition Statistics for Families with Two Children:
Total Number of Families:
15
Number of Families with:
Two Boys: 15 Represents 100.0%
Two Girls: 0 Represents 0.0%
One Boy and One Girl: 0 Represents 0.0%
The output is always two boys make up all the families. I'm assuming that the issue is with randNum and randNum2 variables, but I'm really not sure. I have no idea what to do so any input on where I'm going wrong is greatly appreciated.
Math.random returns a number between 0 and 1.
So when cast to an int it will be always 0.
Select a scaling factor and multiply the result (lets say 5)
and then the result will an int in the range 0-4

How to optimally distribute multiset into submultisets with a given sum

There is a sorted multi set of N integers where N<26, for example:
[1x4,2,5x2,6x2,15,55]
And some sum - for example 10. I would like to get maximum number of sub multi sets from above set that are at least equal to given sum. For example:
[1x3 + 2 + 5] = 10 - first sub multi set
[5 + 6] = 11 - second multi set
[15] - third multi set
[55] - fourth multi set
1,6 - leftovers.
(but as you can see this is not the only answer).
What is the best way to approach this problem? I'm trying to solve this problem in java but any solution with explanation would be appreciated.
Edit:
Currently I am trying below approach:
Create single element multi sets that are higher or equal too sum. Remove them from original set.
Find 2 element sub multi sets that are exactly equal to sum. Remove them from original set <- I'm at this point
And now I do not know how to progress or is my approach correct.
The question is in which point should I start accepting sub multi sets that are higher than sum and how to check if this wont cause loss of some multi sets that would be possible to create otherwise?
For now I have something like this:
private static String findAndRemoveMultisetsEqualTo(SortedMultiset<Integer> numbers, int searchForSum) {
String answer = "";
if (numbers.lastEntry().getElement() >= searchForSum) {
answer += "\nSet of " + searchForSum + " [" + numbers.lastEntry().getElement() + "]";
numbers.remove(numbers.lastEntry().getElement());
answer += " => " + String.valueOf(numbers);
return answer;
} else {
answer += findAndRemoveExactPairSumInMultiSet(numbers, searchForSum);
}
return answer;
}
private static String findAndRemoveExactPairSumInMultiSet(SortedMultiset<Integer> numbers, final int searchForSum) {
String answer = "";
List<Integer> tempList = numbers.stream().filter(number -> number <= (searchForSum / 2)).collect(Collectors.toList());
for (Integer number : tempList) {
if (numbers.contains(searchForSum - number) && (!number.equals(searchForSum - number))) {
answer += "\nSet of " + searchForSum + " [" + number + "," + (searchForSum-number) + "]";
numbers.remove(number);
numbers.remove(searchForSum - number);
answer += " => " + String.valueOf(numbers);
} else if (number.equals(searchForSum - number) && numbers.contains(number) && numbers.count(number) > 1) {
answer += "\nSet of " + searchForSum + " [" + number + "," + number + "]";
numbers.remove(number, 2);
answer += " => " + String.valueOf(numbers);
}
}
return answer;
}

How would I pass a variable through to a class, then back out to the class it was defined in with a different value?

I'm coding a "Nim" program for one of my classes inwhich a random number of rocks is generated, then the player and computer take turns removing 1-3 rocks from the pile. The player to remove the last rock loses.
However, no matter what the code generated for the computer inside the method, it would always return 0, and as such say the computer removed 0 rocks from the pile.
(It also may help to know that these are two separate files.)
//code code code...
System.out.println("You take " + playertake + " stones. There are " + rockCount + " left");
int computerTake = 0;
nimMethods.computerTake(computerTake);
rockCount = rockCount - computerTake;
System.out.println("The computer takes " + computerTake + " stones. There are " + rockCount + " left");
Here is my methods file :
public class nimMethods
{
static int computerTake(int y)
{
y = (int)(Math.random()*((1 - 1) + 3 + 1)); //randomly generating a value between 1-3
return(y);
}
}
I have a strong belief that this a logic error, and is coming from my lack of knowledge on methods. But people don't seem to be asking this question where I look.
Could someone give me a hand? And also explain your answer, i'd like to learn.
Thanks!
You should do:
computerTake = nimMethods.computerTake(computerTake);
The value of computerTake is not being changed in your code, so it stays 0 as initialized.
Not sure why your computerTake() method takes a parameter though.
That makes the code as follows:
System.out.println("You take " + playertake + " stones. There are " + rockCount + " left");
int computerTake = 0;
computerTake = nimMethods.computerTake();
rockCount = rockCount - computerTake;
System.out.println("The computer takes " + computerTake + " stones. There are " + rockCount + " left");
and
public class nimMethods
{
static int computerTake()
{
int y = (int)(Math.random()*((1 - 1) + 3 + 1)); //randomly generating a value between 1-3
return(y);
}
}
This is because Java is Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value.
So you cannot see "changed" value of y oustide your computerTake method because the value of y was copied.
To fix it you can just replace the value of computerTake with your method result which you've returned
computerTake = nimMethods.computerTake(computerTake);

Java printing a string containing multiple integers

Just starting learning java today and can't seem to figure this out. I am following the tutorial on learnjavaonline.org which teaches you a few things and then asks you to write a code to do a specific thing, it then checks the output to see if its correct. The thing is, if its not correct, it doesn't say why, or give you an example of the correct code.
It wants me to output a string saying "H3110 w0r1d 2.0 true" using all of the primitives
i came up with this
public class Main {
public static void main(String[] args) {
char h = 'H';
byte three = 3;
short one = 1;
boolean t = true;
double ten = 10;
float two = (float) 2.0;
long won = 1;
int zero = 0;
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
System.out.println(output);
}
}
but it outputs 86.0 w0r1d 2.0 true
how can i make it so it doesn't add all the integers, but displays them consecutively?
The problem with this line:
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
is that operations are performed left to right, so it first sums h + three (which evaluates to an int) and then one and then ten. Up to that point you have a numerical value (an int) that then will be "summed" to a String. Try something like this:
String output = "" + h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
In this second case your expression will start with a String object, evaluating the rest of the operations as Strings.
You of course could use "" at the beginning or any other value that evaluates to String, like String.valueOf(h). In this last case you wouldn't need to use String.valueOf() for the other operands, as the first one is already a String.
You can either convert your numbers into a string using the toString or valueOf methods of the wrapper classes (guess you are not there yet), or just stuff all your primitives into the printline without the String output.
system.out.println(h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t);
All you need to look for is that there is a String in the printline statement. Meaning if you only want to print our number based datatype you can use system.out.println("" + youNumberVariable).
There would also be the option to add an empty string at the beginning of your declaration of output output = "" + theRest; to force all following values into the string like it does in the printline statement.
Most of it is not very pretty coding but will completly suffice for the learning process.
An easy and ugly way to do this would be to use String.valueOf for each numerical value.
As in:
String output = h + String.valueOf(three); // + etc...
Edit
morgano's approach is perfectly valid as well - +1 for that.
On a more general topic, you might want to use String.concat for String concatenation, or even better, a StringBuilder object.
This SO page contains a lot of info you can use on the matter.
I would use String.valueOf to explicitly cast each numeric value to String before being added. Like so:
String output = h + String.valueOf( three ) + String.valueOf( one ) + String.valueOf( ten ) + " " + "w" + String.valueOf( zero ) + "r" + String.valueOf( won ) + "d " + String.valueOf( two ) + " " + t;
The trick is to get the compiler to interpret + as string concatenation (which then silently convert the numbers to strings) instead of adding two numbers. This mean that one of the two arguments to + must be a string, and not - as your first three arguments - numbers (and yes, a char is a number).
It is not typical in code in the wild to want numbers to be directly adjacent to each other, but have a space between them, like:
String output = h + " " + three + " " + one + " " + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
If you really want to have no spaces, then just let the first argument be the empty string:
String output = "" + h ....
You could also just change h from char to String.
The result you're getting is because, essentially, you're doing arithmetical operations on numeric variable before printing them when relying on implicit casting.
Even the Char is a numeral! H has the value 72 in the ascii table, so you are basically instructing the Java program to print the result of:
72 + 3 + 1 + 10.0 (which is equal to 86.0)
String concatenation with mixed inputs of numerals and symbols like this can be problematic since implicit casting is in play.
In order to make sure stuff is as you want, without using explicit casting, maybe use either strings between each numeric value, like this:
char h = 'H'; // This is a numeral! Capital H has value 72 in Ascii table
byte three = 3;
short one = 1;
boolean t = true; // not a numeral
double ten = 10;
float two = (float) 2.0;
long lOne = 1;
int zero = 0;
System.out.println(h + "" + three + "" + one + "" + (int) ten + " w"
+ zero + "r" + lOne + "d " + two + " " + t );
Note how I needed to cast ten to the int-type, to lose the decimal...
Above example is however not a good example of using string concatenations!
For a proper solution, and this is maybe more aimed at people with more experience, is to try using String formatting, like this:
System.out.println(String.format("%s%s%s%s w%sr%sd %s %s", h, three, one,
(int) ten, zero, lOne, two, t));
Another way is to use message formatting like this, maybe not the best choice for this assignment since the float will be printed as an integer. Also needs to import java.text.MessageFormat
// please note: the double and the float won't print decimals!
// note: import java.text.MessageFormat for this
System.out.println(MessageFormat.format("{0}{1}{2}{3} w{4}r{5}d {6} {7}", h,
three, one, (int) ten, zero, lOne, two, t));
More examples from the Ascii table.
public class Main {
public static void main(String[] args) {
int b = 3110;
int d = 0;
String e = "orld";
double f = 2;
boolean g = true;
System.out.println("H" + b + " " + "w" + d + e + " " + f + " " + g);
}
}

Java Reading Lines and Doing Math Equations

So I have this project to do, that I need to read a text file named Input, and I'm doing it like this:
public static void textParser() {
File inputFile = new File("Input.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
String inputsText;
while ((inputsText = br.readLine()) != null) {
System.out.println(inputsText);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and it works. Inside of Input.txt, it shows:
6
10 + 4
12 - 3
1000 / 50
9 * 64
2^5
90 % 8
1 + 1
6 * 4
The first line (6) will always be the amount of equations to-do, can be different than 6.
Then I have to do how many equations the first line says to, how would I go on doing that? Thanks!
You need to write a parser. Without doing your homework for you this is the pseudo-code that should be sufficient:
for line in ReadFile()
{
for token in split(line,expression)
{
if token is digit
digits.enqueue(token)
if token is symbol
symbols.enqueue(token)
}
for element in digits,symbols:
applySymbol(firstDigit,secondDigit,symbol)
}
I've solved this problem a couple times in different languages. Look into the Shunting-yard algorithm
Basically you push and pop operators and operands onto a priority queue. You're basically converting infix to post-fix. Once your equation is in post-fix notation its much easier to solve.
If you don't have order of precedence to worry about the problem is much simpler but can still be solved by the same approach.
Edit:
We humans use in fix notation:
3 + 5 - 1
The operators are between the operands.
In Post fix notation looks like this:
3 5 + 1 -
The operators appear after the operands. Equations written this way are easy to evaluate. You just push operands onto a stack, then evaluate the last 2 using the next operator. So here, you'd push 3, and 5 onto a stack. Then you encounter + operator, so you add 3 and 5, get 8. Push 8 onto stack. now you read 1. Push 1 onto stack. Now you read -. Subtract 8 from 1. You get an answer of 7.
The shunting yard algorithm tells you how to convert between infix to post fix.
Good luck!
An option would be using ANTLR to generate a parser, this tutorial pretty much covers what you're trying to do
First you need to store them in a array of strings
Then get the first element in the array and convert it to an integer.
Based on the integer value the loop has to be iterated. so loop is formed. now you need to start reading the string array from the next index.
For doing the arithmetic operations first you need to have an array of 4 chars '+','-','*','%'
split the string based on the char array. this you can do it as a separate function. since for everytime it needs to get called. for performance i am saying.
Then you will get the two values parsed and their operator which splits them.
now you can perform the arithmetic operations.
thats it you got the required.
I have finally figured it out a different way that works, here is how I'm doing it:
public static void textParser() {
File inputFile = new File("Input.txt");
try {
Scanner scanner = new Scanner(inputFile);
int numberOfQuestions = Integer.parseInt(scanner.next());
for (int i = 1; i <= numberOfQuestions; i++) {
int firstInt = Integer.parseInt(scanner.next());
String operationSign = scanner.next();
int secondInt = Integer.parseInt(scanner.next());
if (operationSign.contains("+")) {
int answer = firstInt + secondInt;
System.out.println("Equation " + i + " : " + firstInt
+ " + " + secondInt + " = " + answer);
} else if (operationSign.contains("-")) {
int answer = firstInt - secondInt;
System.out.println("Equation " + i + " : " + firstInt
+ " - " + secondInt + " = " + answer);
} else if (operationSign.contains("/")) {
int answer = firstInt / secondInt;
System.out.println("Equation " + i + " : " + firstInt
+ " / " + secondInt + " = " + answer);
} else if (operationSign.contains("*")) {
int answer = firstInt * secondInt;
System.out.println("Equation " + i + " : " + firstInt
+ " * " + secondInt + " = " + answer);
} else if (operationSign.contains("%")) {
int answer = firstInt % secondInt;
System.out.println("Equation " + i + " : " + firstInt
+ " % " + secondInt + " = " + answer);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Thank you to everyone for helping!

Categories

Resources