Do-while loop won't work - java

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!
}

Related

Break a programm with a loop

I wrote a code which calculates grades. But if I'm typing 9999 in the console, then the program should break without any output. How can I do this and which loop should I use? I tried it with a while loop but the program gives me still output.. this is my code with the while loop which doesn't work as it should. The Programm works except for the while loop. How can I do write this better?
import java.util.Scanner;
public class average {
public static double average (double [] grade ){
double sum = 0;
int number = grade.length;
for(int i = 0; i<grade.length; i++){
sum+=grade[i];
}
double average = sum / number;
return average;
}
public static void main (String [] args){
Scanner s = new Scanner(System.in);
System.out.println("How much grades you add?");
int number = s.nextInt();
while(number == 9999){
break;
}
double [] grade = new double [number];
System.out.println("Please enter : ");
for(int i = 0; i<grade.length; i++){
grade[i] = s.nextDouble();
}
System.out.println("My grades are: ");
for(int i = 0; i<grade.length; i++){
System.out.println(grade[i] + " | ");
}
System.out.println("");
System.out.println("My average: " +average(grade));
}
}
You are using a break, which immediately exits only the loop. If you want to quit the program, you should use if and return like this:
if(number == 9999) {
return;
}
This quits the program because with return, you exit the current function. The current function is main(), that's the program's main code. So, if you exit it, you will quit the program.
In functions with a return value (non-void functions) you need to specify the return value like this:
return 9999;
If you are on an other program thread, you need to call System.exit(0).
You don't need to break any loop, you just need to exit the program.
if (number == 9999) {
System.exit();
}

Confusion on do-while loop

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);

Why is this simple program not working

So I'm doing some random practice for an upcoming exam, and I don't know if it's the fact that I've been reviewing for hours and my brain isn't functioning, or something in this code is wrong.
I'm attempting to make a very simple java program that asks the user for the amount of numbers they wish to enter (totalNum), create an array that long, and then ask the user for each individual value. After it asks the user for each value in the array, it prints the array.
Here is my code:
import java.util.Scanner;
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i>totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++;
}
numbers.toString();
System.out.println(numbers);
}
}
When I run it it asks the user for the numbers I want to store, then prints [I#33909752 and stops. I've done dozens of programs like this and for the life of me I can't figure out where I went wrong.
Any help would be appreciated, thanks!
Your loop test is backwards. This
for (int i = 0; i>totalNum; i++) {
should be
for (int i = 0; i < totalNum; i++) {
as is, the test evaluates to false and the loop isn't entered. And, don't increment i in the loop body (that's what i++ does in the for). Finally,
System.out.println(numbers);
isn't going to print the array correctly, because arrays don't override Object.toString(). You can use Arrays.toString like
System.out.println(Arrays.toString(numbers));
i>totalNum is the problem. The for loop will not execute even once.
The for loop has three parts:
The action to perform before starting the loop
The condition
The action to perform after each loop
Your condition is i>totalNum, which is false for i=0 and totalNum=1. The loop won't execute even once.
The i++ is already mentioned in the loop, you do not need to include it in the loop body anymore.
The unexpected output is the caused by the default toString()-method of Array. Use Arrays.toString() for a readable output.
Your loop condition should be
for (int i = 0; i<totalNum; i++) {
and within loop don't increment variable i
use below for your desired result.
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i<totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++; //remove this
}
numbers.toString();
System.out.println(Arrays.toString(numbers));
}
}

How to use for loop to input 10 numbers and print only the positives?

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);
}

Right Loop for this exercise in Java

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

Categories