Do-While Loop not looping - Java - java

I am having a problem with my java code below. I want the loop to stop when the number "-100" but it stops as soon as you enter any number. I'm just learning how to use java so there could be plenty of mistakes here.
public static void main(String[] args){
Scanner keyboard = new Scanner (System.in);
String num = "";
do {
System.out.println("Enter a number: ");
int n = keyboard.nextInt();
System.out.println("The number you entered is: " +n);
System.out.println("------------------------");
} while ("-100".equals(num));
}
}

num is always the empty string, because you never change the value of num. You update n. Which is what I would base the loop on. Like,
Scanner keyboard = new Scanner(System.in);
int n;
do {
System.out.println("Enter a number: ");
n = keyboard.nextInt();
System.out.println("The number you entered is: " + n);
System.out.println("------------------------");
} while (n != -100);
That is, do loop while n is not -100.

Related

Average calculator with user input Java - " java.util.NoSuchElementException: No line found "

I'm creating a simple average calculator using user input on Eclipse, and I am getting this error:
" java.util.NoSuchElementException: No line found " at
String input = sc.nextLine();
Also I think there will be follow up errors because I am not sure if I can have two variables string and float for user input.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
String input = sc.nextLine();
float num = sc.nextFloat();
float sum = 0;
int counter = 0;
float average = 0;
while(input != "done"){
sum += num;
counter ++;
average = sum / counter;
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
Thanks a lot:)
First, the precision of float is just so bad that you're doing yourself a disservice using it. You should always use double unless you have a very specific need to use float.
When comparing strings, use equals(). See "How do I compare strings in Java?" for more information.
Since it seems you want the user to keep entering numbers, you need to call nextDouble() as part of the loop. And since you seem to want the user to enter text to end input, you need to call hasNextDouble() to prevent getting an InputMismatchException. Use next() to get a single word, so you can check if it is the word "done".
Like this:
Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
if (sc.hasNextDouble()) {
double num = sc.nextDouble();
sum += num;
counter++;
} else {
String word = sc.next();
if (word.equalsIgnoreCase("done"))
break; // exit the forever loop
sc.nextLine(); // discard rest of line
System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
}
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
Sample Output
Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0
So there are a few issues with this code:
Since you want to have the user either enter a number or the command "done", you have to use sc.nextLine();. This is because if you use both sc.nextLine(); and sc.nextFloat();, the program will first try to receive a string and then a number.
You aren't updating the input variable in the loop, it will only ask for one input and stop.
And string comparing is weird in Java (you can't use != or ==). You need to use stra.equals(strb).
To implement the changes:
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
float sum = 0;
int counter = 0;
String input = sc.nextLine();
while (true) {
try {
//Try interpreting input as float
sum += Float.parseFloat(input);
counter++;
} catch (NumberFormatException e) {
//Turns out we were wrong!
//Check if the user entered done, if not notify them of the error!
if (input.equalsIgnoreCase("done"))
break;
else
System.out.println("'" + input + "'" + " is not a valid number!");
}
// read another line
input = sc.nextLine();
}
// Avoid a divide by zero error!
if (counter == 0) {
System.out.println("You entered no numbers!");
return;
}
// As #Andreas said in the comments, even though counter is an int, since sum is a float, Java will implicitly cast coutner to an float.
float average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\" at end : ");
String input = scanner.nextLine();
float num = 0;
float sum = 0;
int counter = 0;
float average = 0;
while(!"done".equals(input)){
num = Float.parseFloat(input); // parse inside loop if its float value
sum += num;
counter ++;
average = sum / counter;
input = scanner.nextLine(); // get next input at the end
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}

How to avoid having to declare a new scanner inside do while loop

I have created a program that allows a user to keep guessing numbers until they either guess the correct number or enter end. I have used a do-while loop to do this. When I create a new scanner inside the loop body it works as expected. However if I create it outside the loop body, it works fine if the input is integers or the first input is end However if the input end follows integer inputs it doesn't
pick up the nextLine() until the next loop. Is there a way to do this without having to creat a new scanner object each time.
private static void guessingGame() {
Scanner sc = new Scanner(System.in);
int answer = 7;
String input = "";
int number = 0;
do {
//Scanner sc = new Scanner(System.in);
System.out.print("Guess a number between 1 and 10 or end to finish ");
System.out.println("input at start is: " + input);
boolean b = sc.hasNextInt();
if(b) {
number = sc.nextInt();
System.out.println("number is: " + number); //for testing code
}else {
input = sc.nextLine();
System.out.println("input is: " + input); //for testing code
}
if (number == answer) {
System.out.println("Correct Guess");
break;
}else {
if(input.equals("end")) System.out.println("Hope you enjoyed the game");
else System.out.println("Incorrect Guess, try again ");
}
System.out.println("input before while is: " + input); //for testing code
}while(number != answer && !(input.equals("end")));
}
Example output for when end follow an integer input:enter code here
number is: 3
Incorrect Guess, try again
input before while is:
Guess a number between 1 and 10 or end to finish input at start is:
end
input is:
Incorrect Guess, try again
input before while is:
Guess a number between 1 and 10 or end to finish input at start is:
input is: end
Hope you enjoyed the game
input before while is: end
you can solve this by using a while loop .
See the following code.
private static void guessingGame() {
Scanner sc = new Scanner(System.in);
int answer = 7;
String input = "";
int number = 0;
while(!input.equals("end")) {
//Scanner sc = new Scanner(System.in);
System.out.print("Guess a number between 1 and 10 or end to finish ");
System.out.println("input at start is: " + input);
boolean b = sc.hasNextInt();
if(b) {
number = sc.nextInt();
System.out.println("number is: " + number); //for testing code
}else {
input = sc.next(); //Edited here . Changed nextLine() to next().
System.out.println("input is: " + input); //for testing code
}
if (number == answer) {
System.out.println("Correct Guess");
break;
}else {
if(input.equals("end")) System.out.println("Hope you enjoyed the game");
else System.out.println("Incorrect Guess, try again ");
}
System.out.println("input before while is: " + input); //for testing code
}
}
In here , at first , input will always be empty String . On while loop, it gets assigned to your String input i.e, end . Till it encounters end , your loop will be running.
Edited
Change input=sc.nextLine(); to input=sc.next(); . This is because , your scanner waits for next Line and doesn't consider "end" as input string .

Exiting from while loop not working in java

I am new to java programming.I want to calculate the sum and want to exit the program if user enters "N" and again loop if user enters "Y".But,it is not getting me out of loop even I enter "N".
public class Program {
public static void main(String[] args) {
boolean a=true;
while (a) {
System.out.println("enter a number");
Scanner c=new Scanner(System.in);
int d=c.nextInt();
System.out.println("enter a number2");
Scanner ce=new Scanner(System.in);
int df=ce.nextInt();
int kk=d+df;
System.out.println("total sum is"+kk);
System.out.println("do you want to continue(y/n)?");
Scanner zz=new Scanner(System.in);
boolean kkw=zz.hasNext();
if(kkw) {
a=true;
}
else {
a=false;
System.exit(0);
}
}
}
I didnt know where I made the mistake? Is there any other way?
First of all, your a variable is true if scanner.hasNext() is true, leading to a being true with every input, including "N" which means, your while loop will keep on going until there are no more inputs.
Second of all, you could optimize your code the next way:
I suggest getting rid of a and kkw to make your code cleaner and shorter.
Use only one Scanner and define it outside of the loop. You don't need more than one Scanner for the same input. Also, initializing a Scanner with every loop is resource-consuming.
Use meaningful variable names. Programming should not only be efficient, but also easy to read. In this tiny code it's a minor issue but imagine having an entire program and, instead of adding features and bug-fixing, you had to search for the meaning of every variable.
Here's an optimized and working version of your code:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a number");
int input1 = scanner.nextInt();
scanner.nextLine(); // nextInt() doesn't move to the next line
System.out.println("Enter a second number:");
int input2 = scanner.nextInt();
scanner.nextLine();
System.out.println("Total sum is " + (input1 + input2)); /* Important to
surround the sum with brackets in order to tell the compiler that
input1 + input2 is a calculation and not an appending of
"Total sum is "*/
System.out.println("Do you want to continue? (Y/N)");
if (scanner.hasNext() && scanner.nextLine().equalsIgnoreCase("n"))
break;
}
scanner.close();
try (Scanner in = new Scanner(System.in)) {
boolean done = false;
while (!done) {
System.out.println("enter first number");
int d = in.nextInt();
System.out.println("enter second number");
int df = in.nextInt();
int kk = d + df;
System.out.println(String.format("total sum is %d", kk));
System.out.println("do you want to continue(y/n)?");
String cont = in.next();
done = cont.equalsIgnoreCase("n");
}
} catch(Exception e) {
e.printStackTrace();
}

Reverse integer including 0's in java

I have to do a program that returns the reverse of a number that is input by a user, event the numbers that start and finish with 0 (ex. 00040, it would print 04000)
I was able to do the reverse of the number, but it doesn't print out the 0's and I can't use String variables, just long variables or integers.
Here is my code:
import java.util.Scanner;
public class Assignment_2_Question_2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Welcome to Our Reversing Number Program");
System.out.println("-----------------------------------------");
System.out.println();
System.out.println("Enter a number with at most 10 digits:");
long number = keyboard.nextInt();
long nbDigits = String.valueOf(number).length();
System.out.println("Number of digits is " + nbDigits);
System.out.print("Reverse of " + number + " is ");
long revNumber = 0;
while (number > 0){
long digit = number % 10;
if (digit == 0){ // The teacher told me to add this
nb0 ++; // need to not take into account the 0's inside the number
}
revNumber = revNumber * 10 + digit;
number = number/10;
}
for (int i = 0; i < nb0; i++) { // This will print the number of 0's counted by the if statement and print them out.
System.out.println("0");
}
System.out.println(revNumber);
String answer;
do{
System.out.println("Do you want to try another number? (yes to repeat, no to stop)");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes")){
System.out.println("Enter a number with at most 10 digits:");
long otherNumber = keyboard.nextInt();
long nbrDigits = String.valueOf(otherNumber).length();
System.out.println("Number of digits is " + nbrDigits);
System.out.print("Reverse of " + otherNumber + " is ");
long reversedNumber = 0;
while (otherNumber != 0){
reversedNumber = reversedNumber * 10 + otherNumber%10;
otherNumber = otherNumber/10;
}
System.out.println(reversedNumber);
}
else
System.out.println("Thanks and have a great day!");
}while(answer.equalsIgnoreCase("yes")&& !answer.equalsIgnoreCase("no"));
}
}
Can someone help me? Thank you
Probably not what is intended but clearly (based on problem statement) you must see all digits entered (to include leading 0's) otherwise it is an "impossible solution" - and you state you cannot receive input as a String...
So this snippet reads one digit at a time where each digit is received as an int:
Scanner reader = new Scanner(System.in);
reader.useDelimiter(""); // empty string
System.out.print("Enter number: ");
while (!reader.hasNextInt()) reader.next();
int aDigit;
int cnt = 0;
while (reader.hasNextInt()) {
aDigit = reader.nextInt();
System.out.println("digit("+ ++cnt + ") "+aDigit);
}
System.out.println("Done");
Prints (assume user enter 012 (enter)):
Enter number: digit(1) 0
digit(2) 1
digit(3) 2
Done
You naturally have more work to do with this but at least you have all user entered digits (including leading zeros).
You can use buffer reader;
Like this given code And if you want to do some arithmetic operations in the numbers then you can convert it into int using parseInt method.:-
import java.util.Scanner;
import java.lang.*;
class Main {
public static void main(String args[])
{
System.out.println("ENTER NUM");
Scanner SC = new Scanner(System.in);
String INP = SC.nextLine();
StringBuffer SB = new StringBuffer(INP);
SB.reverse() ;
System.out.println(SB);
}
}

Asking the user what size the array should be

import java.util.Scanner;
/**
* Created by b00598439 on 30/09/2015.
*/
public class Assessment1 {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter number 1 for arrays, 2 to use ArrayLists, or any other number to end the program");
for (int i = 1; i<=2; i=>3; i++){
answer[i] nextInt(); //Get integer entered, if different from 1 or 2, if any other number then quit
}
System.out.println("What size of array would you like?");
int SIZE = in.nextInt(); //What size should the array be?
int [] answer = new int[SIZE]; //Lets user read into the program
System.out.println("The total of the numbers in the program is: " + answer); //Gives total of numbers
System.out.println("The average of the numbers in the program is: " + avg);
int count = 0;
for (int i = 0) ; //Calculating the average
I have been trying to get the code sorted to write to screen and follow on through for the size of the array. I have to get the user to select an option 1, or option 2, if option 1 or 2 isn't chosen then I have to terminate the program. I cannot even get the first part printing or working and this is what I have to do:
1) If the array option is chosen, the program should:
• Ask the user what the size of the array should be
• Let the user read in the numbers into the array
• Output the total of the numbers stored in the array
• Output the average of the numbers stored in the array
I have been sitting here for 4 hours and still getting nowhere
Any help would be appreciated
This can be done in many ways,I have done it in a simple way so you can understand the whole code step by step.By the way,you haven't explained what you want the program to do if option 2 was chosen.You can remove the option 2 by deleting the "case 2:".See the code.
import java.util.Scanner;
public class Assessment1 {
public static void main (String args[]) {
int average,sum=0;
Scanner input = new Scanner(System.in);
Scanner length = new Scanner(System.in);
Scanner option = new Scanner(System.in);
System.out.println("Enter 1 for arrays, 2 to use ArrayLists, or any other number to end the program");
int x=option.nextInt();
switch(x){
case 1:
System.out.println("Input array size: ");
int len=length.nextInt();
int[] numbers = new int[len];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
sum += numbers[i];
}
average=sum/len;
System.out.println("Total sum of all numbers: "+sum);
System.out.println("Average of all numbers: "+average);
case 2:
//insert your "ArrayList code here,you haven't explained what you want here
default:
System.out.println("Program terminated.");
}
}
}
Ok, I developed a little more the code. I put it inside a while loop... it goes back to the beginning and asks to again to enter the options... you enter any number other than 1 or 2 and you get out. I tested it and it works ok in the console. Just a comment.. you are getting the average in integer values... if you would like to get doubles then you have to use doubles and use nextDouble instead of nextInt. Hope that it helps.
import java.util.Scanner;
public class Assessment{
public static void main(String[] args){
// Scanner to get the initial number options
Scanner in = new Scanner(System.in);
// Scanner to get numbers to sum
Scanner numSc = new Scanner(System.in);
// Declaration of variables and array
int answer = 0; //You need int answer, don't need an array by now
int numAnswer;
int sum = 0;
int average;
// Loop the program
while (true){
System.out.println("Enter number 1 for arrays, 2 for arraylists, any other to quit");
// Using in Scanner to test for integer input
if(in.hasNextInt()){
// If there is an integer then give it to numAnswer
numAnswer = in.nextInt();
// What to do if the option is 1, 2 or other number
switch(numAnswer)
{
case 1:
case 2:
answer = numAnswer;
break;
default:
System.exit(0); // Out of the program
}
}
// If answer variable got number 1
if (answer == 1){
// New Scanner to get the size of the array
Scanner sizeSc = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
// Getting the size of the array with sizeSc Scanner
int size = sizeSc.nextInt();
// Making a new array with the size of size variable
int[] inputNums = new int[size];
// Looping to get input numbers
for (int i = 0; i < inputNums.length; i++){
System.out.println("Enter a number in the array: ");
//Getting the numbers from console with numSc Scanner
inputNums[i] = numSc.nextInt();
sum += inputNums[i]; //Getting the sum of each number
}
average = (sum/size);
System.out.println("Sum of numbers: " + sum);
System.out.println("Average of numbers: " + average);
System.out.println(" ");
} else {
System.out.println("YOUR CODE TO THE LISTARRAY");
}
}
}
}

Categories