As a beginner and in java, I'm having some trouble with the output of my code. The code only prints the values of "a","b" and "c" for the value I put into running the code. How would I amend this for it to print all values up to and including the value I put into running the code
Could someone help please? Thank you!
class Numbers
{
public static void main (String[] args)
{
for ( int i = 0; i < args.length; i++)
{
int a = Integer.parseInt(args[i]);
System.out.print(a);
int b = (a*a);
int c = (a*a*a);
System.out.print(b);
System.out.print(c);
}
}
}
So did I get it right in your comment? You want to pass a number that tells you how many iterations the loop should run. And for any iteration you want to write a incrementing number, its square and its cube?
class Numbers {
public static void main (String[] args) {
if (args.length == 0) {
System.out.println("Please specify number.");
return;
}
int iterationCount = Integer.parseInt(args[0]);
for ( int i = 0; i < iterationCount; i++) {
int a = i;
System.out.print(a);
int b = (a*a);
int c = (a*a*a);
System.out.print(b);
System.out.print(c);
}
}
}
Please try this
javac Numbers.java
java Numbers 1 2 3
This should work. In first iteration of your for loop, the a variable will be 1, so it will print 1, 1 and 1. In second iteration, your a variable will be 2, so it will print 2, 4 and 8 and in your third iteration, your a variable will be 3, so it will print 3, 9 and 27.
The loop just runs once because your argument is 3. So args.length is 1. And that is why 3, 9, and 27 are printed.
For the loop to run three times you might evaluate the String passed as args[0] as an int. In that case you need something like (no exception handling here):
int numLoops = Integer.parseInt(args[0]);
for ( int i = 0; i < numLoops; i++)
System.out.print(i);
System.out.print(i*i);
System.out.println(i*i*i);
}
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.
Here in array I insert 0 value in all array index, now I want to check if any array index is equal to 0, then replace the value 0 by value 1, but only one time. for example at the beginning it will find index [0]==0 then replace it by 1 then stop the execution. if index[0]==1, then loop need to find next index where value==0 and replace that value 0 with 1.
public class test {
static int roomArray[] = new int[10];
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
roomArray[i] = 0;
System.out.println(roomArray[i]);
}
test.book();
}
public static void book() {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the room you want to book");
int desiredRoom = sc.nextInt();
for (int i = 0; i < 10; i++) {
if (roomArray[i] == 0) {
roomArray[desiredRoom] = 2;
}
}
}
}
You can change it to
int desiredRoom= sc.nextInt();
if(roomArray[desiredRoom]==0){
roomArray[desiredRoom]= 2;
}
so you are checking and setting the same position
Your code and your requirements to not really match. If you go for
now i want to check if any array index ==0; then replace the value 0 by value 1, but only one time. for example in the begining it will find index [0]==0 then replace it by 1 then stop the execution. if index[0]==1, then loop need to find next index where value ==0 and replace that value 0 with 1.
then it could be like adding a break or even return
for (int i=0; i<10; i++){
if(roomArray[i]==0){
roomArray[desiredRoom]= 2;
break;
}
}
If you want to check only the desired rom, then it is like Scary Wombats answer.
I'm supposed to create and initialize a 100-element array, then make the 7th element the number "7", and finally print the array, starting a new line every 20 elements. I've been trying to figure this out for a long time and I can't.
My code right now is:
public class Array {
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
}
public static void printArray(int[] array){
for (int a=0; a < array.length; a++) {
System.out.print(" " + array[a]);
if ((a - 1) % 20 == 0) {
System.out.println("");
}
}
}
}
When I run this my output is a lot of zeros, far more than 100. They are separated every 20 characters as intended, but the seventh element is not 7. I think it has to do with the association between int "a" and my array, but I can't figure it out. I know the solution must be simple but I just cannot see it. Thank you all!
Proper indentation of your code, in particular the main method, reveals what is going on. You are calling printArray from within the for loop, so you are printing the array contents 100 times.
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
Move the call to printArray after the } ending brace for the for loop.
Now you'll get 100 0s.
Also, I think you meant to have array[a] = a + 1; executed if the index was not 6, e.g.
if (array[a] == 6) {
array[a] = 7;
} else {
array[a] = a + 1;
}
Additionally, you will want to print a newline after 20 numbers, e.g. after indexes 19, 39, etc., so add 1 to a before calculating the remainder, instead of subtracting 1, so that 19 + 1 = 20, whose remainder is 0.
There are many things wrong. However, to answer your question, you are printing the array 100 times since printArray is inside your first loop.
You misplaced an end parenthesis in your main method. The properly formatted method looks like this:
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
}
array[a] = a + 1;
}
printArray(array);
}
First of all your code is organized very badly so it's very easy for u to miss what went where. You have 2 major mistakes, first of all you called printArray()
Inside your for loop and therefore printed it 100 times.
Second, you kept checking if the value inside the array in index a is 6.
You need to check if a is 6 since it is your index like this:
if(a == 6)
array[a] = 7;
Well, I ran your code, and there are a few places that can be corrected.
As for your problem of the many things being printed, that's because you've placed your printarray() inside the for loop, so it's printing the array 100 times.
As for printing it out, i find this code to be more concise:
public static void printArray(int[] array){
int counter = 0;
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
counter++;
if(counter == 20){
counter = 0;
System.out.print("\n");
}
}
}
Also, I'm not really sure why you're using a for loop to just change the 7th element. You could use this:
array[6] = 7;
I'm not really sure what you're doing in the for loop.
I hope this helped! Good luck!
I am new to Java and now I want to learn better for loop. I made some examples , but I don't know how to do a triangle that look like this:
for n=6:
111111
22222
3333
444
55
6
My code until now:
class Pyramid
{
public static void main (String[] args)
{
int i,n=9,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++) {
System.out.print(i); }
System.out.print("\n");
}}}
But what I managed to do it looks like this:
1
22
333
4444
55555
666666
How to make it in reverse order ?
We can use is a function int numberForRow(int row) that will perform a suitable transformation. Then the function can be used like r = numberForRow(i); print(r). It needs to map this:
row (i) -> display number (r)
6 1
5 2
4 3
3 4
2 5
1 6
I think you can write it :)
Look at the relationship between the input (i) and output (r) - it might be useful to note that they always add up to the same value so a little bit of math should do the trick.
(While a function isn't strictly required I find that such functions can help break down a problem and, especially in this case, illustrate a transformation well - it also works in case of a "more advanced" transformation, such as was in the original question ;-)
Your issue is that your outer for loop was going from 6 to 1, so you need to reverse that.
Change
for(i=n;i>=1;i--) {
To
for(i = 1; i <= n; i++) {
Further explanation, so you understand what is happening inside a for loop:
A for loop operates on three clauses: where you start, the condition that the loop runs, and what to do after it runs.
------v
for(i = 1; i <= n; i++) {
This is the assignment. You set a variable to a number, which is where the loop starts. In this case, we start with i = 1, since we want to print only one 1 on the first line. In the third clause, we will increment it (read: add one to it), and run the loop again.
--------------v
for(i = 1; i <= n; i++) {
This is the condition. The loop will run whenever this condition evaluates to true. In other words, if n = 6, this loop will run when i <= 6.
--------------------v
for(i = 1; i <= n; i++) {
This is what will happen each time the loop is executed. After it runs through once when i = 1, we will increment i, so now i = 2. This will happen until the condition (i <= n) evaluates to false, i.e. when i = 7. If the condition is false, the loop will terminate.
public class Pyramid {
public static void main (String[] args)
{
int i,n=9,j;
for(i=1;i<=n;i++)
{
//for(j=1;j<=i;j++) {
for(j=n;j>=i;j--) {
System.out.print(i);
}
System.out.print("\n");
}
}
}
This should help.
Can be done using below method:
public class Main {
public static void main(String[] args) {
int n = 6;
int m =n;
for (int i = 1; i <= n; i++,m--) {
for (int j = 1; j <= m; j++) {
System.out.print(i);
}
System.out.println();
}
}
}
If you want to print the triangular numbers then use the following code
`public class Triangular{
public static void main(String[] args) {
int i = 0;
int j =0;
int count =0;
for (i=1;i<=10;i++){
count = 0; // This is a program to print triangular numbers in JAVA
for(j=1;j<=i;j++){
count = count + j;
}
System.out.println(count);
}
}
}`