Stuck with detecting next line from console - java

I am banging my head to the wall but just can't figure out what is going wrong. Simple program but not working. I need to get 3 inputs(integers) from user. End the program on either array full or when user presses enter. Here is what i am trying without any luck. It works fine all the situtations EXCEPT it cant detect nextline.
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
if (sc.next().isEmpty() || sc.next().equals("\n")){
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
Please help me . Why is it not detecting next line. I have googled already and tried lot of solutions provided but none worked for me. Any HELP!!!
Thanks
Edited code :
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
String next = sc.next();
if (next.isEmpty() || next.equals("\n"))
{
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
}

int[] intArray = new int[3];
int counter = 0;
boolean enterPressed = false; // added boolean to test if they entered a blank line
try (
Scanner sc = new Scanner(System.in); // declaring in a try-with-resources, so it automatically closes.
) {
System.out.println("Start!!");
System.out.println("Enter int"); // Have to print this the first time
while (counter < 3 && !enterPressed) {
if (counter > 0) { System.out.println("Enter int"); }
String next = sc.nextLine(); // just grab a line (the user pressed enter)
if (next.isEmpty()) {
enterPressed = true;
} else {
try {
intArray[counter] = Integer.parseInt(next);
counter++;
} catch (NumberFormatException ex) {
System.out.println("wrong input.");
}
}
}
}

Your code is sticking because it's waiting on the conditional check for sc.hasNextInt(). The solution I propose below, manually parses the user-input string to see if it's an int, rather than using the Scanner's functionality to check if it's an int or not.
I left some comments in the code to hopefully add clarity. Let me know if anything doesn't make sense, and I'm happy to elaborate!
import java.util.Arrays;
import java.util.Scanner;
public class ScannerTestNew {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
// Variable used to hold the user's input via the Scanner.
String userInput = null;
while (true) {
System.out.print("Enter an integer: ");
userInput = sc.nextLine();
// Check to see if an empty string/enter/return has been input:
if (userInput.length() == 0) {
System.out.println("Input is empty!");
break;
}
// Checking to see if the input can be parsed into an int. If it can't, retry.
int intInput = 0;
try {
intInput = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
System.out.println("Invalid input for type Integer. Please try again.");
continue;
}
// We know we have an int at this point. Checking that the array isn't already
// filled.
if (counter <= 2) {
intArray[counter] = intInput;
counter++;
// The array is filled, act accordingly.
} else if (counter > 2) {
System.out.println("Array is full.");
System.out.printf("Array Elements: %s", Arrays.toString(intArray));
break;
}
sc.close();
}
}
}

Related

Scanner method .hasNextInt() and if statement - works only 1 time. For next loop - automatically (didn't wait any input) gives false

I tried to do an input check (need to take 3 numbers using Scanner).
Before that, I used a similar method (.hasNext(int)) in another task - everything worked fine. In this case, it doesn't work.
The first "while" loop works correctly, on the second loop .hasNextInt() returns false and loops the loop - not giving the opportunity to enter data.
boolean num1IsInt = false;
boolean num2IsInt = false;
boolean num3IsInt = false;
int scaicius1 = 0;
int scaicius2 = 0;
int scaicius3 = 0;
System.out.println("Įveskite 3 skaičiai, po viena after each press enter");
while (!num1IsInt) { //check first number is int
Scanner sc1 = new Scanner(System.in);
System.out.println("(1)Įveskyte pirmas skaicius");
if (sc1.hasNextInt()) {
scaicius1 = sc1.nextInt();
num1IsInt = true;
} else {
System.out.println("Not correct integer");
continue;
}
sc1.close();
}
while (!num2IsInt) { //check second number is int
Scanner sc2 = new Scanner(System.in);
System.out.println("(2)Įveskyte antras skaicius");
if (sc2.hasNextInt()) {
scaicius2 = sc2.nextInt();
num2IsInt = true;
} else {
System.out.println("Not correct integer");
continue;
}
sc2.close();
}
while (!num3IsInt) { //check third number is int
Scanner sc3 = new Scanner(System.in);
System.out.println("(3)Įveskyte trecias skaicius");
if (sc3.hasNextInt()) {
scaicius3 = sc3.nextInt();
num3IsInt = true;
sc3.close();
} else {
System.out.println("Not correct integer");
continue;
}
sc3.close();
}
System.out.println("First number = " + scaicius1);
System.out.println("First number = " + scaicius2);
System.out.println("First number = " + scaicius3);
Thank you - #Thomas Kläger. I change code like was at the begin (with only one Scanner, cose with 3 scanners it's didn't work) and add to all else statements reader for this "ghost element which loop my code".
boolean num1IsInt = false;
boolean num2IsInt = false;
boolean num3IsInt = false;
int scaicius1 = 0;
int scaicius2 = 0;
int scaicius3 = 0;
System.out.println("Įveskite 3 skaičiai, po viena after each press enter");
**Scanner sc = new Scanner(System.in);**
while (!num1IsInt) { //check first number is int
System.out.println("(1)Įveskyte pirmas skaicius");
if (sc.hasNextInt()) {
scaicius1 = sc.nextInt();
num1IsInt = true;
} else {
System.out.println("Not correct integer");
**sc.next();**
}
}
while (!num2IsInt) { //check second number is int
System.out.println("(2)Įveskyte antras skaicius");
if (sc.hasNextInt()) {
scaicius2 = sc.nextInt();
num2IsInt = true;
} else {
System.out.println("Not correct integer");
sc.next();
}
}
while (!num3IsInt) { //check third number is int
System.out.println("(3)Įveskyte trecias skaicius");
if (sc.hasNextInt()) {
scaicius3 = sc.nextInt();
num3IsInt = true;
} else {
System.out.println("Not correct integer");
sc.next();
}
}
sc.close();
System.out.println("First number = " + scaicius1);
System.out.println("First number = " + scaicius2);
System.out.println("First number = " + scaicius3);

if a user inputs a letter instead of a number tell them it's not a number

I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here

How to check if user input is String, double or long in Java

I'm a beginner in java. I want to check first if the user input is String or Double or int. If it's String, double or a minus number, the user should be prompted to enter a valid int number again. Only when the user entered a valid number should then the program jump to try. I've been thinking for hours and I come up with nothing useful.Please help, thank you!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fizz {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
try {
Integer i = scan.nextInt();
if (i % 3 == 0 && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i + "は3と5の倍数ではありません。");
}
} catch (InputMismatchException e) {
System.out.println("");
} finally {
scan.close();
}
}
One simple fix is to read the entire line / user input as a String.
Something like this should work. (Untested code) :
String s=null;
boolean validInput=false;
do{
s= scannerInstance.nextLine();
if(s.matches("\\d+")){// checks if input only contains digits
validInput=true;
}
else{
// invalid input
}
}while(!validInput);
You can also use Integer.parseInt and then check that integer for non negativity. You can catch NumberFormatException if the input is string or a double.
Scanner scan = new Scanner(System.in);
try {
String s = scan.nextLine();
int x = Integer.parseInt(s);
}
catch(NumberFormatException ex)
{
}
Try this one. I used some conditions to indicate the input.
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
int charCount = input.length();
boolean flag = false;
for(int x=0; x<charCount; x++){
for(int y=0; y<10; y++){
if(input.charAt(x)==Integer.toString(y))
flag = true;
else{
flag = false;
break;
}
}
}
if(flag){
if(scan.hasNextDouble())
System.out.println("Input is Double");
else
System.out.println("Input is Integer");
}
else
System.out.println("Invalid Input. Please Input a number");
Try this. It will prompt for input until an int greater than 0 is entered:
System.out.println("Please enter a number");
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNext()) {
int number;
if (scan.hasNextInt()) {
number = scan.nextInt();
} else {
System.out.println("Please enter a valid number");
scan.next();
continue;
}
if (number < 0) {
System.out.println("Please enter a number > 0");
continue;
}
//At this stage, the number is an int >= 0
System.out.println("User entered: " + number);
break;
}
}
boolean valid = false;
double n = 0;
String userInput = "";
Scanner input = new Scanner(System.in);
while(!valid){
System.out.println("Enter the number: ");
userInput = input.nextLine();
try{
n = Double.parseDouble(userInput);
valid = true;
}
catch (NumberFormatException ex){
System.out.println("Enter the valid number.");
}
}

Java try-catch statement inside while loop

I have this method and it works fine. I need to put a try/catch statement so
the method can continue if the user puts in a letter. I don't know where to put the statement, It seems everywhere I put it it get's wrong. Could somebody please show me where to put this statement?
public void myMethod() {
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number;
boolean end = false;
while (!end) {
System.out.println("Please give an number between 0-20: ");
number = in.nextInt();
for (int i = 1; i < array.length; i++) {
if (i == number) {
System.out.println(array[number]);
end = true;
}
}
if (!end) {
System.out.println("I cant find number " + number
+ " in the array, please try again ");
}
}
}
Your for loop I can't explain, you need only check values between 0 and 20,
And when you call try catch, you have to skip loop after exception
public static void myMethod() {
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number=0;
boolean end = false;
while (!end) {
System.out.println("Please give an number between 0-20: ");
//check symbol
try{
number = Integer.valueOf(in.next());
}catch(Exception e)
{
System.out.println("It's not a number! ");
continue; //skip loop
}
if((number>=0)&&(number<=20))
{
System.out.println(array[number]);
end=true;
}
else
System.out.println("I cant find number " + number
+ " in the array, please try again ");
/* why do you use loop here???
* u need to check if number between 0-20
for (int i = 1; i < array.length; i++) {
if (i == number) {
System.out.println(array[number]);
end = true;
}
}*/
}
}
public static void main(String[] args) {
Test test = new Test();
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number;
System.out.println("Please give an number between 0-20: ");
do{
try{
number = Integer.parseInt(in.next());
}
catch(Exception e){
System.out.println("Please give an number between 0-20: ");
number = -1;
}
}
while(!(number <= 20 && number >=0 ));
System.out.println(array[number]);
}
System.out.println("Please give an number between 0-20: ");
try{
number = in.nextInt();
}catch(Exception e){
number = 1; //Put random number of default number here
}

Some trouble in loop

Hi there,
I'm a newbie in java and I have a problem with this code. I'm thinking if it is a problem in loop or something..
public static void main(String[] args) {
try {
Scanner scn = new Scanner(System.in);
int z = 0;
String input;
int[] ABArray = new int[2];
while (z == 0) {
System.out.println("Input X to terminate.");
System.out.print("Input: ");
input = scn.nextLine().toLowerCase();
for (int i = 0; i < input.length(); i++) {
char AB = input.charAt(i);
ABArray[AB - 'a']++;
}
if (ABArray[0] == 0 || ABArray[1] == 0) {
System.out.println("Not Equal");
System.out.println("");
} else if (ABArray[0] == ABArray[1]) {
System.out.println("Equal");
System.out.println("");
} else if (ABArray[0] != ABArray[1]) {
System.out.println("Not Equal");
if (ABArray[0] > ABArray[1]) {
System.out.println("The number of A is greater than B.");
} else if (ABArray[0] < ABArray[1]) {
System.out.println("The number of B is greater than A.");
}
System.out.println("");
}
}
} catch (ArrayIndexOutOfBoundsException X) { } //Terminates the program
}
The problem is this
I/O
Input:
ABABAB
Output:
Equal
Input:
AABBB
Output:
Not Equal
The number of B is greater than A.
Input:
AABB //It is equal.
Output:
Not Equal //It says not.
The number of B is greater than A.
As you see, the problem is when I input equal A and B at the first, it says equal, when I input not equal A and B but at the third when I input equal A and B it says not equal.
Problem solved.
Thanks for the help.
You have to set all the values in ABArray to zero every time you start to work inside the while loop. Right now on the third time you start the while loop (with AABB input) you still keep the values which were left from the previous run of the loop - 5 in the 0-indexed element of an array and 6 in the 1-indexed element of an array, thus the program gives you the wrong output.
How about you simply read in the input into a string, then loop through it, counting the number of occurrences of each character you are interested in (here 'a' and 'b'), checking whether their counts are equal? So this works for example:
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
String input;
while (true) {
System.out.println("Input X to terminate.");
System.out.print("Input: ");
input = scanner.nextLine().toLowerCase();
if (input.equals("X")) {
break;
} else {
int countA = 0;
int countB = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'a') {
countA++;
} else if (input.charAt(i) == 'b') {
countB++;
}
}
if (countA == countB) {
System.out.println("Equal!");
} else {
System.out.println("Not equal!");
}
}
}
} catch (ArrayIndexOutOfBoundsException e) // Terminates the program
{
}
}
You can use this code:
public static void main( String[] args )
{
try
{
Scanner scn = new Scanner(System.in);
int z=0;
String input;
int[] ABArray = null;
while(z==0)
{
ABArray = new int[2];
System.out.println("Input X to terminate.");
System.out.print("Input: ");
input=scn.nextLine().toLowerCase();
for ( int i = 0; i < input.length(); i++ )
{
char AB=input.charAt(i);
ABArray[AB-'a']++;
}
if(ABArray[0]==0||ABArray[1]==0)
{
System.out.println("Not Equal");
System.out.println("");
}
else if(ABArray[0]==ABArray[1])
{
System.out.println("Equal");
System.out.println("");
}
else if(ABArray[0]!=ABArray[1])
{
System.out.println("Not Equal");
if(ABArray[0]>ABArray[1])
{
System.out.println("The number of A is greater than B.");
}
else if(ABArray[0]<ABArray[1])
{
System.out.println("The number of B is greater than A.");
}
System.out.println("");
}
}
}
catch(ArrayIndexOutOfBoundsException X) //Terminates the program
{
X.printStackTrace();
}
}

Categories