Basically what I have to do is read user input in (CUI) until the user presses x. Then display the min,max and average of the numbers the user has entered. I keep getting a InputMismatchException when I press x. I have tried a lot of different ways and that is why I may have some unnecessary code in there.
import java.io.*;
import java.util.Scanner;
import java.lang.Number;
public class taskTwo{
public static void main(String [] args) throws IOException {
int min = 0;
int max = 0;
boolean isX =false;
Scanner input = new Scanner (System.in);
BufferedReader input2 = new BufferedReader (new InputStreamReader (System.in));
String s = "x";
s = input2.readLine();
while(isX == false){
if(s.equals ("x") || s.equals ("X")){
isX = true;
}
int val = input.nextInt();
if (val == 0) {
break;
}
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
if(isX == true){
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
}
}
in the while loop you are using nextInt(), obviously it will expect an integer as input. So when you are giving input x which is an string then it will fail.
So in the loop take string as input and if it is not X and is a number then convert it to int values and calculate
s = input2.readLine(); is called outside while loop means only for first line it will check for X and loop can never be ended if fist line is not X or you entered 0.
1.) You don't need two objects reading input. Just input is sufficient.
2.) You can use
input.hasNextInt();
and
input.hasNext();
to check if the input is an int or a string. Something like:
while(true){
if(input.hasNextInt()){
//do something with the integer
}else if(input.hasNext()){
if(input.next().toLowerCase() == "x"){
break;
}
}
}
Related
I am a new-bee in java, I have a problem that i cant figure out to compare previous entered number(int) with next one continuously and I need to write a program that repeatedly reads numbers from the user’s keyboard. The program stops looping when the user types the same number twice in a row.
Thanks in advance for your kind guidance.
Here’s a sample run of the program:
5
13
21
5
4
5
5
Done!
Following was my unsuccessful effort :)
Scanner input = new Scanner(System.in);
System.out.println("Enter Numbers");
int x = 0;
int y = 0;
x = input.nextInt();
y = input.nextInt();
while (x != y) {
x = input.nextInt();
y = input.nextInt();
}
System.out.println("Done!!!!!!!");
input.close();
You can use loop to read number from console and stop if previous nubmer equals to current one. As marker of first number you can use e.g. null value of Integer prv (as alternative, you can use boolean isFirstLine flag for first line or res.isEmpty()).
public static List<Integer> receiveNumbers() {
List<Integer> res = new LinkedList<>();
Integer prv = null;
try (Scanner scan = new Scanner(System.in)) {
while (true) {
int num = scan.nextInt();
if (prv != null && prv == num)
break;
res.add(num);
prv = num;
}
}
return res;
}
import java.util.Scanner;
public class OngoingPractice {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int previous, current;
previous = keyboard.nextInt();
current = keyboard.nextInt();
while (current != previous) {
previous = current;
current = keyboard.nextInt();
}
System.out.println("Done!");
Just use an infinite while loop and break if the new int is equal to previous one. As a suggestion you should show how you tried.
Scanner sc = new Scanner(System.in);
int i;
Integer j = null;
boolean flag = false;
while(true) {
i = sc.nextInt();
if(j==null) {j=i; flag = true;}
if(j==i&&!flag) {
System.out.println("Done");
break;}
j=i;
flag = false;
}
Edited : if first one is -1, it won't work as in the comment. so I modified some.
Remember the last entered data in one variable and check it with the current data. If both matches, break the loop.
Scanner scanner = new Scanner(System.in);
String previousNumber="";
while (scan.hasNextInt()) {
int number = scan.nextInt();
if(!previousNumber.equals("") && number==Integer.parseInt(previousNumber)) {
break;
}else {
System.out.println(number);
}
previousNumber=number+"";
}
I'm trying to ask the user for two two-digit numbers and then perform a length check and a type check on both of the numbers, then I want to output the sum of the numbers. Here's what I have so far:
package codething;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = number.nextInt();
if(number.hasNextInt()) {
} else {
System.out.println("Error");
}
int m;
int length = String.valueOf(number).length();
if (length == 2) {
} else {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
Scanner number1 = new Scanner(System.in);
System.out.println("Enter another two digit number (10-99) ");
m = number.nextInt();
if(number1.hasNextInt()) {
m = number1.nextInt();
} else {
System.out.println("Error");
}
int sum = n + m;
System.out.println(sum);
}
}
At the moment my program won't even ask me for my second input. Not sure what to do :/
So several things:
-Don't construct more than one Scanner objects to read from System.in. It just causes problems.
-You're using String.valueOf() to convert an int to a String. It is better to simply check to make sure it is between 10 and 99.
-You check to make sure that the Scanner has a next int after you call nextInt which won't help. You need to make sure that there is a next int.
-A lot of your if statements have an empty if block and then you do something in the else. You can just do the opposite in the if and omit the else (Instead of if(length ==2) {} you can do if(length != 2) {//code}
Scanner number = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a two digit number (10-99) ");
int n = 0;
if(number.hasNextInt()) {
n = number.nextInt();
} else {
number.next(); //Clear bad input
System.out.println("Invalid");
}
int m = 0;
if ( n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
System.out.println("Enter another two digit number (10-99) ");
if(number.hasNextInt()) {
m = number.nextInt();
} else {
number.next();
System.out.println("Invalid");
}
if (n< 10 || n > 99) {
System.out.println("this isnt a valid input and you have killed my program ;(");
}
int sum = n + m;
System.out.println(sum);
First off, yes this a HW assignment. Having issues with recursive factorials in Java. Everything I'm finding on here and elsewhere already shows me what I've done is correct. However I'm having issues with an additional step. Basically what I need is the 1) User to enter a number 2) Factorial to be calculated 3) If user enters anything but a character or string (rather than an int) for an error message to come out 4) The question to repeat until user enters "0" to exit.
Steps 1 and 2 I have completed. I'm having issues with step 3. It seems like I am missing a return statement if the user enters anything but an int but I can't seem to figure out exactly what.
Here is code thus far:
import java.util.Scanner;
public class Recursive
{
public static void main(String[] args)
{
int number; // To hold a number
char letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
number = keyboard.nextInt();
//Display the factorial
System.out.println(number + "! is " + factorial(number));
}
private static int factorial(int n)
{
if (n == 0)
return 1; // Base Case
else if (n > 0)
return n * factorial(n-1);
else (!(n>0))
return
System.out.println(number + "is invalid");
}
}
After getting the user input, before doing factorial, we have to check if input is a number or not. We can use pattern. Check regular expression patterns to do that. After checking if it is a number or not, check if it is zero, if yes use exit (0) to come out of the program. If not do the factorial
while (true) {
// Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
int number = keyboard.nextInt();
if (Pattern.matches("\\d+", String.valueOf(number))) {
if (Integer.valueOf(number) == 0)
System.exit(0);
// Display the factorial
System.out.println(number + "! is " + factorial(number));
}
else
System.out.println("Error");
}
My answer is based on an assumption that your factorial function is working properly.In order to complete your step 3 and 4 you need to take input in a loop. In that loop, take input as string and parse it into integer, use try catch so that you can catch exception when a non-integer is given as input and you can prompt an error message.
public static void main(String[] args)
{
Integer number; // To hold a number
String letter; // To hold a character
//Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//Get a number from the user
System.out.print("Enter an integer to find the factorial: ");
while(keyboard.hasNext()){
letter = keyboard.next();
try{
number = Integer.parseInt(letter);
if(number==0){
//Exiting
break;
}
int fact = factorial(number);
//Display the factorial
System.out.println(number + "! is " + fact);
System.out.print("Enter an integer to find the factorial: ");
}
catch(NumberFormatException e){
System.out.println("Invalid input please enter integers only");
}
}
}
Also your factorial function is having compilation issues currently. You need to fix it for proper functioning of your code.
My solution for recursive factorial using Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.*;
class Main {
public static String factorial(int n,String s){
if(n>0){
BigInteger fact = new BigInteger(s);
fact = fact.multiply(new BigInteger(n + ""));
return factorial(n-1,fact.toString());
}
else{
return s.toString();
}
}
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int n = Integer.parseInt(line);
if(n==0)
System.out.println("Factorial is 0");
else{
String s = factorial(n,"1");
System.out.println("Factorial is " + s);
}
}
}
the example of factorial using recursive in Java
public class MainClass {
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("%d! = %d\n", counter,
factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}
I'm new to Java and I am trying to write a program that asks the user to input the name of a txt file containing only numbers, and the program will output the sum, average, max, and min of the numbers in the file. I have written most of the program, however I am stuck trying to find the max and min of the values. Any information you can give would be helpful, and if I was not clear enough I can try to elaborate. My code so far is:
public class NumberFile{
public static void main(String[] args){
boolean goodName = false;
int currentNumber, sum = 0, numberCount=0;
Scanner numberFile = null;
FileReader infile;
Scanner input = new Scanner(System.in);
System.out.println("Please enter the name of the file you wish to import: ");
String fileName = input.nextLine();
while (!goodName){
try{
infile = new FileReader(fileName);
numberFile = new Scanner(infile);
goodName = true;
}
catch (IOException e){
System.out.println("invalid file name, please enter another name");
fileName = input.nextLine();
}
}
while (numberFile.hasNextInt()){
currentNumber = numberFile.nextInt();
sum+=currentNumber;
numberCount++;
}
System.out.println("The sum of the numbers is " +sum);
System.out.println("The average of the numbers is " + ((double) sum)/numberCount);
} // end main
} // end class
Have two variables min and max (of course min and max should initially be int.max)
Hint:
if(currentNumber < min)
{
min= currentNumber;
}
if(currentNumber > max)
{
max = currentNumber
}
The above would be in your file read loop.
Declare two int variables - one "min" and one "max".
Initialize min with Integer.MAX_VALUE and max with Integer.MIN_VALUE.
Then within your while loop check every number against those variables - ie. if number is smaller than "min" then assign it as a new "min" value.
If its larger than "max" then assign it as new "max" value.
Hope this clarifies, its very simple so I didnt put any code so you can implement it yourself.
int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
while (numberFile.hasNextInt()){
currentNumber = numberFile.nextInt();
sum+=currentNumber;
numberCount++;
if(min>currentNumber){
min=currentNumber;
}
if(max<currentNumber){
max=currentNumber;
}
}
Declare the minimum value to the maximum int value and reassign the minimum value every time you read new value that is smaller than current minimum value.
Same thing goes for maximum value.
I had an instance where I needed to find the largest Id from an .sql file containing large set of insert statements. These statements also inserted the Id along with all other fields. I thought this will make a good example as the file not only has integers but large chunk of mixed data types. Below is my program,
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
/**
* #author Hamzeen. H.
* #date 15/10/2015
*/
public class Driver {
public Driver() {
}
private void readData() {
try {
Scanner inputFile = new Scanner(new DataInputStream(
new FileInputStream("all_inserts.sql")));
long highest = 0L;
while (inputFile.hasNext()) {
String strNum = buildNumber(inputFile.next());
if (!strNum.equals("")) {
Long temp = Long.parseLong(strNum);
if (temp > highest) {
highest = temp;
}
}
}
System.out.println("Highest:: " + highest);
inputFile.close();
} catch (IOException e) {
System.out.println("Problem finding file");
}
}
private String buildNumber(String str) {
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isDigit(ch)) {
strBuilder.append(ch);
} else if ('.' == ch || !Character.isDigit(ch) || ',' == ch) {
return strBuilder.toString().trim();
}
}
return strBuilder.toString().trim();
}
public static void main(String args[]) {
new Driver().readData();
}
}
I have tried various techniques to check the values of user input in this method. The user should only be able to enter a '1' or a '0'. If any other input is used there should be an error message and the program exits. Any ideas? I got it to work for the first digit but not the second through the tenth.
System.out.println("Enter a ten digit binary number. Press 'Enter' after each digit. Only use one or zero. :");
binary[0] = keyboard.nextInt();
for (index = 1; index < 10; index++)
binary[index] = keyboard.nextInt();// fill array with 10 binary
// digits from user. User
// must press 'Enter' after
// each digit.
Try this:
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext())
{
final String input = scanner.next();
try
{
int num = Integer.parseInt(input, 2);
}
catch (NumberFormatException error)
{
System.out.println(input + " is not a binary number.");
//OR You may exit here, if you don't want to continue
}
}
Try this code part :
import java.util.Scanner;
public class InputTest
{
public static void main(String... args) throws Exception
{
Scanner scan = new Scanner(System.in);
int[] binary = new int[10];
for (int index = 0; index < 10; index++)
{
int number = scan.nextInt();
if (number == 0 || number == 1)
{
binary[index] = number;
System.out.println("Index : " + index);
}
else
System.exit(0);
}
}
}