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);
}
Related
The goal of my code: To be able to write a program where I can enter in any number int as a command-line argument and displays how many digits in the integer number are 7s.
My problem is that I don't understand why my code only runs through the for-loop once. I inserted the system.out.println(sevens); to see how many times this loop works when I compile with a random number like 456789.
I could only think of a for-loop to use for this one and fixed some simple mistakes in the beginning. I also checked my brackets
public class TestingSevens {
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
int count = 0;
for (int i = 0; i < args.length; i++) {
if (sevens%10 == 7) {
count += 1;
}
sevens = sevens/10;
System.out.println(sevens);
}
System.out.println(count);
}
}
The result of inputting a number like 456789 is "45678" for the first print and the second print is "0." I know the number for some reason only runs through the loop once since it cuts off the last number before jumping out of the loop to print the count...any advice?
I presume you want to iterate over each digit of sevens. Since sevens initialized from args[0], the loop limit should match and look at args[0].length() rather than args.length.
for (int i = 0; i < args[0].length(); i++)
An alternate way to write the loop is to iterate until sevens reaches 0. That lines up better with the loop body; both use the same variable.
while (sevens > 0) {
if (sevens%10 == 7) {
count += 1;
}
sevens /= 10;
System.out.println(sevens);
}
Your code has logic errors, so to check if the iterated number is number 7 you need to turn the number into a string and check if the character is the desired character using: numberString.charAt(index)
Below is the corrected code:
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
String numberString = String.valueOf(sevens);
int count = 0;
for (int i = 0; i < numberString.length(); i++) {
char c = numberString.charAt(i);
if (c == '7') {
count += 1;
}
System.out.println("Input number: " + sevens);
}
System.out.println("Count of 7 numbers: " + count);
}
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.
I've recently taken up a computer organization course in where we learn binary hex etc, I took it upon myself to attempt to create a program that will count from 0 up to an input number, however the counting is done in binary. I've run into some trouble and confused myself beyond belief, some clarification and assistance would be greatly appreciated. Specifically speaking, how can I efficiently and effectively replace the values of a string containing the previous binary number, with 0's and 1's using some sort of for-loop. I'm aware that there is some method for directly converting a string to binary, however; I wanted to do this more complicated method for practice.
package counting;
import java.util.Scanner;
public class counting
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello, this is a number counter, please enter the integer you would like to count to");
int number = input.nextInt();
String start = "0000000000";
// 000~etc is used as the start simply because i'm not sure how to calculate how many digit places
//the number input by the user will have
StringBuilder cont = new StringBuilder(start);
System.out.println(start);
/*What i intend to do is have the binary loop counter continue until it reaches
* the number input by the user, afterwards, working in a right to left manner, start counting from
* 0 up to the number given by the user, starting with 0. then using another loop, still using
* the right to left manner, if there is a 0, it should be replaced with a 1, and if there is a
* 1, it should be replaced with a 0, and the character before it should be replaced with a 1, if there
* is no room, continue to the left until there is a space available for a 1 and then reset all values
* after the 1 back to zero, and resume counting. the way i see it is requires a for loop to be used
* as the current position of a cursor used to determine what changes must be made
*/
for(int i = 0; i < number; i++)
{
int l = start.length();
for(int n = 0; n <= number; n++)
{
for(int w = 1; w <= l; w++)
{
if (cont.charAt(l-w) == '0')
{
cont.setCharAt((cont.length()-w), '1');
System.out.println(cont);
}
else if (cont.charAt(l-w) == '1')
{
cont.setCharAt((cont.length()-w), '0');
cont.setCharAt((cont.length()-(w+1)), '1');
System.out.println(cont);
}
}
}
System.out.println(cont);
}
}
}
Here is a little loop that will do what you are looking for. You just have to remember powers of 2 to count in binary.
public static char flip(char c){
if(c == '0')
return '1';
else
return '0';
}
public static void main(String[] args) {
String start = "0000000000";
StringBuilder cont = new StringBuilder(start);
int number = (int)Math.pow(2,10);
for(int i = 0; i < number; i++)
{
if(i != 0){
int val = (int)Math.floor(i/2);
for(int j = 0; j <= val; j++){
// Flip any bit that when modded by 2^j == 0
if(i % Math.pow(2,j) == 0){
cont.setCharAt((cont.length() - (j + 1)), flip(cont.charAt(cont.length() - (j + 1))));
}
}
}
System.out.println(cont);
}
}
I've read through a bunch of threads on using break and continue and I suspect the problem isn't necessarily my use of those, but the layout of my loops. In the following code, I am trying to iterate through the chars in a string that is input by the user to find any - symbols. If found, it will throw an error to the user that a negative number was found and exit. Otherwise, if it does not find a - symbol, it should print out all of the chars in the string.
I used break at the end of my first loop to find the - symbol, but it is not continuing on to the next loop. I tried continue as well but that didn't work. Loops are new to me so I may have this completely wrong, all I know is my first loop is working OK and will throw the error when it finds a - in the string.
strNum1 = JOptionPane.showInputDialog ("Enter Number String");
for (int i = 0; i < strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-') {
System.out.println("Negative Digit Found - Exiting");
break;
}
}
for (int i = 0; i < strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c <= 9) {
System.out.println(c);
}
}
The break statement breaks you only from the first loop. In order to skip running the second loop in the event of finding a - character, you can use some boolean variable to indicate whether the second loop should run :
strNum1 = JOptionPane.showInputDialog ("Enter Number String");
boolean isValid = true;
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-'){
System.out.println("Negative Digit Found - Exiting");
isValid = false;
break;
}
}
if (isValid) {
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c <= '9'){
System.out.println(c);
}
}
}
If you replace the break with a return it will exit the whole method. It sounds like this is probably what you want.
'break;' will stop the loop that it is in from running, where 'continue;' will skip the current 'iteration' in the loop.
for(int x = 0; x < 10; x++)
{
if (x == 5)
break;
// other code
}
// more other code
This will exit the loop once x == 5, and not do the 6th through 10th iterations.
for(int x = 0; x < 10; x++)
{
if (x == 5)
break;
// other code
}
// more other code
This will do every iteration, besides the 6th iteration.
But if you want to skip the '// more other code', then you would need to use a 'return;', provided your code is in a function, and it will skip the rest of the function, which in this case is the '// more other code'.
Use the return statement instead of break if you dont want to execcute the second loop after the first one.
You don't say if the number should be an integer, so I'm assuming yes.
If so, instead of using loops, a better way of validating the input would be:
int num1;
try {
num1 = Integer.parseInt(strNum1);
catch (NumberFormatException e) {
//not a valid number, complain about it
}
if (num1<0) {
//negative number not allowed, complain about it
}
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-'){
System.out.println("Negative Digit Found - Exiting");
break;
}
}
can be modified as
if(strNum1.charAt(0) != '-'){
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c <= 9){
System.out.println(c);
}
}
}
else {
//negative number found...
}
In This way, unnecessary for loop and break statements can be avoided
All answers are good, but if you want to repeat prompt until you get a valid value,
you will need another loop for that, using labels:
negative: while(true) {
strNum1 = JOptionPane.showInputDialog ("Enter Number String");
for (int i=0; i<strNum1.length(); i++) {
char c = strNum1.charAt(i);
if (c == '-'){
System.out.println("Negative Digit Found - Exiting");
continue negative;
}
break negative;
}
}
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("");
}
}
}