Integer-restricted only? - java

How can I limit the input to only integers (no doubles etc)? simple question for someone experienced to answer. if input is anything other than double then display error message, with ability to enter input again
import java.util.Scanner;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int years;
int minutes;
System.out.println("Years to Minutes Converter");
System.out.print("Insert number of years: ");
years = reader.nextInt();
minutes = years * 525600;
System.out.print("That is ");
System.out.print(minutes);
System.out.print(" in minutes.");
}
}

Use Scanner.hasNextInt()
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
Example code:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt())
sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt())
sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
You don't have to parseInt or worry about NumberFormatException. Note that since hasNextXXX methods doesn't advance past any input, you may have to call next() if you want to skip past the "garbage", as shown above.

Ok I made this:
package reader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System. in );
int years;
int minutes;
String data = null;
System.out.println("Years to Minutes Converter");
boolean test = false;
while (test == false) {
System.out.print("Insert number of years: ");
String regex = "\\d+";
data = reader.next();
test = data.matches(regex);
if (test == false) {
System.out.println("There is a problem try again");
}
}
years = Integer.valueOf(data);
minutes = years * 525600;
System.out.print("That is ");
System.out.print(minutes);
System.out.print(" in minutes.");
}
}
It will say:
Years to Minutes Converter
Insert number of years: dsds
There is a problem try again
Insert number of years: ..
There is a problem try again
Insert number of years: 2
That is 1051200 in minutes.

Related

Why is my very simple while loop repeating one extra time?

Here is my while loop. The program sums up integers until a negative number is input. At that point the loop should break and it should print "Goodbye". However it is adding the negative number each time before it says goodbye. Im not sure what is going wrong here. Please help?!
import java.util.Scanner;
public class While {
public static void main(String[] args)
{
int input = 5;
int sum = 0;
while(input >= 0)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
sum = sum + input;
System.out.println("Running total: " + sum );
}
System.out.println("Goodbye!" );
}
Test:
Please enter a positive integer:
5
Running total: 5
Please enter a positive integer:
10
Running total: 15
Please enter a positive integer:
-1
Running total: 14
Goodbye!
I do not want to get the return value of 14, it should simply say Goodbye!
You need to use the break keyword. Your loop will always finish so the check on the while only happens after you've added the negative number. You could change to this:
while(true)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
if(input <0){
break;
}
sum = sum + input;
System.out.println("Running total: " + sum );
}
Or this:
while(input >= 0)
{
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
if(input <0){
break;
sum = sum + input;
System.out.println("Running total: " + sum );
}
}
Or to avoid if statements entirely if needed (though that isn't the point of loops):
while(input >= 0)
{
sum = sum + input;
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
System.out.println("Running total: " + sum );
}
Here was my solution:
while(input >= 0)
{
sum = sum + input;
System.out.println("Running total: " + sum );
System.out.println("Please enter a positive integer: ");
Scanner in = new Scanner (System.in);
input = in.nextInt();
}
System.out.println("Goodbye!" );
}
by calculating the sum at initialization and before the first integer is entered. It appears to work the way I want now. Thanks for your help.

Input Mismatch Exceptions

I've been instructed to create a code that takes a user's first 5 inputs (doubles) and finds the average. My only problem is creating an exception if a user inputs anything other than a number. Could someone show how I can add this exception to my code?
import java.util.*;
public class Test1
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
System.out.println("Please enter a number: ");
double first = numbers.nextInt();
System.out.println("Please enter a number: ");
double second = numbers.nextInt();
System.out.println("Please enter a number: ");
double third = numbers.nextInt();
System.out.println("Please enter a number: ");
double fourth = numbers.nextInt();
System.out.println("Please enter a number: ");
double fifth = numbers.nextInt();
System.out.println("The average is\t" + ((first + second + third + fourth + fifth)/5)+"\t");
}
}
This will handle the user typing non Integers.
It also removes the static Scanner userInput which isn't being used.
public class HelloWorld
{
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
int total =0;
int numberOfQuestion = 5;
for (int i = 0; i < numberOfQuestion ; i ++) {
System.out.println("Please enter a number: ");
while (!numbers.hasNextInt()) {
System.out.println("Input was not a number, please enter a number: ");
numbers.next();
}
total = total + numbers.nextInt();
}
System.out.println("The average is\t" + (total/numberOfQuestion)+"\t");
}
}

How can I read any user input from the scanner library?

I'm fairly new to java, so don't think this is some idiot. Anyways, I've been trying to make a program that can read a certain letter from the console and then decide which operation to use, let's say to add. However, I can't get an If loop to read the variable that decides which operator to use, here is the code, and please help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int number;
String function;
System.out.println("What Do You Want to Do? (a to add; s to" +
" subrtact; d to divited; m to multiply, and sq to square your nummber.)" );
function = user_input.next();
if (function == "sq"){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
}
(I made the description shorter so that it would fit).
This is just an example to get you started in the right direction.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num1, num2, result;
System.out.println("What Do You Want to Do? (a to add; s to"
+ " subrtact; d to divited; m to multiply, and s to square your nummber.)");
String choice = user_input.next();
// Add
if (Character.isLetter('a')) {
System.out.println("Enter first number: ");
num1 = user_input.nextInt();
System.out.println("Enter second number: ");
num2 = user_input.nextInt();
result = num1 + num2;
System.out.println("Answer: " + result);
}
}
}
If you use hasNext() on a scanner it will wait for an input until you stop the program. Also using equals() is a better way of comparing strings.
while(user_input.hasNext()){
function = user_input.next();
if (function.equals("s")){
System.out.print("Enter your number: ");
number = user_input.nextInt();
System.out.print(number * number);
} else {
System.out.println("Unidentified Function!");
}
}
Scanner s = new Scanner(System.in);
String str = s.nextLine();
int a=s.nextInt();
int b=s.nextInt();
if(str.equals("+"))
c=a+b;
else if(str.equals("-"))
c=a-b;
else if(str.equals("/"))
c=a/b;
// you can add operators as your use
else
System.out.println("Unidentified operator" );
I hope it helps!

Subtracting multiple numbers

I am trying to write a method that will subtract multiple numbers instead of using just 2 input numbers.
So far I have...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
double difference = 0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
double valueTwo = in.nextInt();
difference = value - valueTwo;
}
System.out.println("Difference: " + difference);
}
this currently only works with 2 inputs, but my end goal is to be able to continue subtracting multiple numbers.
Instead of continually subtracting from value, instead subtract from difference
Change difference = value - valueTwo; to difference -= valueTwo
This will be equivalent to doing ((A - B) - C) - ..., A being the first input, B the second input, C the third input...
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double difference = in.nextDouble();
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
This should work fine
#include <stdio.h>
int main()
{
int result=0, n,number,i;
printf("How many numbers you want to use?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d", &number);
if(i ==0 ){
result=number;
}
else{
result -= number;
}
}
printf("Answer is= %d ", result);
return 0;
}
Output:
How many numbers you want to use?
4
55
34
1
3
Answer is= 17
This solution doesn't hang after the first input. It is more user friendly.
public static void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the next number: ");
double difference = 0.0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
Why have two variables? Anyway, the following is simpler and prompts correctly:
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
while (true) {
in.nextLine(); // Silently discard rest of line
System.out.print("Please enter the next number, or . to stop: ");
if (! in.hasNextDouble())
break;
value -= in.nextDouble();
}
System.out.println("Difference: " + value);
Test
Please enter the number: 10
Please enter the next number, or . to stop: 1
Please enter the next number, or . to stop: 2
Please enter the next number, or . to stop: 3
Please enter the next number, or . to stop: .
Difference: 4.0

UnknownFormatConversionException in a program that prints a percentage

I have to write a program where I put in baseball stats and it comes out with slugging % batting avg and re says the name of the player then put it on a sentinel loop. My current code is below. I'm trying to get it to work with just one before I turn it into a loop. When I run to test, I get UnknownFormatConversionException. What does it mean? How can I fix my code?
import java.util.Scanner;
public class bata
{
public static void main(String[] args) throws Exception
{
double ba,sp,tb;
int tri,dou,sin,hr,ab,hits;
String name;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Singles");
sin = sc.nextInt();
System.out.print("Enter Doubles");
dou = sc.nextInt();
System.out.print("Enter Triples");
tri = sc.nextInt();
System.out.print("Enter Homeruns");
hr = sc.nextInt();
System.out.print("Enter At bats");
ab = sc.nextInt();
System.out.print("Enter Player name");
name = sc.nextLine();
System.in.read();
tb= (sin + (dou*2) + (tri *3) +(hr *4));
hits = sin+dou+tri+hr;
sp= tb/ab;
ba= hits/ab;
System.out.println(""+name);
System.out.printf("Slugging % is %.3f\n", sp);
System.out.printf("Batting avg os %.3f\n", ba);
}
}
Escape % sign,by using double %%:
System.out.printf("Slugging %% is %.3f\n", sp);
// ^------------- escaping
UnknownFormatConversionException happens when you are expecting an integer and read a string from your scanner. It would be helpful if you could post your input file.
Also, escape the % sign using another %.
System.out.printf("Slugging %% is %.3f\n", sp);

Categories

Resources