Dynamic variables - java

I'm tring to assign variables dynamically, but I don't have a clue how to do that.
What my program should do:
"Write a program to have the user enter three lengths of sides and determine whether the figure is a triangle or not."
This is what I have so far:
package triangle;
import javax.swing.JOptionPane;
public class Triangle {
public static void main(String[] args) {
String x = JOptionPane.showInputDialog("Please enter the side lengths of a triangle with each side \nseparated with a ',' and without spaces. (eg. 1,2,3)");
x += ",";
int y = -1, a = 0;
double z;
for(int i = 0; i < x.length(); i++)
{
if(x.charAt(i) == ',')
{
z = Double.parseDouble(x.substring((y + 1), i));
y = i;
a += z;
}
}
}
}
What I would love to do would be to have this in the if statement:
int a++;
z(a) = Double.parseDouble(x.substring((y + 1), i));
But as I have found out this will not work and I need some kind of array. Sadly, my online class has not started arrays yet and I haven't gotten a grasp of them yet in my own learning.
I would like to make 3 variables (z1, z2, z3) and assign an integer to each one within the if statement.
Edit:
Here's some revised code that now works how I wanted now. Hope this helps someone else in the future!
package triangle;
import javax.swing.JOptionPane;
public class Triangle {
public static void main(String[] args) {
String x = JOptionPane.showInputDialog("Please enter the side lengths of a triangle with each side \nseparated with a ',' and without spaces. (eg. 1,2,3)");
x += ",";
int y = -1, a = 0;
Double[] z = new Double[3];
for(int i = 0; i < x.length(); i++)
{
if(x.charAt(i) == ',')
{
z[a] = Double.parseDouble(x.substring((y + 1), i));
y = i;
a++;
}
}
//Some test code to see if it was working
System.out.println(z[0]);
System.out.println(z[1]);
System.out.println(z[2]);
}
}

You don't need to use arrays, especially that you haven't been introduced to them. You can simply use a Scanner class, and do something similar to
Scanner in = new Scanner(System.in); // this will read from the standard system input
System.out.println("Please enter three lengths of sides: ");
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
And write some logic (I guess that's the point of your homework) checking if this figure is a triangle.
In case you would like to use arrays , you could declare one by doing:
int[] sidesLenghtsArray = new int[3];
And then instead of refering to three different int variables, you could simply refer to your array elements:
int[0] = in.nextInt();
int[1] = in.nextInt();
int[2] = in.nextInt();
Just remember - the number in the brackets is the number of elements that your array will have, but refering to that elements, you start counting from 0. That's why we start with int[0] (1st element) and end with int[2] (3rd element).

Java does not support tuple assignment like
def (a,b,c) = "1,2,3".split(",")
It is possible to do this in Java 8 with a following code:
int[] abc = Arrays.stream("1,2,3".split(",")).mapToInt(Integer::parseInt).toArray();
Here, a would be abc[0], b is abc[1].
Similar code in Java 7 could be this:
String[] abc = "1,2,3".split(",");
int a = Integer.parseInt(a[0]);
int b = Integer.parseInt(a[1]);
int c = Integer.parseInt(a[2]);

The very basic idea is that in every triangle when you add the lengths of two sides, the resulting length should be greater than the length of the remaining sides. Let's say a, b, c are the sides of the triangle.
public static void main(String[] args){
int a=3, b=4, c=5;
if(a+b > c && a+c>b && c+b>a){
System.out.println("This is a valid trianlge");
}
else{
System.out.println("This is not a valid triangle");
}
}
make sure you replace the values of a,b, and c with the values you gain from user input.

Related

Mergesort Hull using Java

I have a class Hull that has one method call update:
public void update(String input) {
String[] array = input.split(" ");
int xCoordinate1= Integer.parseInt(array[0]);
int xCoordinate2 = Integer.parseInt(array[1]);
int yCoordinate = Integer.parseInt(strArr[2]);
String newline = System.getProperty("line.separator");
System.out.println(newline + input);
}
My mainclass page has MergeHulls and main method as such:
public static Hull mergeHulls(Hull hull1, Hull hull2) {
int a=0;
int b=0;
ArrayList<Hull> array1 = new ArrayList<Hull>();
ArrayList<Hull> array2 = new ArrayList<Hull>();
ArrayList<Hull> finalArray = new ArrayList<Hull>();
return (not sure);
}
I roughly do know how to implement the method but am unsure how to get it in the codes. I will write the psudeo code and if someone can help me see if this is correct and how to go about doing it.
int a = 0
int b = 0
While (both arraylists are not null)
{
if (hull1a <= hull2b)
{
then append hull1a to finalarray and increment i
}else
{
append hull2b to finalarray and increment j
}
Question here is if I have a collection of three coordinates in my hull as such:
(0,1,2)
(1,2,3)
(2,3,4)
How do I compare the second x coordinate of the previous interval and with the first x coordinate of the current interval and sort and merge them together?
Please teach me or help me with some references. Really appreciate it.

How to use previous parameter from array in for loop

I have been try to code this, to increment the user input by 33 if the input is "31" or more up to the input or "90", and I have hit a wall where I want to use the user input from the array but I cannot. Could anyone help? Thank you.
if (choice.equals("R")) {
System.out.println("You have selected to draw a Rectangle!");
System.out.println("Please enter the Height and Width of the rectangle that is within 30cm - 90cm: ");
int[] array = new int[2];
int[] array2 = new int[2];
Scanner scan = new Scanner(System.in);
String line1 = scan.nextLine();
String[] numbers1 = line1.split(" ");
for(int i=0;i<numbers1.length;i++){
array[i] = Integer.parseInt(numbers1[i]);
}
I am trying to make a method to be able to easily call upon it later on, but that's the problem as I cannot complete my calculation.
public static void timeTurn (int a, int b) {
for(int i = 1000; i < 3001; i+= 33) {
if(numbers1.equals(>=30)) {
}
}
}
int[] array2 = new int[2]; is useless here.
By the way, please do not name a variable "array" or "array2". It's hard to understand for others and for yourself in the future.
if you defined the "array"s length to 2, then this for loop for(int i=0;i<numbers1.length;i++){...} is meaningless cause you already defined that you can only have two integers in this array.
I do not know the meaning of "convert cm to milliseconds" since one is distance and the other is time...
I can not understand (int a, int b) what "a", "b" means.
by my understanding the second code should be:
public static void timeTurn (int[] length) {
int minMillsecond = 1000;
int maxMillsecond = 3001;
int gap = 33;
for(int len : length){
if (30 <= len <= 90){
len += minMillsecond;
while(len < 3000){ len+=gap;}
print len;
}
}
}

Array not returning strings

This is assessed work so please don't give the answer, just advice!
I'm trying to get my program to return the strings pass, compensation pass or fail depending on the values inputted by the user. However, it's not returning the values and I'm receiving an error for 'weighting'. Earlier it was working, however not in a suitable way because it wouldn't always return the correct before results. I added the array because i think that's what is needed, but now I'm just getting an error. Cheers.
enter code here
public class MarkCalculator {
static int[] marks = new int[12];
static int[] weighing = new int[6];
// public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int weighting;
int coursework;
int exammark;
for (int i = 0; i < marks.length / 2; i++) {
System.out.println("Please enter course work weighting");
weighting = kb.nextInt();
weighing[i] = weighting;
}
for (int i = 0; i < marks.length / 2; i++) {
System.out.println("Please enter course work mark ");
coursework = kb.nextInt();
marks[i] = coursework;
}
for (int i = 0; i < marks.length / 2; i++) {
System.out.println("Please enter exam mark ");
exammark = kb.nextInt();
marks[i + 6] = exammark;
}
System.out.println("Calculating Marks");
MarkCalculator mc = new MarkCalculator();
String[] results = mc.computeMarks(marks, weighing);
for (String result : results) {
System.out.println("Results are " + result);
}
}
public String[] computeMarks(int[] marks, int[] weighing) {
int[] formula = new int[12];
String[] results = new String[weighing.length];
for (int i = 0; i < weighing.length; i++) {
int exam = marks[i];
int cw = marks[i+weighing.length];
int weight = weighing[i];
formula [i]= ((cw + weight) + (exam * (100 - weight)) / 100);
if ((formula[i]<=39) && (formula[i] > 35)) {
results[i] = "COMPENSATION PASS";}
else if (formula[i] >= 40) {
results[i] = "PASS";
}
else {
results[i] = "FAIL";
}
}
return results;
}
public static void computeResult (int[] coursework, int[] exammark)
{
computeResult(coursework,exammark);
}
}
Was posted as comment:
You could separate the marks into two arrays which will be easier to debug? Also it seems like you might be going over the array index for weightings on this line
for (int i = 0; i < marks.length;i++)
{
int exam = marks[i];
int cw = marks[i];
int weight = weighing[i]; // Error is here
//...
}
Because "weighing" has a range 0-5 and you are cycling through to 0-11 (with the marks array)
weighting and marks are different length arrays, yet you are doing the loop
for (int i = 0; i < marks.length; i++)
which will go out of bounds for weighting when i > 5.
It looks like you need to do something like this:
for (int i = 0; i < weighting.length; i++) {
int cw = marks[i];
int exam = marks[i+weighting.length];
int weight = weighing[i];
But that will depend on how you are storing the marks for the cw and exam in the marks array. I would recommend creating separate arrays for cw and exam as these are different items and will make things a lot easier to read and debug for yourself.
As you've asked for tips to improve your program as well, without specific code, then I would consider doing the following:
1) Have separate arrays for exam and cw marks. You're making it hard for yourself to debug your program by concatenating them together and this is also the source of your error.
2) Assuming that you always have the same number of exams as you do cw elements then I would consider having a class variable in MarkCalculator that stores the number of tests. Something like this:
private static int NUM_TESTS.
This way you can initialise arrays like this:
private static int[] examMarks = new int[NUM_TESTS]
and you can do the looping in computeMarks like this:
for (int i = 0; i < NUM_TESTS; i++)
This way if you decide you want more tests you only have to update the code in one place. It would also be easy to change your program so that the user could define how many tests should be calculated.
3) Where you have:
weighting = kb.nextInt();
weightings[i] = weighting;
replace it with:
weightings[i] = kb.nextInt();
as the variable weighting only seem to be used in this place and is therefore unnecessary. This will result in fewer operations the program has to perform and reduces the amount of code on the screen. In practice the compiler will likely remove this redundant variable, but it is good practice to think about how many operations you are performing and which of them aren't necessary.
4) It's better practice to explicitly set access modifiers on fields in a class. So you should have:
'private static int[] weightings = new int[NUM_TESTS];`
If you want to access it from another class you would then typically specify a getter method like so:
public int[] getWeightings() { return weightings; }
5) This is less important, but I would move main to the bottom of the class. In Java it's more typical to see the classes fields first, then the constructor, then public methods, then private methods and have the main at the bottom. In large projects it helps keeping to good style as it makes the code easier to read and understand.
These reference might help you learn more:
Java Coding Style Guide
Oracle Tutorial on access-modifiers
You will encounter an error as "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6"
This is because in method computeMarks. The length of marks (int[]) is 12.
and you just declare a variable with length 6 to handle:
int[] formula = new int[6];
when variable i in for loop reaches 6. The following code will throw out an error.
formula [i]= ((cw + weight) + (exam * (100 - weight)) / 100);
Have a try to declare it with length of 12.
int[] formula = new int[12];
Just paste code for method computeMarks.
public String[] computeMarks(int[] marks, int[] weighing) {
int[] formula = new int[12];
String[] results = new String[weighing.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < weighing.length; i++) {
sb.setLength(0);
int exam = marks[i];
int cw = marks[i + weighing.length];
int weight = weighing[i];
formula[i] = ((cw + weight) + (exam * (100 - weight)) / 100);
if ((formula[i] <= 39) && (formula[i] > 35)) {
sb.append("COMPENSATION PASS");
} else if (formula[i] >= 40) {
sb.append("PASS");
} else {
sb.append("FAIL");
}
sb.append(" cw mark is ").append(cw).append(" and exam mark is ")
.append(exam);
results[i] = sb.toString();
}
return results;
}

How to change 2d array by input?

I have a 2D array of 5 rows and 5 columns, all filled with the value 0. How can I make my program do this:
Enter any random combination of row and column like 2-5, without the [] brackets. Just typing 2-5 should be enough to make my program understand I mean row 2 column 5
Assign value I enter to said array in row-column combination.
This is what I got so far. As you can see I have only managed to output the values of all array elements.
import java.util.*;
public class stink {
public static void main(String[]args){
int[][] kuk = new int[5][5];
printMatrix(kuk);
}
public static void printMatrix(int[][] matrix)
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[row].length; col++)
System.out.printf("%2d", matrix[row][col]);
System.out.println();
}
}
}
you should use Scanner class from java API to get the inputs from the user like in the below code.
pass the inputs with a delimiter like if you want to have 2X3 array pass like 2-3 where '-' is a delimiter.
here are the links for String the and scanner java API.
Scanner sc = new Scanner(System.in);
System.out.println("please enter two numbers");
String inputs = sc.next();
int a=Integer.valueOf(inputs.split("-")[0]);
int b=Integer.valueOf(inputs.split("-")[1]);;
System.out.println(a + " " + b);
int[][] x = new int[a][b];
System.out.println(x.length);
this is not a copy/paste ready answer, but it should at least give you an indication on how you could handle this.
int rows = 0;
int columns = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Rows: ");
rows = scan.nextInt();
System.out.println("Columns: ");
columns = scan.nextInt();
int[][] kuk = new int[rows][columns];
import java.util.*;
public class stink
{
public static void main(String[]args)
{
int[][] kuk = new int[5][5];
// Where x and y are keys, integer is the integer you want to push
pushIntoMatrix(kuk, x, y, integer);
//kuk = pushIntoMatrix(kuk, x, y, integer); // Use if you want the method to return a value.
}
public static void pushIntoMatrix(int[][] matrix, int x, int y, int integer)
//public static int[][] pushIntoMatrix(int[][] matrix, int x, int y, int integer) // Use if you want to return the array.
{
matrix[x][y] = integer;
//return matrix; // Use if you want to return the array.
}
}
Since as you know, any data type in Java that's not a primitive is a reference, passing the kuk array into the method would affect the actual array reference. You can set a return in pushIntoMatrix() if you want, but you don't have to.

Count how many times an element occurs in an array - Java

I recently made a very simple practice program in Python, that takes user input and rolls dice. The code is:
import random
import sys
import math
def roll(rolls, sides, results):
for rolls in range(1, rolls + 1):
result = random.randrange(1, sides + 1)
print result
results.append(result)
def countf(rolls, sides, results):
i = 1
print "There were", rolls, "rolls."
for sides in range(1, sides + 1):
if results.count(i) != 1:
print "There were", results.count(i), i,"s."
else:
print "There was", results.count(i), i
i = i + 1
if i == sides:
break
rolls = input("How many rolls? ")
sides = input("How many sides of the die? ")
results = []
roll(rolls, sides, results)
countf(rolls, sides, results)
(actually this is part of a larger program, so I had to cut'n'paste bits, and I might have missed something out).
And so I decided to translate that to Java. Notice the algorithm here: get random number, print it, append it to an array, then count the amount of each number in the array at the end, and print out that value. Problem is, I don't know how to do the equivalent of someArray.count(someIndex) in Java syntax. So my Java program looks like this so far:
import java.util.*;
public class Dice {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random();
int[] results = new int[TIMES_TO_ROLL];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt(6);
System.out.println(result);
results[i] = result;
}
}
public static int getInt(String prompt) {
System.out.print(prompt + " ");
int integer = input.nextInt();
input.nextLine();
return integer;
}
}
So can someone help me with the array counting code? I understand that this might not be a defined method, since Python is higher level after all, so I could make my own array counting method, but I was wondering if Java, like Python, has a predefined one.
EDIT: I managed something like this:
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
else {
amt = amt;
}
}
return amt;
}
EDIT: Just out of interest, assuming I use Command prompt to run my Java program and Python.exe (command prompt console for Python), which one will be faster (in other words, for the same code, which language has better performance?)?
You could use a HashMap to store the result.
If the new number is not in your map you add it with "1" as initial value.
If it exists your put "+1" to the current map value.
To display the values you just have to iterate on you entries in a for each loop.
The solution is to transform your array to a List and then use the Collections.frequency method:
List<Integer> resultList = Arrays.asList(results);
int freq = Collections.frequency(resultList, 4);
Also you could use ArrayList from the very beginning saving you the transformation:
List<Integer> result = new ArrayList<Integer>();
// add results
int freq = Collections.frequency(result, 4);
See the Collections documentation here
EDIT: If performance is an issue (as suggested in the comments) then maybe you want to use each index of the array as a counter, as follows:
Random flip = new Random(SIDES);
int[] counters = new int[SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
counters[result] = counters[result]+1;
}
Notice that you no longer need to count at the end since you've already got all the counters in the array and there is no overhead of calculating the hash.
There are a couple libraries that will do this for you:
Google Guava's MultiSet
Apache Common's Bag
But for something so simple, you may consider an extra library a bit excessive.
You can also do this yourself with an int[]. Assuming your dice is using whole numbers, have the number rolled refer to the index into the array, and then increment the value at that index. When you need to retrieve the value for a given number, look up its value by the index.
private static final int NUMBER_DICE_SIDES = 6;
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random(NUMBER_DICE_SIDES);
int[] results = new int[NUMBER_DICE_SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
System.out.println(result);
results[result]++;
}
for(int i = 0; i < NUMBER_DICE_SIDES; ++i) {
System.out.println((i+1)+"'s: " + arraysCount(results, i));
}
}
public static int arrayCount(int[] array, int item) {
return array[item];
}
There's a frequency method in collections
int occurrences = Collections.frequency(listObject, searchItem);
Java doc for collections
As far as I am aware, there is no defined method to return the frequency of a particular element in an array. If you were to write a custom method, it would simply be a matter of iterating through the array, checking each value, and if the value matches the element you're after, incrementing a counter.
So something like:
// in this example, we assume myArray is an array of ints
private int count( int[] myArray, int targetValue) {
int counter = 0;
for (int i = 0 ; i < myArray.length; i++ ) {
if (myArray[i] == targetValue) {
counter++;
}
}
return counter;
}
Of course, if you want to find the frequency of all the unique values in your array, this has the potential of being extremely inefficient.
Also, why are you using a 7-sided die? The Random nextInt() will return a number from 0 up to but not including the max. So your die will return values from 0 through 6. For a six-sided die, you'd want a new Random(6); and then increment your roll by one to get a value from one through six: flip.nextInt() +1;.
class FindOccurrence {
public static void main (String[]args) {
int myArray[] = {5, 8, 5, 12, 19, 5, 6, 7, 100, 5, 45, 6, 5, 5, 5};
int numToFind = 5;
int numberOfOccurrence = 0;
for (int i=0; i < myArray.length; i++) {
if (numToFind == myArray[i]) {
numberOfOccurrence++;
}
}
System.out.println("Our number: " + numToFind);
System.out.println("Number of times it appears: " + numberOfOccurrence);
}
}

Categories