Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
开发者_如何学JAVAClosed 9 years ago.
Improve this questioncan you hep me about my assignment? it says that I have to create a program that the output is like this:
123
12
1
we gotta use loop statements
and I really can't think the answer. please help me..
Run an index, say we name it I, in a loop from N to 1, and inside the first loop run another index from 1 to I.
I think I told you enough.
Clarification: I see other people think you might have wanted to print the quotients when dividing a number by successive powers of 10. I find that situation not so probable. But if it's just a coincidence that your numbers have consecutive digits then please disregard my answer and take a look at the other posted here.
Start with a string "123".
Loop from 0 to length of string - 1, in the loop print a slice of the string which starts at the beginning and ends at the loop index.
I guess you don't tell us the big picture. Answering strictly to what you ask could lead to:
public class SO {
public static void main(String[] args) {
for (String s :"123:12:1".split(":")) {
System.out.println(s);
}
}
}
But that's probably not what you want.
Edit: I know this is a stupid answer.
Here's some pseudo code to get you started:
for limit = 3 to 1 inclusive:
for number = 1 to limit inclusive:
output number with no new line
output new line
Your job is to translate that into Java (since it's classwork) and you can do that with the use of for
loops along with System.out.print/println
calls.
However, given this question was asked almost five years ago, I suspect you've probably had to hand something in by now so I have no qualms about now giving actual code:
public class Test{
public static void main(String[] args) {
for (int limit = 3; limit > 0; limit--) {
for (int number = 1; number <= limit; number++) {
System.out.print(number);
}
System.out.println();
}
}
}
The output of that program is, as desired:
123
12
1
You could use two loops:
First you loop from 3 to 1. That will give you the three blocks.
Second in each iteration of your first loop you loop from 1 up to the value of your first variable while building the output.
for (int pow10 = 1; pow10 < n; pow10 *= 10)
System.out.println(n / pow10);
Also a good case for a do-while:
do
System.out.println(n);
while ((n /= 10) > 0);
int a = 123;
for ( int i = a; i > 0; i = i/10 ) { System.out.println(i); }
Can't get much simpler than this when using a for loop.
String string = "123 12 1";
String[] somePartsOfString = string.split("\\ ");
for (int i = 0; i < somePartsOfString.length; i++){
System.out.println(somePartsOfString[i]);
}
An obscure solution which might amuse... ;)
Random r = new Random(292012);
for(int i=0;i<9;i++) {
int n=r.nextnt(4);
System.out.print(n<1?"\n":""+n);
}
精彩评论