Converting a while loop in a do-while loop in Java - java

I know this question has been asked several times already. Feel free to mark it as a duplicate. Anyway, I'd rather ask the community since I am still uncertain.
I should convert this while loop in a do-while loop.
Any thoughts?
public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
int number = input.nextInt();
while (number != 0) {
sum += number;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
number = input.nextInt();
}
}
}

You cant just simple convert any while loop to do while loop , the main difference between them is in do while loop you have an iteration that will happen regardless of the condition.
public class DoWhile {
public static void main(String[] args) {
int number=0;
Scanner input = new Scanner(System.in); int sum = 0;
do{ System.out.println("Enter an integer " +"(the input ends if it is 0)");
number = input.nextInt();
sum += number;
}while (number != 0) ;
}
}

public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
int number = 0;
do {
System.out.println("Enter an integer " +
"(the input ends if it is 0)");
number = input.nextInt();
sum += number;
} while(number != 0)
}
}

You have to tell the program to continue doing something in the "do" block. In your own case you have to tell the program to keep doing this"
System.out.println("Enter an integer " + "(the input ends if it is 0)"); number = input.nextInt();
sum += number;". Then in the "while" block you will have to provide the terminating statement, in your own case "number != 0"
public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
int number;
do {
System.out.println("Enter an integer " + "(the input ends if it is 0)");
number = input.nextInt();
sum += number;
} while (number != 0);
}
}

public class DoWhile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); int sum = 0;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
int number = input.nextInt();
//You need this if statement to check if the 1st input is 0
if(number != 0)
{
do
{
sum+=number;
System.out.println("Enter an integer " + "(the input ends if it is 0)");
number = input.nextInt();
}while(number != 0);
}
}
}

classInfoClass
{
public void setinfo()
{
int userage;
do
{ Console.Write("Please enter your age: ");
} while (!int.TryParse(Console.ReadLine(),out userage));

Related

Never ending for loop with user input

I am new to java and have just learned how to use user input. I have a for loop that goes through 10 times with user input to ask for a number. If the number is invalid, it should print "Invalid number" and not count towards the increasing for loop. Instead, it just loops forever saying 'Invalid number'.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int sum = 0;
Scanner scanner = new Scanner(System.in);
for(int i = 1; i<=10; i++){
System.out.println("Enter number #" + i + " ");
boolean validInt = scanner.hasNextInt();
if(validInt){
int num = scanner.nextInt();
sum += num;
} else{
System.out.println("Invalid Number");
i--;
}
}
System.out.println("Sum was " + sum);
scanner.close();
}
}
The problem is you are updating the iterator i at 2 places.
The better way is to update it according to the condition.
I would also suggest you to make use of wrapper classes for safe integer conversions and handle the exceptions properly like done in the following code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int sum = 0;
Scanner scanner = new Scanner(System.in);
for(int i = 1; i<=10; ){
System.out.println("Enter number #" + i + " ");
String input = scanner.nextLine();
try{
int num = Integer.parseInt(input);
sum += num;
i++; // If input is a valid integer, then only update i
}catch(NumberFormatException e){
System.out.println("Invalid Number");
}
}
System.out.println("Sum was " + sum);
scanner.close();
}
}
I think you also can tweak the code using hasNextInt() directly in the while loop.
while (scanner.hasNextInt()) {
int num = scanner.nextInt();
sum += num;
}
I needed to add a
scanner.nextLine();
After the if and else statement to clear the scanner in both situations.

How do I add the ability for the program to continue even after the first input is given?

I'm writing a Hailstone Sequence program and I want to add the ability for the program to keep calculating even after the first input and output is already printed. Basically, instead of re-running the program, you could keep giving inputs.
public class HailStoneSequence {
static Scanner MyScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter a number to generate the Hailstone Sequence for that number. ");
int num = MyScanner.nextInt(); //Taking input from user
while (num>1)
{
if (num%2 == 0)
{
num /= 2;
System.out.print(num+" ");
}
else
{
num = (num*3)+ 1;
System.out.print(num+" ");
}
}
}
}
Just surround the block of code with a while loop that checks if the input is for example 0, in that case 0 would mean the end of the execution.
import java.util.Scanner;
public class HailStoneSequence {
static Scanner MyScanner = new Scanner(System.in);
public static void main(String[] args) {
int num = 1;
while(num != 0) {
System.out.println("Enter a number to generate the Hailstone Sequence for that number. ");
num = MyScanner.nextInt(); //Taking input from user
while (num>1)
{
if (num%2 == 0)
{
num /= 2;
System.out.print(num+" ");
}
else
{
num = (num*3)+ 1;
System.out.print(num+" ");
}
}
}
}
}
You can use a while loop to keep your program running like so:
System.out.println("Enter a number to generate the Hailstone Sequence for that number:(0 to quit) ");
int num = MyScanner.nextInt(); //Taking input from user
while(num != 0){
//logic
System.out.println("Enter a number to generate the Hailstone Sequence for that number:(0 to quit) ");
num = MyScanner.nextInt(); //Taking input from user
}
Then at the end of your logic take the input again. the program will continue to run until the user enters a key(in this case, 0)
You can do something like this:
String input = "";
do {
// Your code here
System.out.println("Continue?");
input = MyScanner.next();
} while (!input.equals("exit");

How can the numbers in array count to odd or even number?

I wrote the code in java but it does not count to odd or even. It only counts in even numbers. If I miss anything?
import java.util.Scanner;
public class OddEven {
//create the check() method here
static void check(int[] x, int n) {
x = new int[100];
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
x[n++] = in.nextInt();
}
if (x[n] % 2 == 0) {
System.out.println("You input " + n + " Even value");
} else if (x[n] % 2 == 1) {
System.out.println("You input " + n + " Odd value");
}
while (in.hasNextInt()) ;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//read the data here
System.out.print("Input a list of Integer number : ");
int[] x = new int[100];
int n = 0;
check(x, n);
in.close();
}
}
Check these loops:
This essentially puts all the ints in x.
while(in.hasNextInt()) {
x[n++] = in.nextInt();
}
This just loops until it doesn't have an it.
while(in.hasNextInt());
Which means, the if block is not even in a loop. However, the first while loop post increments n, which means even if you have one number, it will assign:
x[0] = 123;
but then n=1. which means, the if block will check the next field. But by default it is 0, which will display that it is even.
This would make more sense:
x= new int[100];
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
x[n] = in.nextInt();
if(x[n]%2==0){
System.out.println("You input "+n+" Even value");
}else if(x[n]%2==1){
System.out.println("You input "+n+" Odd value");
}
n++;
}

I am getting error messages concerning my coding. I know Scanf is not a java function, so I am hoping to get help converting it

I know that scanf is not a java function, so i'm hoping someone can help me to understand how to convert this. Research on this topic is difficult to piece together.
This is my code:
import java.util.Scanner;
public class Average {
Scanner Scanner = new Scanner (System.in);
int main (){
int counter;
int number;
int total;
float average;
total = 0;
counter = 0;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
While (number != 0) {
total = total + number;
counter = counter + 1;
System.out.println("Enter the number 0 to end: ");
Scanf("%d", &number);
}
if(counter != 0) {
average = (float) total / counter;
System.out.println("Average is %.2f\n", average);
} else {
System.out.println("No valid numbers have been entered.");
return 0;
}
}
}
use input like this`
public class seting{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);`
int total = 0;
System.out.printlnln("Enter the value of total :");
total = scan.nextInt(); // use integer input
}
}
You cannot use the same name for the object as for the class. Change Scanner initialization as follows:
Scanner scanObj = new Scanner(System.in);
Replace all your scanf statements with the below:
number = scanObj.nextInt();
These are the changes done to your code:
import java.util.Scanner;
public class one {
public static void main(String[] args) {
Scanner Scanner = new Scanner (System.in);
int counter;
int number = 1;
int total;
float average;
total = 0;
counter = 0;
while(number != 0){
System.out.println("Enter the number 0 to end: ");
number = Scanner.nextInt();
System.out.printf("%d", number);
total = total + number;
counter = counter + 1;
}
if(counter != 0){
average = ((float)total /(float)counter);
System.out.printf("Average is %.2f\n", average);
}
else{
System.out.println("No valid numbers have been entered.");
//return 0;
}
}
}
First the Scanner takes the value the user entered. number = Scanner.nextInt(); This must be done inside your while loop since its the one that check the condition.
The next thing I changed was average = (float) total / counter;
This casts the total value only to a float. use brackets to both ends.
average = ((float)total /(float)counter); like this

How to sum any amount of user inputted numbers from a single line

Trying to figure out how I would take any amount of inputted numbers from a user and add them together
Example user input: 1 2 3 4
Sum = 10
The user can put any amount of numbers in not a specified amount so if he wanted to add 1 2 3 4 5 6 7 8 9 10 11 12 13, it would sum them all up to 91
Thanks for the help in advance.
import java.util.Scanner;
public class test
{
public static final int SENTINEL = -1;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int score = 0;
int sum = 0;
System.out.println("Enter numbers here");
while (score >= 0) {
if (score <= -1) {
score = kb.nextInt();
sum += score;
score = 0;
}
System.out.println(sum);
}
}
}
Thanks to libik for all his time and help, here is the finished code.
import java.util.Scanner;
public class JavaApplication1156 {
public static void main(String[] args) {
System.out.println("Enter numbers here");
int sum;
do {
Scanner kb = new Scanner(System.in);
int score = 0;
sum = 0;
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
if (sum <= -1)
System.out.println("Application ended");
else if (sum >= 0)
System.out.println("Sum = " + sum);
} while (sum != -1);
}
}
It is very easy actually
import java.util.Scanner;
public class JavaApplication115 {
public static void main(String[] args) {
System.out.println("write numbers, if you write zero, program ends");
Scanner input = new Scanner(System.in); //just copy-and paste this line, you dont have to understand it yet.
int number;
int sum = 0;
do {
number = input.nextInt(); //this reads number from input and store its value in variable number
sum+= number; //here you add number to the total sum
} while(number != 0); //just repeat cycle as long as number is not zero
System.out.println("Sum is : " + sum);
}
}
Working code based on your code :
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int score = 0;
int sum = 0;
System.out.println("Enter numbers here");
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
System.out.println(sum);
}
Also if you are interested in "minimal" version, which is the same as the one before, but using as less code as possible, here it is :
public static void main(String[] args) {
int sum = 0;
System.out.println("Enter numbers here");
Scanner kb = new Scanner((new Scanner(System.in)).nextLine()); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
sum += kb.nextInt();
}
System.out.println(sum);
}
Find sum of each line as long as sum is not zero (based on second block of code) :
public static void main(String[] args) {
System.out.println("Enter numbers here");
int sum;
do {
Scanner kb = new Scanner(System.in);
int score = 0;
sum = 0;
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
System.out.println("Sum = " + sum);
} while (sum != 0);
}
//Input the number in a single line (but be in size limit of integer)
import java.util.Scanner;
public class Sum_of_integers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int sum = 0;
while(num >= 1) { //base value
int lastval = num % 10; //the logic
num = num / 10;
sum += lastval;
}
System.out.println(sum);
}
}
Question - Keep taking numbers as inputs till the user enters ‘x’, after that print sum of all.
Scanner sc = new Scanner(System.in);
int input = 0;
int sum = 0;
while (true){
sum = sum+input;
if (input==5){
System.out.println("Loop is stopped");
System.out.println("The sum is " + sum);
break;
}
else {
System.out.println("Take the inputs");
input = sc.nextInt();
}
}

Categories