I have to create a cross shape using methods, and the parameter is the 'size' of the cross. A number is input and the cross is drawn if the number is odd, so if I were to input a 5, the output would look like the screenshot I added to the bottom
The centre line is what's really throwing me off as I've only started methods last week, but so far I have:
import java.util.Scanner;
public class Cross {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type a number: ");
int num = keyboard.nextInt();
drawCross(num);
}
public static void drawCross(int num){
for (int = 1; i <= num; i++) {
if ((num % 2) != 0) {
System.out.println(i + "*");
}
}
}
}
I know this is probably way off, but I'm a total newbie to methods.
Analyze the problem before you start programming. Break the task into steps:
Check whether num is valid for this problem.
num must be positive.
num must be odd.
Notice that you're checking whether num is valid more than once. Check it at the beginning, and quit with an error message if num is invalid. Or, throw an exception, and have main catch it and report to the user.
After you know how to use exceptions, that is.
By the way, num is a bad name for the variable. It's too generic. Except for loop indices, try to have your name be descriptive.
Compute how many spaces must precede the * on all but the center output line.
Compute which line is the center output line.
Do a loop for the top half of the output.
Don't use System.out.println() for individual characters.
That method should be called only once per line.
Print the central line.
Do a loop for the bottom half of the output.
Now, you should try to stop doing everything in main and other static methods. Cross is a class, and you should create an instance of the class and have it do the work.
public class Cross {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type a number: ");
int num = keyboard.nextInt();
Cross cross = new Cross();
cross.drawCross(num);
}
private void drawCross(int size) {
// Your turn.
}
}
Why? So you can test it. One of the most invaluable tools in Java programming is the JUnit library. You will want to offload your logic into tiny methods like:
public boolean validSize(int size) {
// You fill this in.
}
In a test class, CrossTest, you'll write code like:
#Test
public void negativeSizesAreIllegal() {
Cross cross = new Cross();
// Test whether cross.validSize(-13) returns false.
// Look at the JUnit web site or any book describing the tool.
}
Figure out what your requirements on the method are, and write tests to check each one. You'll have similar tests too for 0, odd integers, and even integers. But if you do all your code in static methods, that's a lot harder. This way, as you change your program, you'll know whether your changes have broken your tests. It's like computing an indefinite integral, and differentiating it to check whether you made a mistake.
Finally, simplify your work. The way I outlined your problem, there will be a lot of code duplication. See if you can write a method to replace the duplicate code in steps 4 and 6, and call it twice. Keep going with it; you'll see lots of chances to shorten your program. Having tests is invaluable for that. You'll also be able to use standard methods in the java.lang.String class to simplify things further.
Did you see that
System.out.println(i + "*");
did not do what you thought it did?
Not a best solution. but this one I came up with in 2 mins time :
public static void drawCross(int num){
if (num % 2 != 0) {
for(int i = 0; i < num; i++) {
for(int j = 0; j < num; j++) {
if((i == num / 2) || (j == num / 2))
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
Here is some code that should work:
public static void drawCross(int num)
{
if(num % 2 != 0) //if "num" is odd
{
for(int y = 0; y < num; y++) //loop through the following code "num" times
{
for(int x = 0; x < num; x++) //loop through the following code "num" times
{
if(x == (int)(num / 2) || y == (int)(num / 2)) //if "x" or "y" is in the middle
/*(note that at this point "num" will always be odd, so "num / 2" will always
be #.5. That's why the "(int)" is there: to change it from "#.5" to "#"*/
{
System.out.print("*"); //print "*"
}
else //if "x" or "y" is NOT in the middle
{
System.out.print(" "); //print a space
}
}
System.out.println(); //create a new line
}
}
}
public static void drawCross(int num){
if(num % 2 != 0){
for(int line = 0;line < num;line++){
for(int col = 0;col < num;col++){
if(line == num / 2 || col == num / 2) System.out.print("*");
else System.out.print(" ");
}
System.out.println("");
}
}
}
Related
This project is all about methods and arrays and breaks down into 3 parts. Firstly, create an array. Second, fill said array with random ints. Lastly, create a method that displays whether each int is even or odd as well as provides the average of the random ints.
Java is my first programming language that i'm being introduced to in my curriculum and I've worked in this issue for about 4-5 hours now but hit a wall. I can't seem to get my statsDisplay method to perform the necessary stats on my created arrays. It appears that since it always results with alternating "even/odd", it's just creating its own array from 1-20 and analyzing that instead of the previous Math.random() array.
Is anyone able to see what might be going wrong here?
Also, this is my first ever post on here so I'm sorry if it's not formatted correctly or asked in an odd way...
public class Practicestuff {
public static void main(String[] args) {
int[] vals = new int[20];
fill(vals);
statsDisplay(vals);
print(vals);
}
public static void print(int[] array) {
for(int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
System.out.println();
}
public static void fill(int[] array) {
for(int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() *100);
public static void statsDisplay(int[] array) {
for(double i = 0; i < array.length; i++) {
if(i % 2 == 0) {
System.out.println("Number is even");
if(i % 2 != 0)
System.out.println("Number is odd");
}
}
}
In your statsDisplay() method, the i in the for loop is the index (1, 2, 3, 4...). The if statements are checking if i is odd or even. You want to be checking if array[i] is odd or even, so you should replace the i in the if statements with array[i].
I want to...
create an asterisk triangle, using Java, that matches the length of whatever number (Between 1-50) the user enters.
Details
The first line would always start with an asterisk.
The next line would increment by one asterisk until it matches the
user's input.
The following lines would then decrement until it is back to one
asterisk.
For instance, if the user was to enter 3, then the output would have one asterisk on the first line, two asterisks on the second line, three asterisks on the third line, and then revert back to two asterisks on the following line before ending with an asterisk on the last line.
What I've tried so far
I am required to use nested for loops. So far, I tried to test it out using this practice example I made below. I was only able to create on output of the numbers. I also have some concepts of outputting asterisk triangles. How can I apply the concept of this code to follow along the user's input number?
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int count, index = 0, value, number;
System.out.println("This program creates a pattern of numbers " );
System.out.println("Based on a number you enter." );
System.out.println("Please enter a positive integer. " );
count = keyboard.nextInt();
value = count;
for (index = 1; index <= count; index++)
{
for (number = value; number >= 1; number--)
{
System.out.println(number);
}
value--;
System.out.println();
}
}
}
Here's how i would proceed
write a method printAsterisks that takes an int N as parameter and writes a line of N asterisks. You wil need a for loop to do so.
call printAsterisks in a for loop that counts from 1 to COUNT
call printAsterisks in a second loop that counts down from COUNT-1 to 1
That should do the trick.
Also, as a side note, you should close your scanner. The easy way to do so is enclose ot in a try-with-resource like so :
try (Scanner keyboard = new Scanner(System.in);) {
// your code here
}
Let us know the version of the program taht works (or the question you still have) :)
HTH
Here is what you want:
public class Asterisk {
private static final String ASTERISK = "*";
private static final String SPACE = "";
private static int LENGTH;
public static void main(String[] args) {
try{
readLength();
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
}catch (Exception e) {
System.out.println("You must enter a number between 1 and 50.");
}
}
static void readLength(){
System.out.println("Enter asterisk's length (1-50)");
LENGTH = Integer.parseInt(System.console().readLine());
if (LENGTH<=0 || LENGTH>50)
throw new NumberFormatException();
}
static void drawLine(int asterisks){
StringBuilder line = new StringBuilder();
int spacesLeft = getLeftSpaceCount(asterisks);
int spacesRight = getRightSpaceCount(asterisks);
for (int i=0; i<spacesLeft; i++) {
line.append(SPACE);
}
for (int i=0; i<asterisks; i++) {
line.append(ASTERISK);
}
for (int i=0; i<spacesRight; i++) {
line.append(SPACE);
}
System.out.println(line.toString()+"\n");
}
static int getLeftSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
int mod = spaces%2;
return spaces/2 + mod;
}
static int getRightSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
return spaces/2;
}
}
I am required to use nested for loops
Yes, the main logic lies there...
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
The triangle using 5 as input.
*
**
***
****
*****
****
***
**
*
Tip:
There is an easier way to get input from the user usingSystem.console().readLine().
In regards to the printing part, I wanted to clean up the answers a little:
int input = 3; //just an example, you can hook in user input I'm sure!
for (int i = 1; i < (input * 2); i++) {
int amount = i > input ? i / 2 : i;
for (int a = 0; a < amount; a++)
System.out.print("*");
}
System.out.println();
}
For our loop conditions, a little explanation:
i < (input * 2): since i starts at 1 we can consider a few cases. If we have an input of 1 we need 1 row. input 2, 3 rows. 4: 5 rows. In short the relation of length to row count is row count = (length * 2) - 1, so I additionally offset by 1 by starting at 1 instead of 0.
i > input ? i / 2 : i: this is called a ternary statement, it's basically an if statement where you can get the value in the form boolean/if ? value_if_true : value_if_false. So if the row count is bigger than your requested length (more than halfway), the length gets divided by 2.
Additionally everything in that loop could be one line:
System.out.println(new String(new char[i > input ? i / 2 : i]).replace('\0', '*'));
And yeah, technically with a IntStream we could make this whole thing a one-line, though at that point I would be breaking out newlines for clarity
Keep in mind, I wouldn't call this the "beginner's solution", but hopefully it can intrigue you into learning about some other helpful little things about programming, for instance why it was I replaced \0 in my one-line example.
For a homework assignment, I am trying to construct a program that prints an hourglass shape to the screen using asterisks and spaces. I have written the program below, but its output doesn't look anything like an hourglass. Can anyone help me understand why my program isn't producing the expected output?
public class hourglass {
public static void main(String[] args) {
int x = Integer.parseInt(args[0]);
int k = 2 * x - 1;
int c = k;
for (int j = x; j > 0; j--) {
for (int f = j; f <= k; f++) {
System.out.print("*");
}
for (int o = 1; o <= c; o++) {
if (k % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT: I redid the program now it just prints into infinity and beyond, I understand the logic that I need to take in a x number and then run a for loop, each and every time I go through it I -1 from the x.
Can anyone help me with this please? I'm simply trying to deepen my understanding in Java.
public class hourglass
{
public static void main(String[] args)
{
int valueIn = Integer.parseInt(args[0]);
int maxVALUE = 2*valueIn ;
for( int i = 0 ; (valueIn - 1) > i; i--)
{for( int j =1 ; j < maxVALUE; i++)
{
System.out.print("*");}
for (int o = 1; o < maxVALUE; o++) {
if (maxVALUE % 2 == 0) System.out.print(" ");
else System.out.print(" ");
}
System.out.print("\n");
}
}
}
EDIT 2*
If anyone sees this well, here I go.
I've constructed a code on my own for the past 8 hours and now I'm stuck, I don't know how I can "reverse" my for loop to make it print into the other direction here's my code, I don't know what to do and if anyone can give me any insight on how to do this I would be very pleased, I tried doing an if case if(i == 0) but that never happens and I even tried making that if case ==1; but then the loop ran forever.
Any pointers on how to finish my program?
public class mathrandom
{
public static void main ( String [] args)
{
int valueIn = Integer.parseInt(args[0]);
for ( int i = valueIn; 1 <= i; i--){
for ( int k = i ; k < 2*valueIn -1; k++)
{System.out.print(" ");}
{for ( int j = 1; j <= (i*2)-1; j++)
{
System.out. print("*");
}
System.out.println();
}
}
}}
If you don't think in code (and what novice does?), you can try starting by writing a prose(-ish) description of how your program will go about its task, and then writing code that matches up to the prose. For example, you might start with:
Given an input x representing the width of an hourglass shape, print the hourglass to the screen as a series of lines containing asterisks and spaces. The number of asterisks on each line will start at x, count down by two per line until a line containing fewer than two asterisks, then count back up by two per line until it reaches x again. An appropriate number of leading spaces will be printed on each line to center that line's run of asterisks relative to the other lines' (assuming spaces are displayed with the same width as asterisks).
You can even put that into your source code as a comment. In fact, it can help to break it up into several smaller comments, so that you can follow each logical thought with code that corresponds specifically to that thought. If you do that, then not only does it help you organize your code, but you end up with a nicely-documented program without any extra effort.
If you compare my prose to your program, you should see both similarities and differences. Your program performs some kind of count-down, at each step printing zero or more space characters, some asterisks, and then a newline to end the line. Those are basically the right things for it to do, but the details are wrong. Enough wrong and oddly enough wrong, in fact, that I'm inclined to suspect that the program is more cribbed from external sources than thoughtfully constructed de novo. I suggest from here out you devote your attention to writing the program yourself. In fact, consider starting by tossing out everything in main() except int x = Integer.parseInt(args[0]);.
So, for an assignment in my computer science class, we've got to use loops, either for or while, depending on preference. Now, the assignment IS to use said loops and a given input to draw a beauteous ASCII diamond made of '$' and '-'. Say, an input of 5 would look like:
____$
___$-$
__$-$-$
_$-$-$-$
$-$-$-$-$
_$-$-$-$
__$-$-$
___$-$
____$
The underscores are to denote spaces. Now, anytime I try using
public static void main(String[] args) {
String input=JOptionPane.showInputDialog(null, "Input a number between three and ten here: ");
double length=Double.parseDouble(input);
int i=0; int j=0;
for(i=1; i<length; i++)
{
System.out.print(" ");
for(j=1; j<=i; j++)
{
if(j<i){System.out.print("-$");
}
else if(j==i){System.out.println("");}
}
}
I come out with something like, say, for input=7:
-$
-$-$
-$-$-$
-$-$-$-$
-$-$-$-$-$
And yes, the two too few in the center is true with any input. Any help?
Since this is your homework, I'm just going to point you towards the correct answer and leave you to figure out the rest. Let's try formatting your code so you can see what's going on:
public static void main(String[] args) {
String input=JOptionPane.showInputDialog(null, "Input a number between three and ten here: ");
double length=Double.parseDouble(input);
int i=0; int j=0;
for(i=1; i<length; i++){
System.out.print(" ");
for(j=1; j<=i; j++){
if(j<i){
System.out.print("-$");
}
else if(j==i){System.out.println("");
}
}
}
Now, you've got an outer loop for i ranging from 1..length-1, and for each i you're going to print a space, then you're going to count from 1 to 1 and print "-$" that many times. Then, you're going to print a newline and repeat the outer loop, incrementing i
So, the first time through the outer loop, you print one space, followed by one "-$", followed by a newline. Then on the second time through the outer loop, you print one space, followed by "-$" twice, followed by a newline. And so forth, until i=length, and then you stop.
You want to print a few more spaces before you print dollar signs - a loop here will probably be useful.
try to go trough this code and see how it works... it might be useful for your homework
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("input a number");
int number = input.nextInt();
input.close();
boolean add = true;
int counter = 0;
do {
if (add) {
counter++;
print(' ', number - counter);
print('$', counter);
if (counter == number)
add = false;
System.out.println();
} else {
counter--;
if (counter == 0)
break;
print(' ', number - counter);
print('$', counter);
System.out.println();
}
} while (true);
}
private static void print(char c, int times) {
if (c == '$')
times = (times * 2) - 1;
for (int i = 0; i < times; i++)
System.out.print(c);
}
if you edit the print method you will get your desired result
private static void print(char c, int times) {
if (c == '$')
times = (times * 2) - 1;
for (int i = 0; i < times; i++)
if (i % 2 == 1 && c == '$')
System.out.print('-');
else
System.out.print(c);
}
I'm brand new to Java and my first assignment was to implement a "for" loop. I wrote this program in C++ and it compiles in Java, but I got an error at runtime. Can anyone tell me what's wrong?
import java.util.Scanner;
import java.util.Vector;
public class GlobalMembersMain
{
public static Vector<Integer> get_prime_factors(int number)
{
Vector<Integer> primefactors = new Vector<Integer>();
for (int j = 2; j <= number; j++)
{
if (number % j == 0)
{
primefactors.add(j);
number = number / j;
j = 1;
}
}
return primefactors;
}
public static void main(String[] args)
{
int number;
int count = 1;
System.out.print("Enter integer to analyse:");
System.out.print("\n");
Scanner scan = new Scanner(System.in);
number = scan.nextInt();
Vector<Integer> primefactors = new Vector<Integer>();
primefactors = get_prime_factors(number);
System.out.print("Prime factors are ");
for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
else
{
System.out.print(primefactors.elementAt(a));
System.out.print(" (");
System.out.print(count);
System.out.print(") ");
count = 1;
}
}
System.out.print("\n");
}
}
The output:
Enter integer to analyse:
10
Prime factors are 2 (1) Exception in thread "main" java.lang.ArrayIndexOutOfBoun
dsException: 2 >= 2
at java.util.Vector.elementAt(Unknown Source)
at GlobalMembersMain.main(GlobalMembersMain.java:36)
for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
Is exceeding the size of the primefactors collection. By 2, in fact.
Change to primefactors.size() - 1 to avoid this error.
Arrays are zero based, which I imagine you are aware of. What you may not be aware of is that in Java a List is backed by an array as well. When you invoke primefactors.size() +1 you are getting one more than you would possibly want. For instance is pf is of size 1 your loop will do the following:
pf.get(0); //returns the only value in the list
pf.get(1); // element doesn't exist
Now the other thing is you do not want to use Vector, generally speaking in Java. It is a synchronized collection. What you want is List/ArrayList.
OTHER CODE ISSUES
public static Vector<Integer> get_prime_factors(int number)
this does not need to be static. Also naming convention is camel case in Java so your function name should be getPrimeFactors(int number)
GlobalMembersMain
Should most likely be named GlobalMember as classes are to be singular in nature and I believe you added Main to indicate it was the class that holds the main function.
In your main function you would do this:
GlobalMember member = new GlobalMember();
member.getPrimeFactors(number);
This is where the problem is:
for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
//...
primefactors.elementAt(a+1) for the last element in your collection will throw the exception (AIOB).
Remember that arrays, lists and vectors in Java are zero-based. In your case, the primefactors vector will consist of two elements, available at index 0 and 1 respectively.
The problem you are facing is that you try to access the element primefactors.elementAt(2) which does not exist.
One problem is the break condition in the loop:
for (int a = 0; a < primefactors.size() + 1; a++) {
// ...
}
The first time, a will be 0, the second time 1 which are both fine. However, the loop will not break the third time, because a will equal 2, which is less than primefactors.size() + 1. Consequently, there will be a call to primefactors.elementAt(2) which does not exist and the program will blow up.
There is also a second problem inside the loop since you increment the loop variable by one during the comparison:
if (primefactors.elementAt(a) == primefactors.elementAt(a+1)) {
// ...
}
Yet again, your program will fail if you pass 2 as an argument to primefactors.elementAt(...)