This question already has answers here:
How to test for blank line with Java Scanner?
(5 answers)
Closed 7 years ago.
I am beginner in learning java programming. Basically, I can't make the last bit of my code to work. Before I show you my code, I think it is a good idea to show how the result should be. The result of the program should be:
Please Enter either S(supply) or R(replenish) followed by ID and quantity.
R p122. 10
New Stock-level for p122(Chain) is 58
S. p124. 20
New Stock-level for p125(Pedal) is 18
S. p905. 20
No part found with ID p905
.....// enter empty string to terminate
//Show final stock levels of all Parts
Although, I did be able to perform the main calculation and everything, I cannot print out the final stock levels of all Parts. I really don't understand why.
Here is my code:
import java.util.Scanner;
public class TestPart {
public static void main(String[] args) {
// Array of 5 Part objects
// Part[] part = new Part[5];
Part[] part = new Part[5];
part[0] = new Part("p122", "Chain", 48, 12.5);
part[1] = new Part("p123", "Chain Guard", 73, 22.0);
part[2] = new Part("p124", "Crank", 400, 11.5);
part[3] = new Part("p125", "Pedal", 3, 6.5);
part[4] = new Part("p126", "Handlebar", 123, 9.50);
///////// Test Class 2 ////////
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter either S (supply) or R (replenish) followed by ID and quantity.");
while (scanner.hasNext()) {
String sOrR = scanner.next();
String inputId = scanner.next();
int amount = scanner.nextInt();
for (int i = 0; i < 5; i++) {
String id = part[i].getID();
// Find ID in array
if (id.equals(inputId)) {
// S or R
if (sOrR.equals("R")) {
part[i].replenish(amount);
} else {
part[i].supply(amount);
}
System.out.println("New Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is "
+ part[i].getStockLevel());
}
}
if ((inputId.equals(part[0].getID()) == false) && (inputId.equals(part[1].getID()) == false)
&& (inputId.equals(part[2].getID()) == false) && (inputId.equals(part[3].getID()) == false)
&& (inputId.equals(part[4].getID()) == false)) {
System.out.println("No part found with ID " + inputId);
}
}
scanner.close();
System.out.println("Final stock level for all the parts: ");
for (int i = 0; i < 5; i++) {
System.out.println("Final Stock-level for " + part[i].getID() + "(" + part[i].getName() + ") is "
+ part[i].getStockLevel());
}
}
}
My program executes perfectly the calculating part. However it doesn't display final stocklevels.
Please Enter either S(supply) or R(replenish) followed by ID and quantity.
R p122. 10
New Stock-level for p122(Chain) is 58
S. p124. 20
New Stock-level for p125(Pedal) is 18
S. p905. 20
No part found with ID p905
Your abort condition (namely scanner.hasNext()) won't exit the while loop whenever the user enters an empty string. I don't know if you already noticed but whenever the user only hits the return key, nothing happens because Scanner.next does not trigger on return only. Though be aware that it stores your input. That means once you enter a "valid" input (such as abc), the Scanner will give you everything the user just entered before that valid input. Just a small example to demonstrate what I mean:
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
System.out.println("\"" + scanner.next() + "\"");
}
scanner.close();
System.out.println("finished");
So, if you want to abort your program after the user entered an empty line, this is not possible with java.util.Scanner.hasNext. I recommend you add another character to your "S or R" option that allows the user to exit the program like this:
if(sOrR.equals("E")) break;
You should place this directly behind String sOrR = scanner.next();.
Related
I have created a program that allows a user to keep guessing numbers until they either guess the correct number or enter end. I have used a do-while loop to do this. When I create a new scanner inside the loop body it works as expected. However if I create it outside the loop body, it works fine if the input is integers or the first input is end However if the input end follows integer inputs it doesn't
pick up the nextLine() until the next loop. Is there a way to do this without having to creat a new scanner object each time.
private static void guessingGame() {
Scanner sc = new Scanner(System.in);
int answer = 7;
String input = "";
int number = 0;
do {
//Scanner sc = new Scanner(System.in);
System.out.print("Guess a number between 1 and 10 or end to finish ");
System.out.println("input at start is: " + input);
boolean b = sc.hasNextInt();
if(b) {
number = sc.nextInt();
System.out.println("number is: " + number); //for testing code
}else {
input = sc.nextLine();
System.out.println("input is: " + input); //for testing code
}
if (number == answer) {
System.out.println("Correct Guess");
break;
}else {
if(input.equals("end")) System.out.println("Hope you enjoyed the game");
else System.out.println("Incorrect Guess, try again ");
}
System.out.println("input before while is: " + input); //for testing code
}while(number != answer && !(input.equals("end")));
}
Example output for when end follow an integer input:enter code here
number is: 3
Incorrect Guess, try again
input before while is:
Guess a number between 1 and 10 or end to finish input at start is:
end
input is:
Incorrect Guess, try again
input before while is:
Guess a number between 1 and 10 or end to finish input at start is:
input is: end
Hope you enjoyed the game
input before while is: end
you can solve this by using a while loop .
See the following code.
private static void guessingGame() {
Scanner sc = new Scanner(System.in);
int answer = 7;
String input = "";
int number = 0;
while(!input.equals("end")) {
//Scanner sc = new Scanner(System.in);
System.out.print("Guess a number between 1 and 10 or end to finish ");
System.out.println("input at start is: " + input);
boolean b = sc.hasNextInt();
if(b) {
number = sc.nextInt();
System.out.println("number is: " + number); //for testing code
}else {
input = sc.next(); //Edited here . Changed nextLine() to next().
System.out.println("input is: " + input); //for testing code
}
if (number == answer) {
System.out.println("Correct Guess");
break;
}else {
if(input.equals("end")) System.out.println("Hope you enjoyed the game");
else System.out.println("Incorrect Guess, try again ");
}
System.out.println("input before while is: " + input); //for testing code
}
}
In here , at first , input will always be empty String . On while loop, it gets assigned to your String input i.e, end . Till it encounters end , your loop will be running.
Edited
Change input=sc.nextLine(); to input=sc.next(); . This is because , your scanner waits for next Line and doesn't consider "end" as input string .
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am feeling quite stupid at this point for not being able to figure out something that is most likely a simple fix. I keep getting the error "Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at searchSorting.main(searchSorting.java:15)" after inputting how many numbers I want to input. Others solutions to this problem just don't seem to apply to me somehow. Thanks for the help
import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
int number, search, item, array[], first, last, middle;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
item = Integer.parseInt(in.nextLine());
double[] values = new double[item];
for (int i = 0; i < values.length; i++) {
System.out.print("Input number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
for (int index = 0; index < 5; index++)
System.out.print(values[index] + " ");
in.nextLine();
Arrays.sort(values);
System.out.println("Sorted number is: " + Arrays.toString(values));
System.out.println("Enter the number you are looking for?");
search = in.nextInt();
first = 0;
last = (item - 1);
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println(item + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(item + " is not found.\n");
}}
For more info check out Scanner and Integer documentation, it's an excellent resource.
Edit: Try removing line 15 and replacing item with number in the next line
You call this:
number = in.nextInt();
Assuming the user types 123 and ENTER, this call consumes the 123 and leaves the input stream positioned before the end-of-line character.
The next relevant code is
item = Integer.parseInt(in.nextLine());
The nextLine call advances the input stream past the end-of-line, returning all characters it passed on the way. Since the ENTER key was pressed immediately after 123, the returned value is the emoty string. Which is not an integer.
You need to review your strategy of sometimes scanning numbers (nextInt) and sometimes scanning rest-of-linr (nextLine). Mixing the two needs to be done quite carefully. You might be better advised to stick to the numerical methods (nextInt/nextDouble).
For example, replacing this
item = Integer.parseInt(in.nextLine());
by this
item = in.nextInt();
automatically handles the line-ending.
From discussion in comments:
I am still confused as to why it's having me input
the value a second time on the next line
Making assumptions about how you modified the code since your initial question: it's because you've written code that reads the number twice:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt(); // **** first input ****
array = new int [number];
item = in.nextDouble(); // **** second input ****
double[] values = new double[item];
Each time you call for in.nextSomething() the Scanner is going to read more input. It should likely just be this:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
double[] values = new double[number];
I'm trying to make a system that asks the user how many times they want a phrase to be repeated and then it checks if the answer is an integer or a string. The program works well when I don't try to implement this system and leave it just at asking the phrase and how many times it should be repeated but it falls appart when I try to check if the amount of times is an integer or not.
import java.util.*;
public class Phrase {
public static Scanner phraseScan = new Scanner (System.in);
public static Scanner amountScan = new Scanner (System.in);
public static void main (String[] args ) {
System.out.println("What phrase do you want repeated?");
String phrase = phraseScan.nextLine();
int phraseLoops = 0;
System.out.println("How many " + phrase + "s" + " do you want?");
int desiredPhraseLoops = amountScan.nextInt();
for (;;) {
if (!amountScan.hasNextInt()) {
System.out.println("Integers only please");
amountScan.next();
}
desiredPhraseLoops = amountScan.nextInt();
if (desiredPhraseLoops >= 0) {
System.out.println("Valid amount!");
continue;
} else {
break;
}
}
System.out.println(desiredPhraseLoops + " " + phrase + "s coming your way!");
do {
System.out.println(phrase);
phraseLoops++;
} while (phraseLoops != desiredPhraseLoops);
System.out.println("You printed " + phraseLoops + " " + phrase + "s" );
}
}
What I've tried:
try {
desiredPhraseLoops = amountScan.nextInt();
} catch (InputMismatchException exception) {
System.out.println("This is not an integer.");
}
if (!amountScan.hasNextInt()) {
System.out.println("Good.");
} else {
System.out.println("Enter an Integer please.");
}
Any time I tried anything, it would ask which phrase I wanted and how many times I wanted it repeated. And then the program just stopped afterward, no matter if I put in an integer or a string, it just didnt give me any other prompts.
The output is this:
What phrase do you want repeated?
Test
How many Tests do you want?
3
And that's it.
To begin with, just use one Scanner object. You don't need more than that for keyboard input.
If you like, you can just stick with the Scanner#nextLine() method, for example:
Scanner userInput = new Scanner(System.in);
String phrase = "";
while (phrase.equals("")) {
System.out.println("What phrase do you want repeated?");
phrase = userInput.nextLine();
// VALIDATION:
// Was anything other than a empty string (spaces)
// or longer than 2 characters supplied?
if (phrase.trim().equals("") || phrase.length() < 3) {
// Nope!
System.err.println("Invalid Input!. Enter a proper phrase!");
phrase = "";
}
// Yes, allow the prompt loop to exit.
}
String phraseLoopsNumber = "";
while (phraseLoopsNumber.equals("")) {
System.out.println("How many " + phrase + "s" + " do you want?");
phraseLoopsNumber = userInput.nextLine();
// VALIDATION:
// Did the User supply a string representation of an integer value?
if (!phraseLoopsNumber.matches("\\d+")) {
// Nope!
System.out.println("Invalid Input (" + phraseLoopsNumber + ")! An integer value is expected!");
phraseLoopsNumber = "";
}
// Yes he/she/it did...Allow prompt loop to exit.
}
int numberOfLoops = Integer.parseInt(phraseLoopsNumber);
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.
In the above code, the String#matches() method was used along with a small Regular Expression (RegEx). The "\\d" expression passed to the matches() method checks to see if the string it is working against contains all (1 or more) digits.
If however you're hell bent on using the Scanner#nextInt() method then you can do it this way:
int numberOfLoops = -1;
while (numberOfLoops == -1) {
System.out.println("How many " + phrase + "'s" + " do you want?");
// Trap any input errors against the Scanner.nextInt() method...
// This would be a form of validation.
try {
numberOfLoops = userInput.nextInt();
// Consume the newline from ENTER key in case a nextLine() prompt is next.
userInput.nextLine();
} catch (Exception ex) {
System.out.println("Invalid Input! An integer value is expected!");
// Consume the newline from ENTER key in case a nextLine() prompt is next.
// The first one above would of been skipped past if nextInt() threw an exception.
userInput.nextLine();
numberOfLoops = -1;
continue; // continue loop so as to re-prompt
}
// Further Validation:
// Did the User supply a number greater than 0?
if (numberOfLoops < 1 ) {
// Nope!
System.out.println("Invalid Input (" + numberOfLoops + ")! A value 1 or greater is expected!");
numberOfLoops = -1;
}
// Yes he/she did...Allow prompt loop to exit.
}
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
Hi developers on Stackoverflow! I have a problem on this exercise:
"Write a program that asks user to input a list of N names using the keyboard, then user continues
inputting a name for searching. The program should print out the position of this name in the list.
In case the name doesn’t appear in the list, the program should print out value -1."
Here is my code:
package Tut_01;
import java.util.ArrayList;
import java.util.Scanner;
public class Ex_04 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
ArrayList<String> elements = new ArrayList<> ();
System.out.print ("How many numbers do you want to input: ");
int n = sc.nextInt (); // Count numbers that user want to input
// Ask the user input values
for (int i = 0; i < n; i++) {
System.out.print ("Enter your name " + (i + 1) + ": ");
String name = sc.next ();
elements.add (name);
}
System.out.println ("Which name do you want to search ?");
String searchName = sc.next ();
// Problem?
for (int p = 0; p < n; p++) {
if (searchName == elements.get (p)) {
System.out.println ("Your name is at index " + p + ": " + elements.get (p));
}
}
}
Here is my console:
How many numbers do you want to input: 2
Enter your name 1: Hoa
Enter your name 2: Hieu
Which name do you want to search ?
Hoa
Process finished with exit code 0
I mean I don't know why my code stops there instead of printing the position of the index. Anyone knows this issue? Thanks for showing me!
You are comparing String in the wrong way. String is an object not a primitive, so you cannot use ==.
The proper way is:
searchName.equals(elements.get(p))
Below the simple code will give the same output.Make use of indexOf method
System.out.println("Your name is at index " + elements.indexOf(searchName) + ": " + searchName);
When i run the following program I get an error at line 20, and this is my code:
package J1;
import java.util.Scanner;
public class SpeedLimit {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.next();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + "miles" + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
}
when i run the code, I enter the following input from the keyboard:
3
20 2
30 6
10 7
2
60 1
30 5
4
15 1
25 2
30 3
10 5
-1
to get this result as an output:
170 miles
180 miles
90 miles
but i get the following Error when i run the code
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at J1.SpeedLimit.main(SpeedLimit.java:20)
String pair = keyboard.next(); This reads only one token which are separated by " " so when you split pair by " ". It will only have one element, The String itself. So you need to read the whole line and then split it by delimited " ".
Another mistake is that when you change that line with String pair = keyboard.nextLine(); , You will still get error because System considers Enter key as input of .nextLine() method. So you need to discard that extra unnecessary input.
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
int ip1=keyboard.nextInt();
int ip2=keyboard.nextInt();
speed = speed + ip1*(ip2-last);
last = ip2;
}
output = output +speed + "miles" + "\n";
speed =0;
input = keyboard.nextInt();
}
You are reading the variable pair the wrong way and then you split it and assign it to tab which fails to automatically to fetch index cause pair variable got a problem.
*nextLine(): reads the remainder of the current line even if it is empty.
keyboard.nextLine(); //To avoid the exception you commented
String pair = keyboard.nextLine(); //here is solved
tab = pair.split(" ");
Keyboard.next() will only read the input till the space, so pair and the array will have only one number, so tab[1] results in arrayOutOfBound exception. Use the method nextLine() to read the inputs with space.
You Can try below changes in your code :
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = Integer.parseInt(keyboard.nextLine());
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.nextLine();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0].trim())*(Integer.parseInt(tab[1].trim())-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + " miles " + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
i did'n really understand how you are providing the inputs. but, if "3" happens to be your first line then split(" ") would return an array of length 1. thus, tab[0] would return 3 and tab[1] will give you a nullPointerException.
try adding an check for the length of tab before executing your line 20.
this should do the trick:
if(tab.length() > 1){
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
}