Jump to content

Need help creating some basic java programs.

suchamoneypit

Im in a beginners Java Programming class. I was doing well for the beginning of the class, but slowly started falling behind once we started learning loops and arrays. I have several short programs that I was wondering if people could code, preferably with comments the describe how the program works. The programs are meant to made as simple as possible, and made primarily using arrays.Im not looking for someone to do my work for me to pass in , I honestly want to learn how to do this and how others are doing it. I tend to understand new stuff once I've actually seen someone implement it, but thats not how my teacher teaches, she just verbally explains it and shows some slides, then lets us off to figure it out. I've tried looking online for help, but almost all suggestions implement code that I've never seen/used.The docs with the directions are attached. Im working off of Eclipse.

Project Deadly Desert Map.doc

Project Histogram.doc

Worksheet Arrays and Methods.doc

Gaming - Ryzen 5800X3D | 64GB 3200mhz  MSI 6900 XT Mini-ITX SFF Build

Home Server (Unraid OS) - Ryzen 2700x | 48GB 3200mhz |  EVGA 1060 6GB | 6TB SSD Cache [3x2TB] 66TB HDD [11x6TB]

Link to comment
Share on other sites

Link to post
Share on other sites

I don't want to do your homework for you, but if you attempt the problems and post what problems you run into I'm happy to help. If you feel you don't know enough to even start on a problem I recommend you take a look at the Java course on Code Academy

 

I recommend starting with problem 1 in Worksheet – Methods and Arrays. I'll start you off:

import java.util.Scanner;public class Test {    public static void main(String[] args) {        int[] num = new int[10]; // An array of length 10 that will store the users input                // We now need to populate the num array with 10 numbers from the user        // Getting input from the user can be done using a Scanner object. Refer to https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html for more information        // From that page you can see that reading input from the user can be done in the follow way:        Scanner sc = new Scanner(System.in);        num[0] = sc.nextInt(); // Get the first number from the user. This needs to be repeated 10 times                // We now need get the users favorite number. This can also be done with the Scanner        // You may want to print a message to the user asking for their favorite number. See http://www.javawithus.com/tutorial/displaying-information-using-print-and-println-methods        // PUT CODE HERE                // Now that we have the 10 numbers and the user's favorite, we need to count the occurrences of favorite in num        int countOfFavorite = Favorite(favorite, num);                // We now need to print a message to the user saying how many times the favorite was found.        // See http://www.javawithus.com/tutorial/displaying-information-using-print-and-println-methods        // PUT CODE HERE    }        public static int Favorite(int favorite, int[] num) {        // We need to loop over all of the numbers in the num array and count how many times we encounter favorite        // First we need an int to keep track of how many times we have seen the favorite number:        int count = 0;                // Then we need to loop over all the numbers in num. See http://java67.blogspot.ca/2013/08/how-to-iterate-over-array-in-java-15.html        // During the loop we need to check if the number in the array is equal to favorite. If it is, we need to increment count.        // PUT CODE HERE                // Then we return count        return count;    }}
Link to comment
Share on other sites

Link to post
Share on other sites

 

I don't want to do your homework for you, but if you attempt the problems and post what problems you run into I'm happy to help. If you feel you don't know enough to even start on a problem I recommend you take a look at the Java course on Code Academy

 

I recommend starting with problem 1 in Worksheet – Methods and Arrays. I'll start you off:

import java.util.Scanner;public class Test {    public static void main(String[] args) {        int[] num = new int[10]; // An array of length 10 that will store the users input                // We now need to populate the num array with 10 numbers from the user        // Getting input from the user can be done using a Scanner object. Refer to https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html for more information        // From that page you can see that reading input from the user can be done in the follow way:        Scanner sc = new Scanner(System.in);        num[0] = sc.nextInt(); // Get the first number from the user. This needs to be repeated 10 times                // We now need get the users favorite number. This can also be done with the Scanner        // You may want to print a message to the user asking for their favorite number. See http://www.javawithus.com/tutorial/displaying-information-using-print-and-println-methods        // PUT CODE HERE                // Now that we have the 10 numbers and the user's favorite, we need to count the occurrences of favorite in num        int countOfFavorite = Favorite(favorite, num);                // We now need to print a message to the user saying how many times the favorite was found.        // See http://www.javawithus.com/tutorial/displaying-information-using-print-and-println-methods        // PUT CODE HERE    }        public static int Favorite(int favorite, int[] num) {        // We need to loop over all of the numbers in the num array and count how many times we encounter favorite        // First we need an int to keep track of how many times we have seen the favorite number:        int count = 0;                // Then we need to loop over all the numbers in num. See http://java67.blogspot.ca/2013/08/how-to-iterate-over-array-in-java-15.html        // During the loop we need to check if the number in the array is equal to favorite. If it is, we need to increment count.        // PUT CODE HERE                // Then we return count        return count;    }}

what type of code would I use to search the array for a specific number? I made the first half but that's where I got stuck on that program. Also, on the Project Dead Desert program, I know it will be a 2D array, but what type of code would I use in order to find these "hot spots", as I not only need to read specific elements of an array, but in the arrays above and below it and add to determine the "hot spots".

 

thank you taking the time to help.

Gaming - Ryzen 5800X3D | 64GB 3200mhz  MSI 6900 XT Mini-ITX SFF Build

Home Server (Unraid OS) - Ryzen 2700x | 48GB 3200mhz |  EVGA 1060 6GB | 6TB SSD Cache [3x2TB] 66TB HDD [11x6TB]

Link to comment
Share on other sites

Link to post
Share on other sites

what type of code would I use to search the array for a specific number? I made the first half but that's where I got stuck on that program. Also, on the Project Dead Desert program, I know it will be a 2D array, but what type of code would I use in order to find these "hot spots", as I not only need to read specific elements of an array, but in the arrays above and below it and add to determine the "hot spots".

 

thank you taking the time to help.

You need to loop over every element in the array and check if the element is equal to the favorite.

 

In the example on http://java67.blogspot.ca/2013/08/how-to-iterate-over-array-in-java-15.html

they loop over an array of strings and print each string out:

String[] languages = {"Java", "Scala", "C++", "Ruby", "Python", "Perl"};for(String str : languages){     System.out.println(str); }

If we wanted to check if the element in the array equaled "C++" we could do that like this:

String[] languages = {"Java", "Scala", "C++", "Ruby", "Python", "Perl"};for(String str : languages){     if (str.equals("C++") {        // Stuff inside this block will only be executed if str equals "C++"    } }

If we wanted to see if the array contained the word "Java" we could do that like this:

boolean containsJava = false;String[] languages = {"Java", "Scala", "C++", "Ruby", "Python", "Perl"};for(String str : languages){     if (str.equals("Java") {        containsJava = true;    } }return containsJava;

If we wanted to count the occurrences of "Ruby" in the array, we could do that like this:

int count = 0;String[] languages = {"Java", "Scala", "C++", "Ruby", "Python", "Perl"};for(String str : languages){     if (str.equals("Ruby") {        count = count + 1; // This increments count by 1    } }return count;

From the above you should be able to work out how to count the occurrences of favorite. Hint: to check if two ints are equal you need to use:

int == int

The Deadly Hot Spot problem is a lot more difficult than problem 1 in Worksheet – Methods and Arrays. You should focus on problem 1 before moving onto the Deadly Hot Spot problem.

Link to comment
Share on other sites

Link to post
Share on other sites

 

You need to loop over every element in the array and check if the element is equal to the favorite.

 

In the example on http://java67.blogspot.ca/2013/08/how-to-iterate-over-array-in-java-15.html

they loop over an array of strings and print each string out:

String[] languages = {"Java", "Scala", "C++", "Ruby", "Python", "Perl"};for(String str : languages){     System.out.println(str); }

If we wanted to check if the element in the array equaled "C++" we could do that like this:

String[] languages = {"Java", "Scala", "C++", "Ruby", "Python", "Perl"};for(String str : languages){     if (str.equals("C++") {        // Stuff inside this block will only be executed if str equals "C++"    } }

If we wanted to see if the array contained the word "Java" we could do that like this:

boolean containsJava = false;String[] languages = {"Java", "Scala", "C++", "Ruby", "Python", "Perl"};for(String str : languages){     if (str.equals("Java") {        containsJava = true;    } }return containsJava;

If we wanted to count the occurrences of "Ruby" in the array, we could do that like this:

int count = 0;String[] languages = {"Java", "Scala", "C++", "Ruby", "Python", "Perl"};for(String str : languages){     if (str.equals("Ruby") {        count = count + 1; // This increments count by 1    } }return count;

From the above you should be able to work out how to count the occurrences of favorite. Hint: to check if two ints are equal you need to use:

int == int

thank you. I will be working on the program sometime today, I will give it a go with this info.

Gaming - Ryzen 5800X3D | 64GB 3200mhz  MSI 6900 XT Mini-ITX SFF Build

Home Server (Unraid OS) - Ryzen 2700x | 48GB 3200mhz |  EVGA 1060 6GB | 6TB SSD Cache [3x2TB] 66TB HDD [11x6TB]

Link to comment
Share on other sites

Link to post
Share on other sites

Work with what has been provided with you and practice, practice, practice. I have been programming for quite some time and I still get confused by loops in some contexts... so don't worry about not getting it timmediately. The more you work with loops and such, the better you will become.

 

Link to comment
Share on other sites

Link to post
Share on other sites

what type of code would I use to search the array for a specific number? I made the first half but that's where I got stuck on that program. Also, on the Project Dead Desert program, I know it will be a 2D array, but what type of code would I use in order to find these "hot spots", as I not only need to read specific elements of an array, but in the arrays above and below it and add to determine the "hot spots".

 

thank you taking the time to help.

This is what I've worked on so far, using what you gave me and some sources from the internet.

package matthewA;import java.util.Scanner;public class MethodsAndArrays {static Random rand=new Random();	public static void main(String[] args) {		// TODO Auto-generated method stub				//PROBLEM 1 - METHODS AND ARRAYS				int arrayStatus=0; //counter for how many inputs the user has used				Scanner scan=new Scanner(System.in); //imports scanner		int [] num = new int [10];   //declares array						for (int i=0; i<=9; i++){  //loops 10 times to get 10 integers entered by the user.			System.out.println("Input an integer");			num[i]=scan.nextInt();			arrayStatus++;						System.out.println("Stored " +arrayStatus+"/10 numbers"); //outputs how many "slots" are used in array		    }						System.out.println("What is your favorite number?");	//asks for and finds out the users favorite number		int favNum=scan.nextInt();				int count=Favorite (num, favNum);  //uses the Favorite method to look for the fav num in array		System.out.println("You entered your favorite number "+count+" time."); }			public static int Favorite(int [] num, int favNum)	{		int temp, count = 0;   //makes the ints	     for( temp = 0; temp< num.length; temp++)   //loops to find fav num, if found, adds to the counter "temp" 	     {	          if (num[temp]=favNum)	             count++;	     }	     return (count);  //returns count to the main method		}	} 

I'm getting stuck in my method I'm using to search for the favorite number, its giving me an error because I'm using an int and it wants a boolean, what could i do to solve this issue?

Gaming - Ryzen 5800X3D | 64GB 3200mhz  MSI 6900 XT Mini-ITX SFF Build

Home Server (Unraid OS) - Ryzen 2700x | 48GB 3200mhz |  EVGA 1060 6GB | 6TB SSD Cache [3x2TB] 66TB HDD [11x6TB]

Link to comment
Share on other sites

Link to post
Share on other sites

This is what I've worked on so far, using what you gave me and some sources from the internet.

package matthewA;import java.util.Scanner;public class MethodsAndArrays {static Random rand=new Random();	public static void main(String[] args) {		// TODO Auto-generated method stub				//PROBLEM 1 - METHODS AND ARRAYS				int arrayStatus=0; //counter for how many inputs the user has used				Scanner scan=new Scanner(System.in); //imports scanner		int [] num = new int [10];   //declares array						for (int i=0; i<=9; i++){  //loops 10 times to get 10 integers entered by the user.			System.out.println("Input an integer");			num[i]=scan.nextInt();			arrayStatus++;						System.out.println("Stored " +arrayStatus+"/10 numbers"); //outputs how many "slots" are used in array		    }						System.out.println("What is your favorite number?");	//asks for and finds out the users favorite number		int favNum=scan.nextInt();				int count=Favorite (num, favNum);  //uses the Favorite method to look for the fav num in array		System.out.println("You entered your favorite number "+count+" time."); }			public static int Favorite(int [] num, int favNum)	{		int temp, count = 0;   //makes the ints	     for( temp = 0; temp< num.length; temp++)   //loops to find fav num, if found, adds to the counter "temp" 	     {	          if (num[temp]=favNum)	             count++;	     }	     return (count);  //returns count to the main method		}	} 

I'm getting stuck in my method I'm using to search for the favorite number, its giving me an error because I'm using an int and it wants a boolean, what could i do to solve this issue?

You're really close!

When you want to test two ints for equality you need to use:

num[temp]==favNum

What you're doing:

num[temp]=favNum

is actually assigning favNum to num[temp], which is why you get an error like "cannot convert int to boolean".

Link to comment
Share on other sites

Link to post
Share on other sites

for the histogram problem, one way to do it: 

 

I assume you are just declaring your input array in the code itself. Create and initialize another integer array of size 10 to store the counts of the numbers in each increment (0-9.. etc). Loop through the input array, if the number is less than 10 increment the count array at index 0, if it is 10-20, increment index 1.. etc. Declare your string (ie : String star = "*"), loop through the array with the counts in it and print on a new line the star string repeated the necessary amount of times. Should be easy to do with what you already know, except maybe how to repeat a string. But that is also easy to look up and learn.  

Link to comment
Share on other sites

Link to post
Share on other sites

I have recently started using Processing, it's great for learning Java and you can make some cool programs while your at it.

Oh, and it's free, and I believe it's also open source.

Main Gaming Rig:

Spoiler

Core i7-4770, Cryorig M9i Cooler, ASUS B85M GAMER, 8GB HyperX Fury Red 2x4GB 1866MHz, KFA2 GTX 970 Infin8 Black Edition "4GB", 1TB Seagate SSHD, 256GB Crucial m4 SSD, 60GB Corsair SSD for Kerbal and game servers, Thermaltake Core V21 Case, EVGA SuperNOVA 650W G2.

Secondary PC:

Spoiler

i5-2500k OCed, Raijintek Themis, Intel Z77GA-70K, 8GB HyperX Genesis in grey, GTX 750 Ti, Gamemax Falcon case.

 

Link to comment
Share on other sites

Link to post
Share on other sites

for the histogram problem, one way to do it: 

 

I assume you are just declaring your input array in the code itself. Create and initialize another integer array of size 10 to store the counts of the numbers in each increment (0-9.. etc). Loop through the input array, if the number is less than 10 increment the count array at index 0, if it is 10-20, increment index 1.. etc. Declare your string (ie : String star = "*"), loop through the array with the counts in it and print on a new line the star string repeated the necessary amount of times. Should be easy to do with what you already know, except maybe how to repeat a string. But that is also easy to look up and learn.  

thanks, that makes a lot of sense to me now, it shouldn't be hard for me to make that. 

 

You're really close!

When you want to test two ints for equality you need to use:

num[temp]==favNum

What you're doing:

num[temp]=favNum

is actually assigning favNum to num[temp], which is why you get an error like "cannot convert int to boolean".

I finished problem 1 on that worksheet now, but me and my classmate are having difficulties figuring out how we would get the strings in the array in problem two to print backwards in order to compare the word normally and backwards and determine words that are the same, in the problem the example is to check for words like "racecar" which are the same spelled backwards.  Would you have any suggestions/hints that could help me solve that?

Gaming - Ryzen 5800X3D | 64GB 3200mhz  MSI 6900 XT Mini-ITX SFF Build

Home Server (Unraid OS) - Ryzen 2700x | 48GB 3200mhz |  EVGA 1060 6GB | 6TB SSD Cache [3x2TB] 66TB HDD [11x6TB]

Link to comment
Share on other sites

Link to post
Share on other sites

You can use StringBuilder to reverse a string. Then check for equality between the two strings. 

 

http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#reverse()

 

A more efficient way would be to compare the individual characters of the string in a loop, using string.charAt(i) to obtain the character at the i-th index in the string. 

Link to comment
Share on other sites

Link to post
Share on other sites

package matthewA;public class Histogram {	public static void main(String[] args) {				int [] array = {26, 19, 45, 22, 79, 35, 21, 4, 76, 45, 56, 90, 88, 32, 45, 3, 66, 74, 77, 35, 24, 33, 42, 55, 76, 74, 88, 90};		int [] values ={0,0,0,0,0,0,0,0,0,0};														for (int i=0; i<=array.length-1; i++){					if (array [i]<10){					values [0]++;			           }				else if (array [i] > 10 && array[i] < 20){ //fills 0-10					values [1]++;				}				else if (array [i] > 20 && array[i] < 30){ //fills 					values [2]++;				}				else if (array [i] > 30 && array[i] < 40){ //fills 					values [3]++;				}				else if (array [i] > 40 && array[i] < 50){ //fills 					values [4]++;				}				else if (array [i] > 50 && array[i] < 60){ //fills 					values [5]++;				}				else if (array [i] > 60 && array[i] < 70){ //fills 					values [6]++;				}				else if (array [i] > 70 && array[i] < 80){ //fills 					values [7]++;				}				else if (array [i] > 80 && array[i] < 90){ //fills 					values [8]++;				}				else if (array [i] > 90 && array[i] < 100){ //fills 					values [9]++;				}										}				for (int j=0; j<=array.length-1; j++){										}	}} 

 

for the histogram problem, one way to do it: 

 

I assume you are just declaring your input array in the code itself. Create and initialize another integer array of size 10 to store the counts of the numbers in each increment (0-9.. etc). Loop through the input array, if the number is less than 10 increment the count array at index 0, if it is 10-20, increment index 1.. etc. Declare your string (ie : String star = "*"), loop through the array with the counts in it and print on a new line the star string repeated the necessary amount of times. Should be easy to do with what you already know, except maybe how to repeat a string. But that is also easy to look up and learn.  

I have been having trouble print "*" dependent on the values I now have stored in my secondary array. How would I code a loop to do that for each one? Here is my code:

 

Gaming - Ryzen 5800X3D | 64GB 3200mhz  MSI 6900 XT Mini-ITX SFF Build

Home Server (Unraid OS) - Ryzen 2700x | 48GB 3200mhz |  EVGA 1060 6GB | 6TB SSD Cache [3x2TB] 66TB HDD [11x6TB]

Link to comment
Share on other sites

Link to post
Share on other sites

I have been having trouble print "*" dependent on the values I now have stored in my secondary array. How would I code a loop to do that for each one? Here is my code:

 

You would need to iterate the array; for every integer encountered use a nested loop to the value of that integer to append/output a *. Use the outermost loop to deal with new line/returns.

 

A side note about your code: While it looks like it will work, and it may well do what you need (I haven't the time to try it) it is rather monolithic/static i.e. it's not going to cope with changing data. You could have a think about making things a bit more dynamic/flexible and extensible. For example, consider getting rid of all of those if elses and instead automatically detect different ranges.

The single biggest problem in communication is the illusion that it has taken place.

Link to comment
Share on other sites

Link to post
Share on other sites

You would need to iterate the array; for every integer encountered use a nested loop to the value of that integer to append/output a *. Use the outermost loop to deal with new line/returns.

 

A side note about your code: While it looks like it will work, and it may well do what you need (I haven't the time to try it) it is rather monolithic/static i.e. it's not going to cope with changing data. You could have a think about making things a bit more dynamic/flexible and extensible. For example, consider getting rid of all of those if elses and instead automatically detect different ranges.

We haven't learned how to make it detect different ranges, it would be interesting to know how to do that, would you have any examples of that? I like keeping my code as small as possible and thats really what I wanted when imagining this program.

Gaming - Ryzen 5800X3D | 64GB 3200mhz  MSI 6900 XT Mini-ITX SFF Build

Home Server (Unraid OS) - Ryzen 2700x | 48GB 3200mhz |  EVGA 1060 6GB | 6TB SSD Cache [3x2TB] 66TB HDD [11x6TB]

Link to comment
Share on other sites

Link to post
Share on other sites

In your second empty for loop you should loop over the values array (not array) and print * values[x] times
for (int j = 0; j <= values.length - 1; j++) {    // Print '*' values[j] times. This can be done using a for loop that loops from 0 to values[j].    // Remember to use System.out.print('*') and not System.out.println('*') because you want the '*'s on the same line    // After the inner for loop that prints the '*'s, you want to print a new line:    System.out.println();}

We haven't learned how to make it detect different ranges, it would be interesting to know how to do that, would you have any examples of that? I like keeping my code as small as possible and thats really what I wanted when imagining this program.

Lets say that the max number in your problem was no longer 100. It was 100,000. Would have have 10,000 if statements checking the range?

You could have a for loop that checks the range for you. values[0] equals the number of values between 0 and 10. values[1] equals the number of values between 10 and 20. values[n] equals the number of values between n * 10 and (n + 1) * 10. From that you should be able to make your for loop more concise.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×