Using multiple user inputs and printing into a single line - java

I'm trying to get 3 different inputs from a user and then print them onto a single line, to get an end result of something like "The cow jumped over the moon." I'm brand new to Java and don't quite understand how to print these variables properly. Could anyone help?
import java.util.Scanner;
public class test_input {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first noun: ");
String n = scan.nextLine();
System.out.println("Enter the second noun: ");
String a = scan.nextLine();
System.out.println("Enter a verb: ");
String v = scan.nextLine();
System.out.println("The" +n +v "over the" +a);
}
}

Related

Problem with a console whoile executing program

Here is my code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter area code: ");
int areaCode = scan.nextInt();
System.out.println("Enter number: ");
int localNumber = scan.nextInt();
String phoneNumber = "(" + areaCode + ")-" + localNumber;
System.out.println("Calling number "+phoneNumber);
}
}
Execution is ok, program asks to enter two int variables, but when I try to submit my task I got this kind message in console:
Number of passing tests: 0
Number of failing tests: 2
--- Details ---
JUnit version 4.11
.E.E
Time: 0.053
There were 2 failures:
1) areaCode222Number3334444_ShouldPrintFormattedNumber(MainTest)
org.junit.ComparisonFailure: expected:<[]Calling number (222)...> but was:<[Enter area code:
Enter number:
]Calling number (222)...>
How to handle it? Should I have to clean up console??
Thanks in advance
It seems that the automated test does not expect "Enter area code: " and "Enter number: " messages printed. Just remove two System.out.println sentences which print these lines from your code.
Try this after every occurence of the nextInt sentence :
field.nextLine();
This method advances the Scanner instance (scan) past the current line and returns the input that was skipped.
Your code should look like this:
-- collapsed package and imports statements --
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter area code: ");
int areaCode = scan.nextInt();
scan.nextLine();
System.out.println("Enter number: ");
int localNumber = scan.nextInt();
scan.nextLine();
String phoneNumber = "(" + areaCode + ")-" + localNumber;
System.out.println("Calling number "+phoneNumber);
}
}
EDIT: Syntaxe.

homework parsing strings: removing comma from string (java zybooks)

I am trying to get the strings to separate, and WITHOUT the comma.
We haven't learned anything like arrays, this is an intro class.
Everything I find on here just keeps giving me errors or does nothing to my code in zybooks.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // Input stream for standard input
Scanner inSS = null; // Input string stream
String lineString = ""; // Holds line of text
String firstWord = ""; // First name
String secondWord = ""; // Last name
boolean inputDone = false; // Flag to indicate next iteration
// Prompt user for input
System.out.println("Enter input string: ");
// Grab data as long as "Exit" is not entered
while (!inputDone) {
// Entire line into lineString
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
firstWord = inSS.next();
lineString.split(",");
// Output parsed values
if (firstWord.equals("q")) {
System.out.println("Enter input string: ");
inputDone = true;
}
//This may be where I am messing up??
else if (lineString.contains(",")) {
secondWord = inSS.next();
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
} else {
System.out.println("Error: No comma in string");
System.out.println("Enter input string: ");
}
}
return;
}
}
I am messing up somewhere and keep getting different error codes as I keep messing with it...
"Enter input string:
First word: Jill,
Second word: Allen"
When it should be
"Enter input string:
First word: Jill
Second word: Allen"
And then also as the computer enters more data I start getting this message:
"Exception in thread "main" java.util.NoSuchElementException"
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ParseStrings.main(ParseStrings.java:44)"
One of the possibilities (if you didn't learn about arrays) is to use StringBuilder and remove commas or simply loop over input string and if character at let's say index 8 is comma, you do yourString.substring(0,8);, and then print the second word as yourString.substring(10, yourstring.length); I put starting index of 10 in the second substring because you want to skip comma and a space that's separating first and last name. Here is code sample for using nothing but String class, it's methods and for loop:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String str = in.nextLine();
int indexOfComma = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',')
indexOfComma = i;
}
System.out.println("First name is: " + (str.substring(0, indexOfComma)));
System.out.println("Last name is: " + (str.substring(indexOfComma + 2, str.length())));
}
}
Or as I see you tried using split() (but since you said you didn't learn arrays yet I posted solution above), you can do it with .split() like this:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
String[] name = in.nextLine().split(", ");
System.out.println("First name is: " + name[0]);
System.out.println("Last name is: " + name[1]);
}
}
Also, here is an example with StringBuilder class:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter first name and last name: ");
StringBuilder name = new StringBuilder(in.nextLine());
name.deleteCharAt(name.indexOf(","));
System.out.println("Full name is: " + name);
}
}
Your error happens when the Scanner reads all the data, such as calling the nextLine method and there's no line... Or next method when you didn't put a space after the comma
By default, the Scanner uses whitespace as a delimiter. If you want to add a comma delimiter before any whitespace, you can try this
Scanner sc=new Scanner(System.in);
sc.useDelimiter(",?\\s+");
Now, sc.next() will read only Hello from Hello, World, and a second call to it should return World
Or you can use the array you made
String[] words = lineString.split(",");
String first = words[0]:
String second = words[1];

How can I get multiple user inputs and save their value? [duplicate]

How could I read input from the console using the Scanner class? Something like this:
System.out.println("Enter your username: ");
Scanner = input(); // Or something like this, I don't know the code
Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.
A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in. It's really quite simple.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
To retrieve a username I would probably use sc.nextLine().
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);
You could also use next(String pattern) if you want more control over the input, or just validate the username variable.
You'll find more information on their implementation in the API Documentation for java.util.Scanner
Scanner scan = new Scanner(System.in);
String myLine = scan.nextLine();
Reading Data From The Console
BufferedReader is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes.
readLine() « just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \r\n
Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\s) and it is recognised by Character.isWhitespace.
« Until the user enters data, the scanning operation may block, waiting for input.
« Use Scanner(BUFFER_SIZE = 1024) if you want to parse a specific type of token from a stream.
« A scanner however is not thread safe. It has to be externally synchronized.
next() « Finds and returns the next complete token from this scanner.
nextInt() « Scans the next token of the input as an int.
Code
String name = null;
int number;
java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
name = in.readLine(); // If the user has not entered anything, assume the default value.
number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
System.out.println("Name " + name + "\t number " + number);
java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
name = sc.next(); // It will not leave until the user enters data.
number = sc.nextInt(); // We can read specific data.
System.out.println("Name " + name + "\t number " + number);
// The Console class is not working in the IDE as expected.
java.io.Console cnsl = System.console();
if (cnsl != null) {
// Read a line from the user input. The cursor blinks after the specified input.
name = cnsl.readLine("Name: ");
System.out.println("Name entered: " + name);
}
Inputs and outputs of Stream
Reader Input: Output:
Yash 777 Line1 = Yash 777
7 Line1 = 7
Scanner Input: Output:
Yash 777 token1 = Yash
token2 = 777
There is problem with the input.nextInt() method - it only reads the int value.
So when reading the next line using input.nextLine() you receive "\n", i.e. the Enter key. So to skip this you have to add the input.nextLine().
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (it consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
There are several ways to get input from the user. Here in this program we will take the Scanner class to achieve the task. This Scanner class comes under java.util, hence the first line of the program is import java.util.Scanner; which allows the user to read values of various types in Java. The import statement line should have to be in the first line the java program, and we proceed further for code.
in.nextInt(); // It just reads the numbers
in.nextLine(); // It get the String which user enters
To access methods in the Scanner class create a new scanner object as "in". Now we use one of its method, that is "next". The "next" method gets the string of text that a user enters on the keyboard.
Here I'm using in.nextLine(); to get the String which the user enters.
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[]) {
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] arguments){
Scanner input = new Scanner(System.in);
String username;
double age;
String gender;
String marital_status;
int telephone_number;
// Allows a person to enter his/her name
Scanner one = new Scanner(System.in);
System.out.println("Enter Name:" );
username = one.next();
System.out.println("Name accepted " + username);
// Allows a person to enter his/her age
Scanner two = new Scanner(System.in);
System.out.println("Enter Age:" );
age = two.nextDouble();
System.out.println("Age accepted " + age);
// Allows a person to enter his/her gender
Scanner three = new Scanner(System.in);
System.out.println("Enter Gender:" );
gender = three.next();
System.out.println("Gender accepted " + gender);
// Allows a person to enter his/her marital status
Scanner four = new Scanner(System.in);
System.out.println("Enter Marital status:" );
marital_status = four.next();
System.out.println("Marital status accepted " + marital_status);
// Allows a person to enter his/her telephone number
Scanner five = new Scanner(System.in);
System.out.println("Enter Telephone number:" );
telephone_number = five.nextInt();
System.out.println("Telephone number accepted " + telephone_number);
}
}
You can make a simple program to ask for the user's name and print whatever the reply use inputs.
Or ask the user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like the behavior of a calculator.
So there you need the Scanner class. You have to import java.util.Scanner;, and in the code you need to use:
Scanner input = new Scanner(System.in);
input is a variable name.
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name: ");
s = input.next(); // Getting a String value
System.out.println("Please enter your age: ");
i = input.nextInt(); // Getting an integer
System.out.println("Please enter your salary: ");
d = input.nextDouble(); // Getting a double
See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();
According to a String, int and a double varies the same way for the rest. Don't forget the import statement at the top of your code.
A simple example:
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
int number1, number2, sum;
Scanner input = new Scanner(System.in);
System.out.println("Enter First multiple");
number1 = input.nextInt();
System.out.println("Enter second multiple");
number2 = input.nextInt();
sum = number1 * number2;
System.out.printf("The product of both number is %d", sum);
}
}
When the user enters his/her username, check for valid entry also.
java.util.Scanner input = new java.util.Scanner(System.in);
String userName;
final int validLength = 6; // This is the valid length of an user name
System.out.print("Please enter the username: ");
userName = input.nextLine();
while(userName.length() < validLength) {
// If the user enters less than validLength characters
// ask for entering again
System.out.println(
"\nUsername needs to be " + validLength + " character long");
System.out.print("\nPlease enter the username again: ");
userName = input.nextLine();
}
System.out.println("Username is: " + userName);
To read input:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
To read input when you call a method with some arguments/parameters:
if (args.length != 2) {
System.err.println("Utilizare: java Grep <fisier> <cuvant>");
System.exit(1);
}
try {
grep(args[0], args[1]);
} catch (IOException e) {
System.out.println(e.getMessage());
}
import java.util.*;
class Ss
{
int id, salary;
String name;
void Ss(int id, int salary, String name)
{
this.id = id;
this.salary = salary;
this.name = name;
}
void display()
{
System.out.println("The id of employee:" + id);
System.out.println("The name of employye:" + name);
System.out.println("The salary of employee:" + salary);
}
}
class employee
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Ss s = new Ss(sc.nextInt(), sc.nextInt(), sc.nextLine());
s.display();
}
}
Here is the complete class which performs the required operation:
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int valid = 6;
Scanner one = new Scanner(System.in);
System.out.println("Enter your username: ");
String s = one.nextLine();
if (s.length() < valid) {
System.out.println("Enter a valid username");
System.out.println(
"User name must contain " + valid + " characters");
System.out.println("Enter again: ");
s = one.nextLine();
}
System.out.println("Username accepted: " + s);
Scanner two = new Scanner(System.in);
System.out.println("Enter your age: ");
int a = two.nextInt();
System.out.println("Age accepted: " + a);
Scanner three = new Scanner(System.in);
System.out.println("Enter your sex: ");
String sex = three.nextLine();
System.out.println("Sex accepted: " + sex);
}
}
There is a simple way to read from the console.
Please find the below code:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Reading of Integer
int number = sc.nextInt();
// Reading of String
String str = sc.next();
}
}
For a detailed understanding, please refer to the below documents.
Doc
Now let's talk about the detailed understanding of the Scanner class working:
public Scanner(InputStream source) {
this(new InputStreamReader(source), WHITESPACE_PATTERN);
}
This is the constructor for creating the Scanner instance.
Here we are passing the InputStream reference which is nothing but a System.In. Here it opens the InputStream Pipe for console input.
public InputStreamReader(InputStream in) {
super(in);
try {
sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## Check lock object
}
catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
}
By passing the System.in this code will opens the socket for reading from console.
You can flow this code:
Scanner obj= new Scanner(System.in);
String s = obj.nextLine();
You can use the Scanner class in Java
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println("String: " + s);
import java.util.Scanner; // Import the Scanner class
class Main { // Main is the class name
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
you have wrote
Scanner = input()
this is wrong method, you have to make an integer or a string, i would like to prefer string, and then give a string any name that can be i that can be n or anything else, remember that you are giving name to username you can also give name username also, and the code is
String username = sc.nextline();
System.our.println("the username is" + username);
I hope you understand now

Need to have a string "Enter a number: " repeat

As the title said I need to enter a string "Enter a number: " repeat itself after I've entered multiple values until I enter "DONE."
So for example it should look like this:
Enter a number:
4
Enter a number:
53
Enter a number:
DONE //closes program
This is a small part to a larger program and granted I know its simple, but I cant figure this out :[
What I'm guessing and been trying is a public static class with a toString method. But I can only get one "Enter a number: " printed once.
Enter a number:
4
53
DONE //closes program
Thanks in advance.
Some code I have for this part would be:
import java.util.Scanner;
public class EnterANumba
{
public static void main(String[] args)
{
while() //Stuck here
{
System.out.println("Enter a number:");
}
Scanner scanner = new Scanner(System.in);
String word=null;
while (scanner.hasNextLine())
{
word = scanner.nextLine();
if (word != null)
{
word = word.trim();
if (word.equalsIgnoreCase("done"))
{
break;
}
}
else
{
break;
}
}
I guess this following code snippet may help you.
public class Main {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter a number:");
while(!(s.next().equalsIgnoreCase("DONE"))){
System.out.println("Enter a number:");
}
}
}
try asking for the 1st time and then make a loop where you validate the input and ask until the condition is met...
Example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number:");
while (!("done".equalsIgnoreCase(scanner.next()))) {
System.out.println("Enter a number:");
}
System.out.println("Enter a number:we are done....");
}

How can I delay the execution of a command? [duplicate]

This question already has answers here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
How to use scanner in java? [duplicate]
(7 answers)
Closed 7 years ago.
I have to say I am a newbie in java programming so I would like some help with the following question:
How can I delay a java program so that it waits for a user to give an input?
Here is my code:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.println("1st value= ");
Scanner aa1 = new Scanner(System.in);
System.out.println("2nd value= ");
Scanner bb1 = new Scanner(System.in);
What I get now from this code is "1st value= " and "2nd value= " displayed. After that the program requests the input.
Any ideas on how can I make this simple programm to wait for the user's answer before printing "2nd value= " in the console?
Ask for input from the user:
int index = aa1.nextInt();
You don't need to create two Scanner variables. You can use one of them and use the function input.nextInt(); to get both values, where input it's the name of the Scanner variable.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number1, number2;
System.out.println("1st value= ");
number1 = input.nextInt();
System.out.println("2nd value= ");
number2 = input.nextInt();
}
}
You must first import the Scanner before your Main class.
import java.util.Scanner;
You must then create a Scanner variable. I use "in" in my example:
Scanner in = new Scanner(System.in);
This will force the program to wait for user input.
` import java.util.Scanner;
public class Example{
public static void main( String[] args )
{
String name;
String address;
String cityStateZip;
Scanner in = new Scanner(System.in);
//User input
System.out.println("What is your name?");
name = in.nextLine();
System.out.println("Enter your address:");
address = in.nextLine();
System.out.println("Enter your City, State, and Zip code:");
cityStateZip = in.nextLine();`
You have to use only one Scanner variable. This is the solution :
import java.util.Scanner;
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println("1st value= " + str);
str = sc.nextLine();
System.out.println("2nd value= " + str);
}
}
You can see the different next***() on the doc on this link http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html.
I advise you to follow a Java formation if you want to code in this language.
You can use it as:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("1st value= "
+ input.nextInt()
+ "2nd value= "
+ input.nextInt());
}
For further reference to can go through Scanner java doc http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Add necessary imports by pressing control+shift+o after you have typed the main function.
public static void main(String agrs[])
{
// Take Scanner object
Scanner scanner =new Scanner(System.in);
// Ask user for 1st input
System.out.println("Enter 1st value:");
String value=scanner.nextLine();
System.out.println("1st value is ="+s);
// Ask user for 2nd input
System.out.println("Enter 2nd value:");
value=scanner.nextLine();
System.out.println("2nd value is ="+s);
}
NOTE : scanner.nextLine() will read the user input as a String,
If you need the input as int , use scanner.nextInt(); For float use scanner.nextFloat() and so on.
Now the console is halted for user input and then asks for second input.
Hope it helps.

Categories

Resources