I just started learning java and I want to make a simple program where it requests the persons
name, outputs the name then asks for the thier favorite number. It will then compare their number
to the number 6 and will output something depending on if the number is larger or smaller than 6.
I am getting a "String to int convert" error in Netbeans which has to do with the scanner.
Hopefully I am asking this correctly but how can I make the scanner pick-up integers?
Thanks
package javaapplication2;
import java.util.Scanner;
import java.lang.String;
public class JavaApplication2 {
public static void main(String[] args) {
// Creating an instance of the scanner class.
// Gets name and numbers.
Scanner getName = new Scanner(System.in);
Scanner getNumber = new Scanner(System.in);
//Holds name and number
String userName;
int userNumber;
// Asks for the users name.
// Holds name in userName.
System.out.println("What is your name?");
userName = getName.nextLine();
//Reponds with the users name.
System.out.println("Hello" + userName + "!");
//Asks for favorite number.
// Holds number in userNumber.
System.out.println("What is your favorite number?");
userNumber = getNumber.nextLine();
// Checks if users number is larger than 6.
if (userNumber > 6) {
// Stuff goes here.
}
}
}
You should use only one Scanner for one input stream:
Scanner in = new Scanner(System.in);
And after that you should use it's methods to get integers:
String name = in.nextLine();
int number = in.nextInt();
To be sure, you should read the documentation for Scanner:
Scanner
Scanner::nextLine
Scanner::nextInt
This might help: Javadoc page for Scanner.
Related
I would like to print an error message when the user presses enter or space enter instead of a string. I have tried isEquals("") and isEmpty() but haven't found anything that works yet.
Here's my code:
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.next();
if(input.equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
One way to do this, change keyboard.next() to keyboard.nextLine(), use trim() to remove unnecessary spaces, check with isEmpty().
String input = keyboard.nextLine().trim();
if (input.isEmpty()) {
// error message
} else {
// good to go
}
import java.util.Scanner;
public class check{
public static void main(String args[]){
System.out.println("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
if(input.trim().equals("")){
System.out.println("Empty");
} else {
System.out.println("number inputed");
}
}
}
Strangely, I don't get an error when running your code. However, I noticed that your code simply doesn't react to an empty input (just pressing enter). If you want to check for that, you can use keyboard.nextLine().
Judging by the rest of your code, it seems like you want the user to input only a number. An easy way to check if the user entered an integer if you're using Scanner is keyboard.hasNextInt().
Meaning you can do something like this:
if(keyboard.hasNextInt()) {
int yourNumber = keyboard.nextInt();
System.out.println("Your number is: " + your Number);
}
else {
System.out.println("Please enter a valid integer");
}
To check whether the string input is empty, you can use the String.isEmpty() method. Look below:
String input = keyboard.nextLine();
if(!input.isEmpty()) {
//the input is not empty!
}
else {
//the input is empty!
}
Note, however, that since you want to receive numbers as inputs you should not retrieve them as strings. Below is an example where the program retrieves a double from the user. Scanner provides many methods to validate the user's input. In this case, I'm using hasNextDouble() to check whether the input is a number.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
while(!scanner.hasNextDouble()) {
System.out.println("That's not a number!");
scanner.next();
}
double numberInput = scanner.nextDouble();
System.out.println("The entered number was " + numberInput);
I made a sample program similar to yours and used nextLine() instead of next(). When user enters space and clicks enter he will print "space" else "a number".
I'm new to programming. I'm trying to get multiple inputs from the user by using Scanner class. I'm using net beans and trying to run and compile my code within the net beans IDE. The program runs and compiles whenever I do not close the scanner after asking for input. But when I attempt to close the scanner after every time I asked for input I get an the nosuchelementexception scanner closed error. In class, we were taught to close scanner after every time we ask for input from the user. My professor does this, also while using NetBeans and his program compiles and runs every time. Like me, he also only declares scanner once and uses the same variable multiple times while asking for input from the user.
import java.util.Scanner; // This allows us to use Scanner
public class GettingInput {
public static void main(String[] args) {
// ALWAYS give the user instructions. System.out.println("Enter an integer: ");
// Create a new scanner
Scanner keysIn = new Scanner(System.in);
// Specify the type of data/variable you are scanning in
int num = keysIn.nextInt();
// Close your scanner when you are done.
keysIn.close();
// ALWAYS confirm that you scanned in what you thought you did.
System.out.println("Your int: " + num);
// Repeat the process for a different data type
System.out.println("---------");
System.out.println("Enter a floating-point value:");
keysIn = new Scanner(System.in);
double num2 = keysIn.nextDouble(); // note the different method
keysIn.close();
System.out.println("Your floating-point: " + num2);
// Repeat it yet again
System.out.println("---------");
System.out.println("Now enter a string.");
keysIn = new Scanner(System.in);
String str = keysIn.nextLine(); // again, a different method
keysIn.close();
System.out.println(str);
}
}
This is code he had written, compiled and ran in class. When I try to run the same code it does not work.
I'm also using a Mac Book Pro and the latest version of Mac OS.
it happens because you closed the scanner and initiating the scanner object again. so it is better that you don't close the scanner where you know you are going to use it later again in your code, but you should do it once you are done with it.
Another thing is that, for different type of inputs you even don't need to create an entire scanner object again, you can just call appropriate methods of that scanner for your corresponding inputs type. Such that
import java.util.Scanner;
public class GettingInput {
public static void main(String[] args) {
Scanner keysIn = new Scanner(System.in);
int num = keysIn.nextInt();
System.out.println("Your int: " + num);
System.out.println("---------");
System.out.println("Enter a floating-point value:");
double num2 = keysIn.nextDouble();
System.out.println("Your floating-point: " + num2);
System.out.println("---------");
System.out.println("Now enter a string.");
String str = keysIn.next();
keysIn.close();
System.out.println(str);
}
}
Hello everyone~ I'm a little new in this theme of programming. I'm here to expose a particular case, of my college project, hoping that can find a way to validate the java code.
Basically, I'm designing a system to sum the daily sales of a company and save them into a matrix. The code below corresponds to the first day only.
package fsystem;
import java.util.ArrayList;
import java.util.Scanner;
public class class_Sist {
public class_Sist() {
}
ArrayList <Integer> MondayPrices = new ArrayList();
int Week[][]= new int [2][7];
public void addPricesDay1(){
Scanner scn = new Scanner(System.in);
String answer;
Integer auxAddition=0;
boolean flagNext= false, flagAgain= false;
System.out.println("Next it is come to apply the amounts of sales made on the day "+Week[0][0]+". Please "
+ "indicate the price of each of the items that were sold.");
do {
System.out.println("Enter the price of the corresponding article.");
MondayPrices.add(scn.nextInt());
do {
System.out.println("It requires enter the price of another article?");
answer= scn.next();
if (("Yes".equals(answer))||("yes".equals(answer))) {
flagNext=false;
flagAgain=true;
}
if (("No".equals(answer))||("no".equals(answer))){
flagNext=false;
flagAgain=false;
System.out.println("Introduced sales prices have been stored successfully.");
}
if ((!"Yes".equals(answer))&&(!"yes".equals(answer))&&(!"No".equals(answer))&&(!"no".equals(answer))) {
System.out.println("Error. Please respond using by answer only yes or no.");
flagNext=true;
}
} while (flagNext==true);
} while (flagAgain==true);
for (int i=0; i<MondayPrices.size(); i++) {
auxAddition= auxAddition+MondayPrices.get(i);
}
System.out.println("The total amount in sales for monday is "+auxAddition);
Week[1][0]=auxAddition;
}
}
So, what I need is to validate that the data inputted by the user be only numeric, and never otherwise, but I don't know completely how ArrayList works, therefore, I would greatly appreciate if someone could explain me how I can do that.
Use Scanner hasNextInt() function.
Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the nextInt() method.The scanner does not advance past any input.
Use it with while to check whether the input is integer.
Scanner stdin = new Scanner(System.in);
while (!stdin.hasNextInt()) stdin.next();
MondayPrice.add(stdin.nextInt());
http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt%28%29
You can validate the input before adding the integer in the ArrayList.
I hope this will help - How to use Scanner to accept only valid int as input
I'm using eclipse for this project. I've tried compiling in command prompt but the same problems happen. The scanner works until I get to "phone" and then it just seems to skip the user input and prints everything else on the same line.
I expect to store the users input into the assigned variables, and then print them out on separate lines.
I added sc.close; to see if that would help but it didn't. Some help would be greatly appreciated. Also my variable "address" isn't completely printed out.
I think I may be using Scanner incorrectly?
import java.util.Scanner;
public class ContactDisplay {
public static void main(String[] args) {
//Write a program that displays your name, address, and telephone number;
//create scanner
Scanner sc = new Scanner(System.in);
//Creates the variables;
String name;
String address;
String phone;
//Asks for name
System.out.print("What is your name? ");
//stores the name
name = sc.next();
//Asks and stores the address
System.out.print("What is your address? ");
address = sc.next();
//Asks and stores the phone number
//PROBLEM IS BELOW
System.out.print("What is your phone number? ");
phone = sc.next();
//Prints everything out
System.out.println(name);
System.out.println(address);
System.out.println(phone);
}
}
Here is a screenshot:
You should use 'sc.nextLine()' to scan string values, and you should use 'sc.nextInt' to scan integer values. If you press ctrl and space keys while typing a bunch of code it shows you the possible things you may want to write.
I am trying to replace a specific character '8' with a '2' in a string. I think I have everything set up correctly and when I look online for examples, this looks like it should. When I print the string though, it is just as I entered it. To run it, test it with "80802" or some similar input. Thanks!
import java.util.Scanner;
class PhoneNumber {
public static void main(String[] args) {
String number = null;
Scanner scan = new Scanner(System.in);
// Prompt the user for a telephone number
System.out.print("Enter your telephone number: ");
// Input the user's name
number = scan.nextLine();
// Replace the relevant letters with numbers
number.replace('8', '2');
System.out.println("Your number is: " + number );
}
}
A common mistake... You want:
number = number.replace('8', '2');
String.replace() doesn't change the String, because Strings are immutable (they can not be changed). Instead, such methods return a new String with the calculated value.
number.replace() returns a new string. It does not change `number'.
number.replace('8','2'); returns the correct string it does not modify number. To get your desired functionality you must type
number = number.replace('8','2');
public static void main(String[] args) {
String number = null;
Scanner scan = new Scanner(System.in);
// Prompt the user for a telephone number
System.out.print("Enter your telephone number: ");
// Input the user's name
number = scan.nextLine();
// Replace the relevant letters with numbers
number = number.replace('8', '2');
System.out.println("Your number is: " + number );
}
Hope this helps.