Using scanner input to make a for loop - java

I am trying to make a sort of ATM. I want the program to do the following: If a user enters a number, the number gets multiplied by 12.
I already have the following code:
import java.util.Scanner;
public class DisplayMultiples {
public static void main(String args[]) {
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
keyboardInput.nextLine();
int b = 12;
if() {
for (int i = 1; i < b; i++) {
System.out.println(i*b);
}
else {
System.out.println("Error, this value is never used");
}
}
}

Convert the input to a number.
If the input is not a number, show error message, and exit.
If the input is a number, multiply it by 12, show result, and exit.

The easiest way is to get an int from the Scanner and then check if it's between 1 and 12, and if so, multiply it by 12.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
int number = keyboardInput.nextInt();
if (number > 0 && number < 13) {
System.out.println(number * 12);
} else {
System.out.println("Error, this value is never used");
}
Note that as you are likely a beginner, entering anything but an int in the console will result in an error but I assume that's not entirely necessary for you. If it is, read up on try...catch.

This way will avoid exceptions when entering non numbers.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
String inpStr = keyboardInput.nextLine();
int b = 12;
int inpVal = -1;
try {
inpVal = Integer.parseInt(inpStr);
} catch (NumberFormatException nfe) {
}
if (inpVal >= 1 && inpVal <= 12) {
System.out.println(inpVal * b);
} else {
System.out.println("Error, this value is never used");
}

Related

Why do I have to put an integer twice for my Scanner input to work?

I'm trying to make a simple program where you can put integers in, and it will tell you if it increased or decreased from the previous integer input. But when I run the code, I have to put an integer value twice, but I only want it put once.
The input and output should look like (numbers typed by me, words output by the program):
Starting...
5
Increasing
4
Decreasing
6
Increasing
etc. etc.
But instead it looks like:
Starting...
5
5
Increasing
Input Number:
1
2
Not Increasing
etc. etc.
This is my code:
import java.util.Scanner;
public class Prob1 {
public static void main(String[] args) {
System.out.println("Starting...");
int input;
int previousInput = 0;
Scanner scan = new Scanner(System.in);
while (!(scan.nextInt() <= 0)) {
input = scan.nextInt();
if (input > previousInput) {
System.out.println("Increasing");
previousInput = input;
} else {
System.out.println("Not Increasing");
previousInput = input;
}
System.out.println("Input Number:");
}
scan.close();
}
}
Why does this problem occur, and how can I fix it?
The loop behavior you are describing is:
read a numeric input value
do something with it (print a message)
if the loop value meets a condition (input is 0 or less), exit the loop
otherwise, repeat
Here's a "do-while" loop that reads like those steps above:
Scanner scan = new Scanner(System.in);
int input;
do {
input = scan.nextInt();
System.out.println("input: " + input);
} while (input > 0);
System.out.println("done");
And here's input+output, first entering "1", then entering "0":
1
input: 1
0
input: 0
done
while (!(scan.nextInt() <= 0)) { takes an int and then input = scan.nextInt(); takes another one. You need to change the while loop to use input.
modified based on your code
public static void main(String[] args) {
System.out.println("Starting...");
int input;
int previousInput = 0;
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Input Number:");
input = scan.nextInt();
if (input <= 0) {
System.out.println("app shut down");
break;
}
if (input > previousInput) {
System.out.println("Increasing");
} else {
System.out.println("Not Increasing");
}
previousInput = input;
}
scan.close();
}

Java lottery Machine Task

My task is to allow a user to input their lottery numbers and check if
they have won the jackpot.
The user should be given the chance to enter 4 numbers. Each number should be in the range 1-99. If
the user enters a number that is less than 1, or greater than 99, then the programme should prompt
them to enter a number in the correct range. You should use a while loop to ensure that the user inputs
the correct number. What should the exit condition of the while loop be?
I have tried making a while loop as the task asks me to do. this did not work. I am completely and utterly stuck.
String password = "MyNameJeff";
Scanner dave = new Scanner(System.in);
System.out.println("lottery numbers");
int UserInput = dave.nextLine();
while (!password.equals(UserInput)) {
System.out.println random math command <----
UserInput = dave.nextLine();
}
System.out.println("Lottery numbers here?");
This while loop will take the first userInput and check its range between 1 and 99 inclusive.
while(userInput < 1 || userInput > 99){
System.out.println("Please re-enter another lottery number: ");
userInput=dave.nextInt();
}
If it is not in the range 1 to 99, it will request the user to re-enter another lottery number.
the condition is when you want to stop the while loop. for example
you may want to stop when you have 4 numbers
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Scratch {
public static void main(String[] args) {
List<Integer> choices = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
boolean done = false;
//we set done to false, and the condition is "while !(not) done"
while (!done) {
try {
System.out.println("write lottery numbers:");
String userInput = scanner.nextLine();
Integer result = Integer.parseInt(userInput);
// compareTo is a bit tricky, read the javadoc for information
if (result.compareTo(0) < 0) {
System.out.println("dont add number less then 0");
continue;
}
if (result.compareTo(99) > 0) {
System.out.println("dont add number more then 99");
continue;
}
//adding more result is the only way done will be eventually true
choices.add(result);
//set to done when the size of the list is 4
done = choices.size() == 4;
} catch (NumberFormatException e) {
System.out.println("Only add number");
}
}
System.out.println("Lottery numbers here?");
choices.forEach(System.out::println);
}
}
Check this code
public static void main (String[]args) throws IOException, ParseException {
int [] winNumbers = new int[4];
int [] numbers = new int[4];
int indx=0;
System.out.println("Enter Lottery Numbers");
while (indx<4) {
System.out.println("Enter number: ");
Scanner dave = new Scanner(System.in);
try {
String in = dave.nextLine().trim();
int inNum = Integer.parseInt(in);
if (inNum>0 && inNum<100) {
numbers[indx] = inNum;
indx++;
continue;
}
}
catch (NumberFormatException | NullPointerException nfe) {
}
System.out.println("Please enter a number in the range 1-99");
}
Random rand = new Random();
for (int i=0; i<winNumbers.length; i++){
int r = rand.nextInt(98);//will get a random number between 0-98
r +=1; // for the number to be on the space 1-99
winNumbers[i]=r;
}
System.out.println("User entered: " + Arrays.toString(numbers));
System.out.println("Lottery numbers here: " + Arrays.toString(winNumbers));
}
Two int arrays are used with size 4.
One is filled using Scanner. There are some checks:
trim(): will remove any whitespace that the user might enter
catch: will catch a numberFormatException or null. It will print nothing.
If the code does not enter the if(inNum>0 && inNum<100) then the indx counter will not increment and the code will print the error message: Please enter a number...
The second part of the code generates 4 random numbers and stores them in the second array.
Finally, it prints the two arrays.

Count How many number multiple by the number from input user between a range

again I have a problem with doing practice prepare for the exam.
Would everyone help me? Thanks a lot
write a program input an integer in the range 100 to 200 inclusive. If the user enters invalid input then your algorithm should re-prompt the user until the input is valid. Your algorithm should then count how many numbers between 500 and 1000 which are multiples of the number input. Finally, the count should be output to the user. You should make good use of sub-modules.
Here my code
import java.util.*;
public class Exam3
{
public static void main(String args[])
{
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while(input < 100 || input > 200)
{
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count ++;
}
System.out.println("count is: " + count);
}
public static void int getCount(int input, int count)
{
for(int i = 499;i <= 1000; i++ )
{
if(i % input==0)
{
count++;
}
}
return count;
}
}
The algorithm should be:
Having correct input, find all multiples of it that are in range [500, 1000]. Count them.
It's a bad approach to check all the numbers, as we know from our math knowledge, that between k*a and k*a + a there is no number divisible by a.
Knowing that and having input we enlarge our temp initialized with value of input by input. If it's in range [500, 1000] we enlarge our counter. Simple as that.
public static void main(String args[]) {
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while (input < 100 || input > 200) {
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count++;
}
System.out.println(input + " fits " + count(input) + " times");
}
private static int count(int input) {
int result = 0;
int temp = input;
while (temp <= 1000) {
if (temp >= 500) {
result++;
}
temp += input;
}
return result;
}
According to your code, I see some issues. I'll point them out, as it is important for practicing Java.
Method can be either void or return int. You can't have void int. In this case, we return int, so int is the return type,
It's important to stick to Java styling. Don't put too many empty lines, keep indents.
Use Eclipse or IntelliJ (IntelliJ is more pro). They will point unused code blocks, so you would know that that getCount wasn't called.

A tiny issue with exception handling interactment - not the correct output

package test5555;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class Test5555 {
private static int[] randomInteger;
public static void main(String[] args) {
boolean validInput = false;
randomInteger = new int[100];
Random rand = new Random();
for (int i = 0; i < randomInteger.length; i++)
randomInteger[i] = rand.nextInt();
int indexPosition = 0;
Scanner input = new Scanner(System.in); {
System.out.println("Please enter an integer for the array index position: ");
while(!validInput)
{
try
{
indexPosition = input.nextInt();
validInput = true;
System.out.println(randomInteger[indexPosition]);
} catch ( InputMismatchException | IndexOutOfBoundsException ex) {
System.out.print("Please enter a valid integer between 0 and 100 or type quit to exit: ");
String s = input.next();
if(s.equals("quit")){
System.exit(0);
System.out.println(randomInteger[indexPosition]);
}
}
}
}
}
}
The code runs perfectly except for two minor hiccups that I cannot solve. When you run it you get Please enter an integer for the array index position:If you type a number above 100 or a string such as bob then you get Please enter a valid integer between 0 and 100 or type quit to exit:which is perfect. But if you type quit then you get Please enter a valid integer between 0 and 100 or type quit to exit: BUILD SUCCESSFUL (total time: 2 minutes 2 seconds) so it quits it but it repeats the exception statement which I do not want.
When you type a number above 100 and receive the Please enter a valid integer between 0 and 100 or type quit to exit: if you then type a correct integer the program will just turn off and it will say BUILD SUCCESSFUL instead of retrieving the number for you from the array
Replace your while loop code with below,
String s = null;
while(!validInput)
{
try
{
if(s != null){
indexPosition = Integer.parseInt(s);
}
else{
indexPosition = input.nextInt();
}
System.out.println(randomInteger[indexPosition]);
validInput = true;
} catch ( InputMismatchException | NumberFormatException | IndexOutOfBoundsException ex ) {
System.out.println("Please enter a valid integer between 0 and 100 or type quit to exit: ");
input.nextLine();
s = input.next();
if(s.equals("quit")){
System.exit(0);
}
}
}
Please read this to get more idea on Scanner.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
In your case the problem is (As per doc)
When a scanner throws an InputMismatchException, the scanner will not
pass the token that caused the exception, so that it may be retrieved
or skipped via some other method.
The behavior you describe in point 1 us not correct. If you type in a number and then quit it works "as expected"
If you type in a string such as "bob" your nextInt() fails with an InputMissmatchException which means your "input.next()" call in the catch clause will read "bob" and see it's not equal to "quit" and just go back to the loop and block and wait for an "int".
In point 2. You type an int and you get an exception...but you've set validInput to true already so you'll exit the loop. You need to set validInput after you print.
If I got your question correctly, I would implement little differently. Please check if it fulfills your requirement.
import java.util.Random;
import java.util.Scanner;
public class Test5555 {
private static int[] randomInteger;
public static void main(String[] args) {
randomInteger = new int[100];
Random rand = new Random();
int indexPosition;
for (int i = 0; i < randomInteger.length; i++)
randomInteger[i] = rand.nextInt();
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer for the array index position: ");
while(true) {
String strIndex = input.next();
if(strIndex.equals("quit")) break;
indexPosition = getIntVal(strIndex);
if(indexPosition < 0 || indexPosition >= randomInteger.length) {
System.out.print("Please enter a valid integer between 0 and "
+ randomInteger.length + " or type quit to exit: ");
continue;
}
System.out.println(randomInteger[indexPosition]);
break;
}
input.close();
}
protected static int getIntVal(String inputStr) {
int result = -1;
try {
result = Integer.parseInt(inputStr);
} catch(NumberFormatException e) {}
return result;
}
}
This part of your code is wrong
try
{
indexPosition = input.nextInt();
validInput = true;
System.out.println(randomInteger[indexPosition]);
} catch ( InputMismatchException | IndexOutOfBoundsException ex) {
You are saying that your indexPosition is right before to check it, the line
validInput = true;
Should be later of check if the array have that position.
Right code:
...
indexPosition = input.nextInt();
System.out.println(randomInteger[indexPosition]);
validInput = true;
....

Java Scanner Continuous User input?

For java practice, i am trying to create a program that reads integers from the keyboard until a negative one is entered.
and it prints the maximum and minimum of the integer ignoring the negative.
Is there a way to have continuous input in the same program once it runs? I have to keep running the program each time to enter a number.
Any help would be appreciated
public class CS {
public static void main(String []args) {
Scanner keys = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = keys.nextInt();
while(true)
{
if(n>0)
{
System.out.println("Enter again: ");
n = keys.nextInt();
}
else
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
}
Here is a part of my code - It works, but i think there is an easier way of doing what i want but not sure how!
import java.util.Scanner;
public class ABC {
public static void main(String []args) {
int num;
Scanner scanner = new Scanner(System.in);
System.out.println("Feed me with numbers!");
while((num = scanner.nextInt()) > 0) {
System.out.println("Keep Going!");
}
{
System.out.println("Number is negative! System Shutdown!");
System.exit(1);
}
}
}
You could do something like:
Scanner input = new Scanner(System.in);
int num;
while((num = input.nextInt()) >= 0) {
//do something
}
This will make num equal to the next integer, and check if it is greater than 0. If it's negative, it will fall out of the loop.
A simple loop can solve your problem.
Scanner s = new Scanner(System.in);
int num = 1;
while(num>0)
{
num = s.nextInt();
//Do whatever you want with the number
}
The above loop will run until a negative number is met.
I hope this helps you

Categories

Resources