Accessing a variable from inside a do-while loop [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
How can I access a variable from inside a do-while loop in Java?
The code below writes out a value until the value entered is not is between 0 and 10.
Here is my code :
import java.util.Scanner;
public class DoWhileRange {
public static void main(String[] args) {
do{
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int total +=0;
}while (a>0 && a<10);
System.out.println("Loop Terminated");
System.out.println("The total is : "+total);
}
}
The loop continues to ask for input so long as the input is between 0 and 10. Once some other number is entered the loop terminates and displays the total of all inputted numbers.

try like (declare the variable a outside the loop):
int a = -1;
do{
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
a = in.nextInt();
}while (a>0 && a<10);

To access a variable beyond the loop, you need to declare/initialize it outside of the loop and then change it inside the loop. If the variable in question wasn't an int, I would suggest that you initialize it to null. However, since you can't initialize an int variable to null, you'll have to initialize it to some random value:
import java.util.Scanner;
public class DoWhileRange {
public static void main(String[] args) {
int a = 0; //create it here
do {
System.out.println("Enter a number between 0 an 10");
Scanner in = new Scanner(System.in);
a = in.nextInt();
} while (a>0 && a<10);
System.out.println("Loop Terminated");
// do something with a
}
}
NOTE: If you simply declare the variable before the loop without initializing it (as per #Evginy's answer), you'll be able to access it outside the loop but your compiler will complain that it might not have been initialized.

try this
Scanner in = new Scanner(System.in);
int a;
do {
System.out.println("Enter a number between 0 an 10");
a = in.nextInt();
} while (a > 0 && a < 10);
System.out.println("Loop Terminated");

Related

Is there a way to use If-else statement instead of while loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
EDIT: instead of any loops, i know this kind of statement needs a while loop but I was required to use only the If-else statement.
Im trying to find the largest digit in an inputted number and all examples i can see are using while and im a bit troubled in coding it using if else. this is my sample JAVA code:
Scanner cs1 = new Scanner (System.in);
System.out.println ("Input three digit number : ");
int num = cs1.nextInt ();
int reminder, Largest_number= 0;
while (num > 0)
{
reminder = num % 10;
if (Largest_number< reminder)
{
Largest_number= reminder;
}
num = num / 10;
}
System.out.println("\nOutput : "+Largest_number);
cs1.close();
}
}
You can loop through that number without loop.
public static void main(String[] args) {
Scanner cs1 = new Scanner(System.in);
System.out.println("Input three digit number : ");
int num = cs1.nextInt();
int largestNumber = 0;
System.out.println("\nOutput : " + getLargestNumber(Math.abs(num), largestNumber));
cs1.close();
}
static int getLargestNumber(int num, int largestNumber){
if (num>0){
int reminder = num % 10;
if (largestNumber < reminder) {
largestNumber= reminder;
}
num = num/10;
largestNumber = getLargestNumber(num, largestNumber);
}
return largestNumber;
}
What I am doing here is basically I am mimicing standard for or while loops with a thing called recursion.
From GeeksforGeeks:
What is Recursion? The process in which a function calls itself
directly or indirectly is called recursion and the corresponding
function is called as recursive function.
So I'm recursively calling static method getLargestNumber(int num, int largest_number) until I reach the moment when I do not enter if (num>0) statement.
And since calling of getLargestNumber is happening inside of that if statement, then the recursion stops, and I get the final result back.
UPDATE
You algorithm is wrong. You need to pass Absolute value of entered integer. Otherwise you algorithm will give wrong answer if you pass negative value as input.
Changed num to Math.abs(num).
This is a solution without any kind of loop but only if there is guaranteed to have as input 3-digit numbers.
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner cs1 = new Scanner (System.in);
System.out.print("Input three digit number: ");
String threeDigitNum = cs1.next();
int largestNum, tmpNum;
// assuming 1st digit is the largest
largestNum = threeDigitNum.charAt(0) - '0';
// checking if 2nd digit is greater than 1st
tmpNum = threeDigitNum.charAt(1) - '0';
if( tmpNum > largestNum )
largestNum = tmpNum;
// checking if 3nd digit is greater than 1st or 2nd
tmpNum = threeDigitNum.charAt(2) - '0';
if( tmpNum > largestNum )
largestNum = tmpNum;
System.out.println("\nOutput : "+largestNum);
cs1.close();
}
}
Note:
Any char is reprsented as an integer value, and that is what charAt() method returns. So from it subtracting the chrachter '0' (represented by it's integer value) it gives as a result the integer equivalent of that value. In case of digits, for example '8' - '0' will result in integer value 8.

Trying to print out some sequence of numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to print out a sequence of numbers using this formula
Enter a number
if number is even divide number by 2.
But if number is odd multiply number by 3 and add 1
continue doing this until number becomes 1
sample input=3
Sample output=10 5 16 8 4 2
this is what I tried but still not getting it
package victor;
import java.util.Scanner;
public class proj {
public static void main(String[] args) {
Scanner put=new Scanner(System.in);
int temp=0;
boolean notOne=true;
System.out.println("input::: ");
int num=put.nextInt();
while(temp!=1){
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
else {
temp=num;
System.out.println(temp*3+1);
break;
}
}
if(temp!=1){
notOne=false;
}
}
}
It's not working because you keep re-assigining the variable temp to the initially scanned num.
You keep checking if the initially scanned num is odd or even, when you should check if temp is odd or even.
You also break out of the loop for no reason.
And finally, you're not saving the result of the operations, you're only printing out the result.
Try to understand the points I mentioned above by noticing the differences between your code and the following:
while(temp!=1){
if (temp%2==0){
temp = temp/2;
}
else {
temp = temp*3+1;
}
System.out.println(temp);
}
You are not updating the value of temp. You are just printing it. Take the following statement
if (num%2==0){
temp=num;
System.out.println(temp/2);
break ;
}
Here you are setting temp to num and just printing temp/2 and never setting a value.
I wrote my version of it which is a bit more simpler. I hope this will help you. You can create a string to get a better output of course.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scan.nextInt();
while (number != 1) {
number = number % 2 == 0 ? number / 2 : ((number * 3) + 1);
System.out.println("Number became " + number);
}
}
}
Try this:
public class Main
{
public static void main(String[] args) throws Exception
{
System.out.println("Starting...");
//Lets start the program, first we need
//the Scanner class to access to the input
Scanner stdin = new Scanner(System.in);
System.out.print("Type a num: ");
//I dont use: nextInt() because when asking for another input, will scan only
//the rest of the line (Maybe just \n - line break )
int num = Integer.parseInt(stdin.nextLine());
//Optional
int loops = 0;
while(num!=1){
//Pair, so num/2
if ( num %2 == 0){
num/=2;
}
else{
//num*3 +1
num=num*3 +1;
//Note that:
//1 + num*3
//Doesnt alter the result
}
System.out.println("num: "+num);
loops++;
}
System.out.println("total loops: "+loops);
}
}

need to determine the positive, negative and zero numbers in program and add all the positive and negative numbers separately [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I need to determine the positive, negative and zero numbers in a program and add all the positive and negative numbers separately. I'm using while loop (can use do-while) because for loop and array is not allowed. Badly need your help. Here's my code. The code should allow entering 10 numbers before determining.
public class Mix22 {
public static void main(String[] args) {
Scanner ety = new Scanner(System.in);
int count=0;
int positive=0;
int negative =0;
int num=0;
System.out.println("Enter a number: ");
num = ety.nextInt();
while(num!=10){
if(num<0)
negative++;
if (num>0)
positive++;
System.out.println("Enter a number: ");
num = ety.nextInt();
}
System.out.println("Negative numbers in the program: " + negative);
System.out.println("Positive numbers in the program: " + positive);
}
}
Is the problem that you want to run the loop 10 times? You've got a count variable that you are not otherwise using. The loop should look something like:
int count=0;
while (count != 10) {
...
++count;
}
Conventionally a for loop is used for this (if allowed):
for (int count=0; count<10; ++count) {
...
}

How could I add a while loop into my code when there's already if statements [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Have seen other posts, but I don't know when to enter the while loop or for loop for my program run until it meets conditions, which is enter a number between 1 and 20 and the run the code.
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number, total;
System.out.println("Please enter an integer from 1 to 20:");
number = scanner.nextInt();
if (number >= 21){
System.out.println("Your integer must be between 1 and 20.");
}
else if ( number <= 0){
System.out.println("Your integer must be between 1 and 20.");
}
else {
for(int i = 1; i<=20; i++){
total = number * i;
System.out.println(i + " X " + number + " = " + total);
}
}
}
}
Put a while loop around the scanner input
while(number < 0 || number > 20)
{
number = scanner.nextInt();
// if statements here
}
With this, you will need to initialize number so that you get into the loop
int number = -1;

Creating a random output from an user input array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
public class decisionMaker {
public static void main(String args[]) {
String option[] = new String[10];
// Output
for (int i = 0; i <= 9; i++) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the next option:");
option[i] = input.next();
System.out.println(" ");
}
for (int i = 0; i <= 9; i++) {
System.out.println("option: ");
System.out.println("option[i]+" ");
}
// Output
}
I'm trying to figure out how to add a count to the options, exit and end the program after entering a certain letter or number, and how to create a random output from the user input. I want it to give me one option that I had input at random. Can anyone help me with one or a few of these things. I'm trying to learn to code on my own, and I'm stuck on these.
Randomness
You can generate random numbers using java.util.Random;:
import java.util.Random;
public class SomeClass{
static Random rand = new Random();
public static void main(String args[]){
System.out.println(rand.nextInt());
}
}
About some broken code:
If you want to print out the value of a variable with System.out.println() then you need only type the variable without any quotation marks. The code you've written below will not compile:
System.out.println("option: ");
System.out.println("option[i]+" ");
Assuming that's what you want to do, it should instead be written as:
System.out.println("option: ");
System.out.println(option[i]);
Or even System.out.println("option: \n"+option[i]);
(The escape sequence \n when placed inside of quotation marks just indicates to the console to add a new line.)
Scanner:
Additionally, as nick zoum pointed out, your Scanner object should be initialized outside of the for loop, such as right underneath of the main() method.
Please comment below if you need clarification or if I misunderstood what you were looking for. It was very hard to understand your question.
You could try something like this:
public class DecisionMaker {
public static void main(String[] args) {
// output
Scanner scanner = new Scanner(System.in);
int size = getInt(scanner);
String option[] = new String[size];
for (int index = 0; index < size; index++) {
System.out.print("Enter the next option:");
option[index] = scanner.next();
}
int index = (int) (Math.random() * size);
System.out.println(option[index]);
scanner.close();
// output
}
public static int getInt(Scanner scanner) {
int size = 0;
while (size <= 0) {
if (scanner.hasNext()) {
if (scanner.hasNextInt()) {
size = scanner.nextInt();
}
}
if (size <= 0) {
System.out.println("The input: " + scanner.next() + " is not a valid value.");
}
}
return size;
}
}
How the program works:
The Scanner is initialized in the beginning and there is only
one instance of it.
Then the program will wait until the user inserts a valid number for
the size of options.
The next 5 lines were essentially copied from your code.
Finally we get a random Integer in the range of 0 - (size - 1) and print
the String of the array with that index.

Categories