Here is my Code
import java.util.*;
public class dowhile
{
public static void main (String [] args)
{
Scanner kb = new Scanner (System.in);
System.out.println("Enter number of # to be displayed: ");
int tim = kb.nextInt();
String hash = "#";
do
{
System.out.println(hash);
hash = hash + 1;
} while (hash.equals(5));
}
}
I am confused on how to display number of # after asked by the user..
I know hash.equals(5) does not make sense.
how can i fix this code?
Any one please give the suggestion to me.
You could use tim as a counter, and decrement it before testing if it's greater than 0. Something like,
int tim = kb.nextInt();
do {
System.out.print("#");
} while (--tim > 0);
System.out.println();
You can also use Apache commons-lang3 which has StringUtils.repeat(String, int)
Parameters:
str - the String to repeat, may be null
repeat - number of times to repeat str, negative treated as zero
hash is the string that you are going to print, so you should never change its value like this:
hash = hash + 1; // this does not actually compile anyway.
To keep track of how many times you still need to print, you need an int variable. As you can see, tim is an int and it already has the user input stored in it. Let's use tim as our counter.
Each time you print a # you decrease tim by 1. And in the loop condition, you write tim > 0. This will make the loop run as long as tim is greater than 0.
Scanner kb = new Scanner(System.in);
System.out.println("Enter number of # to be displayed: ");
int tim = kb.nextInt();
String hash = "#";
do {
System.out.println(hash);
tim--; // this is equivalent to tim = tim - 1;, in case you did not know
} while (tim > 0);
However, I don't think using a do-while loop is suitable here. What if the user entered 0? One # will still be printed. That's no good isn't it?
I suggest a for loop here:
Scanner kb = new Scanner(System.in);
System.out.println("Enter number of # to be displayed: ");
int tim = kb.nextInt();
String hash = "#";
for (int i = 0 ; i < tim ; i++) {
System.out.println(hash);
}
Declare one int variable before the loop. Increment number by one in do and check then number in while loop is will print your desired output.
int i=0;
do
{
System.out.println(hash);
i=i + 1;
} while (i<tim);
Related
I'm trying to make a "for" loop in which it asks the user to input 10 numbers and then only print the positives.
Having trouble controlling the amount of inputs. I keep getting infinite inputs until I add a negative number.
import java.util.Scanner;
public class ej1 {
public static void main(String args[]) {
int x;
for (x = 1; x >= 0; ) {
Scanner input = new Scanner(System.in);
System.out.print("Type a number: ");
x = input.nextInt();
}
}
}
From a syntax point of view, you've got several problems with this code.
The statement for (x = 1; x >= 0; ) will always loop, since x will always be larger than 0, specifically because you're not introducing any kind of condition in which you decrement x.
You're redeclaring the scanner over and over again. You should only declare it once, outside of the loop. You can reuse it as many times as you need.
You're going to want to use nextLine() after nextInt() to avoid some weird issues with the scanner.
Alternatively, you could use nextLine() and parse the line with Integer.parseInt.
That said, there are several ways to control this. Using a for loop is one approach, but things get finicky if you want to be sure that you only ever print out ten positive numbers, regardless of how many negative numbers are entered. With that, I propose using a while loop instead:
int i = 0;
Scanner scanner = new Scanner(System.in);
while(i < 10) {
System.out.print("Enter a value: ");
int value = scanner.nextInt();
scanner.nextLine();
if (value > 0) {
System.out.println("\nPositive value: " + value);
i++;
}
}
If you need to only enter in ten values, then move the increment statement outside of the if statement.
i++;
if (value > 0) {
System.out.println("\nPositive value: " + value);
}
As a hint: if you wanted to store the positive values for later reference, then you would have to use some sort of data structure to hold them in - like an array.
int[] positiveValues = new int[10];
You'd only ever add values to this particular array if the value read in was positive, and you could print them at the end all at once:
// at the top, import java.util.Arrays
System.out.println(Arrays.toString(positiveValues));
...or with a loop:
for(int i = 0; i < positiveValues.length; i++) {
System.out.println(positiveValues[i]);
}
Scanner scan = new Scanner(System.in);
int input=-1;
for(int i=0;i<10;i++)
{
input = sc.nextInt();
if(input>0)
System.out.println(input);
}
I am taking an online MOOC to learn Java, the only problem i have is it is from the university of Helsinki in Finland i live in the US so there are limited times when i can be awake to ask for help on an exercise. my current exercise is to ask the user for a number and then print each whole number up to that number while using a
while {
}
statement
this is the code i have currently
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number = Integer.parseInt(reader.nextLine());
System.out.print("up to what number?:"+ number);
while (number<=number){
System.out.println(number);
number++;
}
}
and what it looks like it is doing is ignoring the
while (number<=number) {
System.out.println(number);
part of my code and proceeding straight to the
number++;
portion of my code do i need to declare another int(variable) to store a value?
the way the course has the test cases for grading i can't simply declare a variable with a definite value as they run several test cases like positive numbers and negative numbers.
is there a way to use the reader to store a value to two separate variables so that they can be compared against each other and only print the numbers up to that number?
i also know that i am missing a
Break;
statement but i am not sure where i would place it in the code i have, i have tried to use
} else {
break;
but get an error stating that i have an else without an if.
i am using netbeans as it is required for my course because the server submissions are setup through TMC.
thinking about it now i'm sure its not skipping the while statement but simply continues to print because as it prints and increments the users input is incremented as well since i only have the one variable but i am again not sure how i would go about storing the user input value in two different variables where i can compare them with the less than or equal to statement and stop the printing once it reaches the number input by the user, in that case i would not necessarily need the break statement as it would stop once it prints up to the number input.
ANSWERED: here is what i finally came up with as my answer.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("up to what number?:");
int numbers = 1;
int number = Integer.parseInt(reader.nextLine());
while (numbers <= number){
System.out.println(numbers);
numbers++;
}
}
You are comparing number to itself. So (number <= number) is always true.
Use a different variable, such as count to actually count up. Initialize it at zero.
Change the condition to (count < number), then in the loop change the increment to count++ and then output count.
Oh, and you should probably prompt for the number before you read it in.
ie your whole program will be:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("up to what number?:");
int number = Integer.parseInt(reader.nextLine());
int count = 0;
System.out.println(number);
while (count<number){
count++;
System.out.println(count);
}
}
You need another variable to increment upto inserted number
int i=1;
while (i<=number){
System.out.println(i++);
}
What your loop is doing
while (number<=number){
System.out.println(number);
number++;
}
for example number=10 so it's checking like this 10<=10 do you need this,absolutely not.
So for your code you need an another variable to increment up to entered number.
This would do it:
public static void main(String[] args) {
int startingInt = 1; //begin printing from 1
System.out.println("Up to what number?");
Scanner reader = new Scanner(System.in);
int number = Integer.parseInt(reader.nextLine());
while (startingInt <=number){
System.out.println(startingInt);
startingInt++;
}
}
i'm c# expert, so first of all please use c#.
But I know I know you can't always select your laguagued, ;)
Here is solution , it works on my machine.
while (number<=number){
System.out.println(number);
number++;
if (number==arg[0]) break;
}
Enjoy the solution!
System.out.println("Up to what number?");
int number = Integer.parseInt(reader.nextLine());
int n = 1;
while (n <= number) {
System.out.println(n);
n++;
}
Hi guys i am learning java in order to code in Android, i got some experience in PHP, so i got assigned an exercise but cant find the right loop for it, i tried else/if, while, still cant find it, this is the exercise:
1- prompt the user to enter number of students, it must be a number that can divide by 10 (number / 10) = 0
2- check of user input, if user input not dividable by 10 keep asking the user for input until he enter the right input
How i code it so far, the while loop not working any ideas how to improve it or make it work?
package whiledowhile;
import java.util.Scanner;
public class WhileDoWhile {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
/* int counter = 0;
int num;
while (counter <= 100) {
System.out.println("Enter number");
num = user_input.nextInt();
counter += num; // counter = counter + num
//counter ++ = counter =counter +1
}
System.out.println("Sum = "+ counter);
*/
int count = 0;
int num;
System.out.println("Please enter a number: ");
num = user_input.nextInt();
String ex;
do {
System.out.print("Wrong Number please enter again: " );
num++;
}
while(num/10 != 0 );
}
}
When using a while loop, you'll want to execute some code while a condition is true. This code needs to go inside the do or while block. For your example, a do-while loop seems more appropriate, since you want the code to execute at least one time. Also, you'll want to use the modulo operator, %, inside of your while condition, not /. See below:
Scanner s = new Scanner(System.in);
int userInput;
do {
// Do something
System.out.print("Enter a number: ");
userInput = s.nextInt();
} while(userInput % 10 != 0);
Two things:
I think you mean to use %, not /
You probably want to have your data entry inside of your while loop
while (num % 10 != 0) {
// request user input, update num
}
// do something with your divisible by 10 variable
Help I have a puzzle that needs solved!
I made a Fibonacci series but I forgot to include the 0
Who can help me solve this riddle?
If the input is five in the sequence the output should be 0,1,1,2,3
What should I change to clean up the code and get the desired result without completely starting from scratch?
//Class Assignment 9 little Fibonacci series based on what input
//the user provides
import java.util.Scanner;
public class LittleFibonacci {
int number;// This declares an int variable
public static void main(String[] args){
//itnu is the new object
LittleFibonacci itnu = new LittleFibonacci ();
itnu.GetNumberInput();
}
public void GetNumberInput()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a number and that number will be a" +
" \nrepresentitive of the length of a sequence in the Fibonocci series.");
number = input.nextInt();
int f1, f2=0, f3=1;
for(int i = 1 ; i <= number ; i++ )
{
System.out.print(" "+f3+" ");
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
input.close();
}
}
Just start your loop at zero instead of one, and change the initializations of {f1,f2,f3} accordingly (left as an exercise for the reader).
The other solutions here that tell you to output zero first are basically cheating. You might as well just hard-code all the Fibonacci numbers. You won't get any marks for doing that.
Add
System.out.print(" "+f2+" ");
before the for loop. Change the for loop terminating condition to <.
I guess to be really completist we should also check that the user does not enter 0 (or a negative number) and not even print f2 in that case.
This may seem slightly "unclean" but the fibonacci sequence has two starting numbers, they are special and need special treatment.
the approach I would take, is to print your base cases first, and then reset them after each iteration
int fPrev = 0, fCur = 1;
System.out.print(fPrev+" "+fCur);
for(int i = 2 ; i <= number ; i++ )
{
int fNew = fPrev + fCur
System.out.print(" "+fNew);
fPrev = fCur;
fCur = fNew;
}
I'm having a problem with my while loop. The program asks the user for their name and after the user have made their input, the program asks how many times you would like to print the input.
I've been stuck on my while-loop for quite a time and can only make it work if I do something like: } while (antal > some random number)
package uppg2;
import java.util.Scanner;
public class Uppg2 {
public static void main(String[] args) {
Scanner name = new Scanner(System.in);
Scanner ant = new Scanner(System.in);
int antal;
String namn;
System.out.print("Whats your name?: ");
namn = name.nextLine();
System.out.print("How many times u wanna print ur name?: ");
antal = ant.nextInt();
do {
System.out.print(namn);
} while (????);
antal++;
namn = null;
antal = 0;
}
}
I personally would use a for loop like so:
for(int i = 0 ; i < antal; i++){
System.out.println(namn);
}
This would be rather a use-case for a for-loop like some others suggested. But when you insist on using a while loop:
int counter = 0; // a variable which counts how often the while loop has run
do {
System.out.print( namn ); // do what you want to do
counter++ // increase the counter
} while (counter < antal) // check if the desired number of iterations is reached
When you don't need the value of antal anymore when the loop is over, you can also do it without the counter variable and just reduce antal every loop and check if it has reached 0.
do {
System.out.print( namn );
antal--;
} while (antal > 0)
You could count antal down (antal--) until it is 1. Not sure if it is OK to destroy the value in antal though.
package uppg2;
import java.util.Scanner;
public class Uppg2 {
public static void main(String[] args) {
final Scanner in = new Scanner(System.in);
int antal;
String namn;
System.out.print("Whats your name?: ");
namn = in.nextLine();
System.out.print("How many times u wanna print ur name?: ");
antal = in.nextInt();
int i = 0;
while(i < antal){
System.out.print( namn );
i++;
}
in.close();
}
}
Tell me if that works. Basically, you need an increment counter to ensure that it only prints out the desired amount of times. Since we start counting at 0, we don't need to ensure that it goes till it equals the print time, but while it still is under it.
you would have to have a counter that is incremented inside of your do-while loop, and perform your comparison against that value
it would make your loop loop something like:
antal = ant.nextInt();
int i = 0;
do{
System.out.print( namn );
i++;
}while (i < antal);
note that because it's a do-while loop, you will always print the name at least once, even if the user enters zero. To prevent this, you would need to use a for or while loop, as described by other answerers, or use an if condition around the System.out.println call to check if antal is zero.
Also, if you don't care what antal is at the end, you can use TofuBeer's solution.
Here's a solution to a similar problem. See if you can't translate it into your problem:
// How many times to I want to do something?
int max = 40;
for (int i = 0; i < max; i++) {
// Do something!
}