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.
Related
This is the code:
import java.util.Scanner;
public class javapractice {
public static void main(String[] Args) {
int XX = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter Number :");
int number = input.nextInt();
boolean nextint = input.hasNextInt();
if (nextint) {
count++;
XX += number;
} else {
break;
}
input.nextLine();
}
int YY = XX/count;
System.out.println("SUM = " + XX + " AVG = " + YY);
input.close();
}
}
I want the output to print the sum of the numbers entered and when I enter let's say a word like "Hello", it breaks out of the loop and prints Sum 0 0 and AVG = 0.
The issue I'm having is that whenever I enter the number, it asks me for it two times and doesn't take the next number in the row after that and whenever I enter a string variable lets say "I", it outputs Inputmismatch. What would be the fix to this?
Don't mix nextLine() and all the other next methods; pick one. If you want to read a line's worth of text, just call next(), but if you want the input to flow as 'everytime a user hits enter, read another token', which you usually do, update the definition of 'what defines a token?': scanner.useDelimiter("\r?\n");.
Try this code:
int XX = 0;
int count = 0;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter Number: ");
if (input.hasNextInt()) {
count++;
XX += input.nextInt();
} else {
break;
}
}
int YY = XX / count;
System.out.println("SUM = " + XX + " AVG = " + YY);
input.close();
I'm trying to make a method that gets the user's input of 6 numbers and add them to a Tree set of integers. I'm trying to make a try and catch exception so if the users accidentally enters in a letter it'll catch the exception and ask them to enter in a number. Right now the program crashes when you try to enter in a letter. It'll print out "Invalid" then crashes. I'm not sure whats going on. Can anyone provide some insight?
public static Set<Integer> getTicket()
{
int userInput;
TreeSet<Integer> getNumbers = new TreeSet<Integer>();
Scanner input = new Scanner(System.in);
System.out.println("Enter your 6 numbers between 1-40: ");
for (int i = 0; i<6 ; i++)
{
try
{
System.out.print(i+1 + ": ");
userInput = input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("Invalid");
userInput = input.nextInt();
}
getNumbers.add(userInput);
}
System.out.println("Your ticket was: " + getNumbers);
return getNumbers;
}
Just a few notes on some of the changes made. From your original code, one thing I noticed that is not really an error but a head scratcher. Both of your methods (getWinning Numbers() and getTicket() ) returned a Set<integer> set, however you did not use it in main. So I simply took the output from the methods and placed them in the main method, where they should be IMHO. Methods like these should do ONE thing and in this case is return a set of integers. No printing or anything else that’s all it does.
I changed the logic in the getTicket() method. I simply set up a loop that continued until you had 6 valid numbers. Inside that loop I use a try statement to weed out the invalid input. The way the try statement is set up is one of many ways that you could accomplish this. As you can see the statement immediately after the try (guess = Integer.parseInt(userInput);) is where the invalid input problem could pop up and throw a NumberFormatException. If the input is invalid, you drop immediately to the catch where we output a message and continue. If the input is valid then we simply check for duplicates and the range of the number. If the numbers are ok then add it to pickedNumbers and increment numberCount.
public class Lottery
{
public static Set<Integer> generateWinningNumbers()
{
Random rndNumbers = new Random();
TreeSet<Integer> winningNumbers = new TreeSet<Integer>();
int max = 40;
int min = 1;
int range;
int sixNum;
for (int i = 0; i < 6; i++)
{
range = max - min + 1;
sixNum = rndNumbers.nextInt(range) + min;
while (winningNumbers.contains(sixNum))
{
sixNum = rndNumbers.nextInt(range) + min;
}
winningNumbers.add(sixNum);
}
return winningNumbers;
}
public static Set<Integer> getTicket(Scanner input)
{
String userInput;
int guess;
TreeSet<Integer> pickedNumbers = new TreeSet<Integer>();
System.out.println("Enter your 6 numbers between 1-40: ");
int numberCount = 1;
while(numberCount < 7)
{
System.out.print(numberCount + ": ");
userInput = input.nextLine();
try
{
guess = Integer.parseInt(userInput);
if( guess > 0 && guess < 41 && (!pickedNumbers.contains(guess)) )
{
pickedNumbers.add(guess);
numberCount++;
}
else
{
if (pickedNumbers.contains(guess))
{
System.out.println("Number already picked: " + guess);
}
else
{
System.out.println("Invalid number. Pick a number between 1-40: " + guess);
}
}
}
catch (NumberFormatException e)
{
// bad input
System.out.println("Invalid input: " + userInput);
}
}
return pickedNumbers;
}
}
Changes in the Main now take advantage of the methods returning a Set of integers for us. We create two Set<Integer> variables (winningTicket and userTicket) then we simply get the returned sets from the methods and output the results as opposed to printing the results from the methods.
public static void main(String[] args) throws IOException
{
Scanner userInput = new Scanner(System.in);
boolean done = false;
String yesNo;
Set<Integer> winningTicket;
Set<Integer> userTicket;
while(!done)
{
winningTicket = Lottery.generateWinningNumbers();
userTicket = Lottery.getTicket(userInput);
System.out.println("Your ticket was: " + userTicket);
System.out.println("Winning Numbers: " + winningTicket);
System.out.print("\nWould you like to try again? ");
yesNo = userInput.nextLine();
if(!yesNo.equalsIgnoreCase("y"))
{
System.out.println("Done");
done = true;
}
}
userInput.close();
}
Hope this helps
This happens because you don't catch exceptions inside cath block. for loop doesn't look good here, try while:
public static Set<Integer> getTicket()
{
int userInput;
TreeSet<Integer> getNumbers = new TreeSet<Integer>();
Scanner input = new Scanner(System.in);
System.out.println("Enter your 6 numbers between 1-40: ");
int correct = 0;
while(correct < 6)
{
try
{
System.out.print((correct+1) + ": ");
userInput = input.nextInt();
getNumbers.add(userInput);
correct++;
}
catch (InputMismatchException e)
{
System.out.println("Invalid input");
}
}
System.out.println("Your ticket was: " + getNumbers);
return getNumbers;
}
Also you cant't print collection that simple:
System.out.println("Your ticket was: " + getNumbers);
What you can do, is to use streams:
System.out.println("Your ticket was: " + getNumbers.stream().map(Object::toString).collect(Collectors.joining(" ")));
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));
I have an assignment, and I need to use a loop to allow a user to enter ten different numbers in a programme which then adds up the variables.
I have found various pieces of code and stitched them together to create this:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
String totalNum, num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
Scanner in = new Scanner (System.in);
System.out.println("Please enter ten numbers:");
int[] inputs = new int[10];
for (int i = 0; i < inputs.length; ++i)
{
inputs[i] = in.next();
}
//Process
totalNum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10;
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
It's not great, but it's the best I have so far. Please help?
You don't need the variables num1 to num10. You can simply sum up in the loop itself. Like:
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += = in.next(); // sum = sum + in.next();
}
Furthermore you assigned your variables as Strings, but you need int. In your case it would print something like 1111111111, if the input would always be a 1.
Take a look here how you would handle Integers properly.
You can achieve that in two ways, either inside the loop itself just add the number or if you need to keep track of them for later just add them to the array.
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
String total;
Scanner in = new Scanner (System.in);
int numOfInputValues = 10;
System.out.println("Please enter ten numbers:");
int[] inputs = new int[numOfInputValues];
for (int i = 0; i < numOfInputValues; ++i)
{
// Append to array only if you need to keep track of input
inputs[i] = in.next();
// Parses to integer
total += in.nextInt();
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
}
}
First of all, your class should be in CamelCase. First letter is always in capital letter.
Second, you don't need an array to save those numbers.
Third you should make a global variable that you can change with ease. That is a good practice.
And you should always close stream objects like Scanner, because they leak memory.
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
int numberQuantity = 10;
int totalNum = 0;
Scanner in = new Scanner(System.in);
System.out.println("Please enter ten numbers:");
for (int i = 0; i <= numberQuantity; i++) {
totalNum += in.nextInt();
}
in.close();
System.out.println(totalNum);
}
}
So the simplest answer I found is:
import javax.swing.*;
import java.util.Scanner;
public class exercise6
{
public static void main (String []args)
{
//Input
int totalNum, num1;
totalNum = 0;
for (int numbers = 1 /*declare*/; numbers <= 10/*initialise*/; numbers ++/*increment*/)
{
num1 = Integer.parseInt(JOptionPane.showInputDialog("Input any number:"));
totalNum = totalNum + num1;
}
//Output
JOptionPane.showMessageDialog(null, "Total = " + totalNum);
Try this way I only re-edit your code:
import javax.swing.*;
public class InputNums {
public static void main(String[] args) {
int total = 0;
for (int i = 0, n = 0; i < 10;) {
boolean flag = false;
try {
n = Integer.parseInt(JOptionPane
.showInputDialog("Input any number:"));
} catch (NumberFormatException nfe) {
flag = true;
}
if (flag) {
flag = false;
JOptionPane.showMessageDialog(null,
"Invalid no Entered\nEnter Again...");
continue;
}
total += n;
i++;
}
JOptionPane.showMessageDialog(null, "Total = " + total);
}
}
My program is to enter 10 numbers and add them together then display the result. Then I am to divide the smaller number by the larger number and display the result. Users cannot enter characters or zero.
I am new and have been working on this for DAYS. I do not see my mistake.
Now my problem is the Variable i isn't being recognized.
I introduced an Exception (try..catch) and it wouldn't read. I tried moving things all over (I'm new, I'm guessing and seeing what does what..) I did something wrong and probably something stupidly small. I need some help and fresh eyes.
I also need to end the program when the user enters 9999. Any idea where that would go? 'Cause I'm about to break out into tears.
public static void main(String[] args) throws NumberFormatException {
Scanner in = new Scanner(System.in);
Scanner input = new Scanner(System.in);
double[ ] digit = new double[11];
int sum = 0;
//Declare an array
System.out.print("Please Enter Ten Numbers:");
System.out.println();
try{
for (int i = 1; i < digit.length; i++)
System.out.print("Numbers " + i + ": ");
digit[i] = (double)in.nextInt(); //Array Not recognized here
sum += (int)digit[i];//Or recognized here
// Input the data into array from the user.
if(digit[i]==0.0)//None of these are recognized either, what did I do?
{
System.out.println("You can't enter zero. Try again");
--i; //nope
in.nextLine();//dispose of wrong number
}
}catch (NumberFormatException e){
System.out.println("You Can Only Enter Numbers!");
--i; //nope, not recognizing here either
in.nextLine();//dispose of wrong input
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println();
System.out.println("Would you like to divide the values?");
System.out.println("Yes or No to Exit the Program");
String a = input.next();
if(a.equalsIgnoreCase("yes")){
double [] divisionResult = new double[digit.length / 2];
//Division array declared
for (int i = 1; i < digit.length; i += 2)
//These are all good and recognized. No problem with the division part
{
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult [i / 2] = result;
System.out.println(result);
}
}
else if(a.equalsIgnoreCase("no")){
System.exit(0);
}
}
}
}
You for loop doesn't have braces around it. Only the first line below it is part of the loop.
You need braces around the contents of your for loop.
I have tried to modified the attached code snippet. Hope this might help you.
package com.so.general;
import java.util.Scanner;
public class AddNumbers
{
private static final int SIZE_OF_ARRAY = 10;
public static void main(String[] args)
{
int counter = 0;
double sumOfTenDigits = 0.0;
double[] digit = new double[SIZE_OF_ARRAY];
int listOfElements = digit.length;
System.out.print("Please Enter Ten Numbers:"+"\n");
Scanner readInputFromUser = new Scanner(System.in);
try
{
for (counter=0; counter<listOfElements; counter++)
{
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
if(digit[counter] == 0.0)
{
System.out.println("Zero is not allowed. Please try again.");
System.out.print("Numbers " + (counter+1) + ": ");
digit[counter] = Double.parseDouble(readInputFromUser.next());
}
sumOfTenDigits += digit[counter];
}
}
catch(NumberFormatException numberFormatExcep)
{
System.err.println(" You have entered other than numbers. Only numbers are allowed. Terminating the program.");
numberFormatExcep.printStackTrace();
System.exit(0);
}
System.out.println("Addition is: "+ sumOfTenDigits);
System.out.println("Would you like to divide the values? Press Y to continue, any other character to terminate the program.");
Scanner continueWithDivide = new Scanner(System.in);
String userInput = continueWithDivide.nextLine();
closeScanner(readInputFromUser);
closeScanner(continueWithDivide);
if(readInputFromUser != null)
{
readInputFromUser.close();
}
// Always use static string literals on the left hand side.
// This prevents Null pointer exception.
if("Y".equalsIgnoreCase(userInput))
{
double[] divisionResult = new double[listOfElements/2];
for(int i=0; i<listOfElements; i+=2)
{
double result = digit[i];
if (result > digit[i+1])
{
result = result/digit[i+1];
}
else
{
result = digit[i+1]/result;
}
divisionResult[i/2] = result;
System.out.println(result);
}
}
else
{
System.out.println("You have entered "+userInput+". Terminating the program.");
System.exit(0);
}
}
/**
* Closed the scanner
* #param scanner
*/
public static void closeScanner(Scanner scanner)
{
if(scanner != null)
{ try
{
scanner.close();
}
catch(IllegalStateException illegatStateExcep)
{
System.err.println("Scanner is already closed.");
illegatStateExcep.printStackTrace();
}
}
}
Please note the below points:
Always use proper indentation.
Always match { }
Even if your if or for is having only one statement, use { }.
For example:
for (int counter=1; i<digit.length; i++)
{
System.out.print("Numbers " + i + ": ");
}
Above three points will save a lot of your time if some thing goes wrong in your program.
Use proper name for the variables and method.
Always close the IO resources after the use.
For example:
if(scanner != null)
{
scanner.close();
}