I need to write a test class that will do the following:
a. Let the user input an integer and display it.
b. Let the user input a float value and display it.
c. Let the user input his/her name (no white spaces) and display the
name as: “Hello <name>, welcome to Scanner!”
d. Let the user input a character and display it.
e. Let the user input any string (with white spaces) and display it.
My questions is, how can I simply scan just a Character and display it? And in number 2, How can I input a String with white spaces and display it? (letters "d" and "e")
I've searched around, but I cannot find the simplest solution (since I'm new to Java and programming).
Here is my code so far:
package aw;
import java.io.PrintStream;
import java.util.Scanner;
public class NewClass1
{
public static void main(String[] args)
{
int num;
double num2;
String name;
char c;
Scanner sc = new Scanner(System.in);
PrintStream ps = new PrintStream(System.out);
//for integer
System.out.println("Enter a number: ");
num = sc.nextInt();
ps.printf("%d\n", num);
//for float
System.out.println("Enter a float value: ");
num2 = sc.nextDouble();
ps.printf("%.2f\n", num2);
//for name w/o white space
System.out.print("Enter your first name: ");
name = sc.next();
ps.printf("Hello %s, welcome to Scanner\n", name);
//for character
System.out.print("Enter a character: ");
c = sc.findWithinHorizon(".", 0).charAt(0);
System.out.print(“%c”, c);
//for name w/ white space
System.out.print("Enter your full name: ");
name = sc.nextLine();
System.out.print(“%s”, name);
}
}
I hope you can help me. Thanks!
First, there's no need to wrap System.out in a PrintStream because out already supports formatting with format() or printf() methods.
Next, you need to understand that when you input a line of data you also terminate it with a new line \n. The next<Type>() methods only consume the <Type> and nothing else. So, if a next<Type>() call may match \n, you need to skip over any extra new lines \n with another nextLine() before.
Here's your code with fixes:
int num;
double num2;
String name;
char c;
Scanner sc = new Scanner(System.in);
//for integer
System.out.print("Enter a number: ");
num = sc.nextInt();
System.out.printf("%d\n", num);
//for float
System.out.print("Enter a float value: ");
num2 = sc.nextDouble();
System.out.printf("%.2f\n", num2);
//for name w/o white space
System.out.print("Enter your first name: ");
name = sc.next();
System.out.printf("Hello %s, welcome to Scanner\n", name);
//for character
System.out.print("Enter a character: ");
c = sc.findWithinHorizon(".", 0).charAt(0);
System.out.printf("%c\n", c);
sc.nextLine(); // skip
//for name w/ white space
System.out.print("Enter your full name: ");
name = sc.nextLine();
System.out.printf("%s", name);
Use Scanner.next(Pattern) and pass Pattern.compile("[A-Za-z0-9]") to let scanner accept only 1 character defined. You can pass any regex as argument and check for next() Scanner.next(); for next line with spaces
Use this:
//for a single char
char Character = sc.findWithinHorizon(".", 0).charAt(0);
//for a name with white space
System.out.print("Enter your full name: ");
String name2 = sc.next();
String surname = sc.next();
System.out.println(name2 + " " + surname);
Related
The Following code is a simple java program where I am just getting an input of a student details but the program doesn't do anything it just stays like this no compilation error or does not take any input
import java.util.Scanner;
public class Scannerexample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int Rollno = scan.nextInt();
String firstname = scan.nextLine();
String lastname = scan.nextLine();
String Department = scan.nextLine();
Boolean Result = scan.hasNext();
char gender = scan.next().charAt(0);
System.out.println("Enter Rollno "+ Rollno);
System.out.println("Enter Firstname "+ firstname);
System.out.println("Enter Lastname "+ lastname);
System.out.println("Enter Department "+ Department);
System.out.println("Enter Result "+ Result);
System.out.println("Enter Gender "+ gender);
scan.close();
}
}
Each call of scan.nextSomething waits for input. So the way you have written the program you wait for inputting of all the fields and then print them. Try typing some fields and press enter to see the result in the end.
What you probably wanted is something like:
System.out.println("Enter rollno: ");
int rollno = scan.nextInt();
System.out.println("You entered rollno: "+ rollno);
Also there are some java conventions which are nice and make the code readable :) For example variables start with lowercase and classes are in CamelCase
So what your Code does is every time you call
scan.nextLine();
The Program waits for your Input, until you hit 'Enter'.
So if you want to write something before the Input, you have to do it like this:
System.out.print("Enter Rollno: ");
int rollno = scan.nextInt();
System.out.print("Enter Firstname: ");
String firstname = scan.next();
// Any more.
Keep an eye that you only use 'print()' instead of 'println()' so that your input is on the same Line.
Also use scan.next(), to only grab the input, and not the complete line in terminal.
be carefull with scan.next() or scan.nextLine()
System.out.print("Enter Rollno: ");
int rollno = scan.nextInt();
System.out.print("Enter Firstname: ");
String firstname = scan.next();
System.out.println(firstname);
// Any more.
System.out.print("Enter Lastname: ");
String lastname = scan.next();
System.out.println(lastname);
in this case, if you input Firstname as: John Doe, it will not let you to input Lastname, because it will read next string in line.
scan.next() read strings up to "space", then another scan.next() will read next strings up to next "space".
I've seen a couple of threads that are similar to this question, but had trouble finding the solution to my specific question.
The code I am writing is for a teacher to input a student's name and grades and receive an output of the final letter grade.
The area I am having trouble with is the last name input gets grouped together with the first name input, instead of asking the question by itself. How do I prompt these to appear as separate questions?
import java.util.*;
public class AssignmentTest {
public static void main (String [] args) {
Scanner console = new Scanner (System.in);
int iStudentID = 0; //StudentID
String sLastName = ""; //Last Name
String sFirstName = ""; //First Name
int iAssignmentsScore = 0; //Assignment Input
int iQuizzesScore = 0; //Quizzes Input
int iMidtermsScore = 0; //Midterm Input
int iFinalScore = 0;; //Final Input
//USER INPUT
//StudentID Input
System.out.println("Please enter the StudentID: ");
iStudentID = console.nextInt() ;
//Last Name Input
System.out.println ("Please enter the student's last name: ");
sLastName = console.nextLine() ;
//First Name Input
System.out.println ("Please enter the student's first name: ");
sFirstName = console.nextLine() ;
//Assignment Input
System.out.println ("Please enter the student's assignment score: ");
iAssignmentsScore = console.nextInt() ;
//Quiz Input
System.out.println ("Please enter the student's quiz score: ");
iQuizzesScore = console.nextInt ();
//Midterm Input
System.out.println ("Please enter the student's midterm score: ");
iMidtermsScore = console.nextInt ();
//Final Input
System.out.println ("Please enter the student's final score: ");
iFinalScore = console.nextInt ();
}
}
Since sFirstName and lFirstName , each consist of a word you should use
next()
Finds and returns the next complete token from this scanner.
Instead of
nextLine()
Advances this scanner past the current line and returns the input that
was skipped.
#madprogrammer has better explanation:
Actually, the issue is after iStudentID = console.nextInt() ; returns,
there is still a new line character in the buffer, so that when
sLastName = console.nextLine() ; is called, it skips of this
automatically (returning an empty String) - this is a very common
mistake
try this
System.out.println ("Please enter the student's last name: ");
sLastName = console.nextLine() ;
console.nextLine();
I think this may be as simple as adding another new line character \n. For example
System.out.println ("\nPlease enter the student's first name: ");
you should use next() instead of nextLine()
I have a question. I know you can prompt a user multiple times with scanner as so
public static void main(String[] args) {
String First;
String Last;
int Age;
Scanner input = new Scanner(System.in);
System.out.print("What is the First name of person?");
First = input.next();
System.out.print("What is the Last name of person?");
Last = input.next();
System.out.print("What is the Age of person?");
Age = input.next();
}
But is there a way there to prompt all in one line?
For example I want to enter
Console-What is the First, Last, and Age of the person?
User- First Last Age
First, Java variables start with a lower case letter by convention (yours look like class names). Second, this
Age = input.next();
gives you a compiler error. Because Age is an int. You can certainly split the single line as others have suggested, but you can also construct a Scanner(String) and use it with something like
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first name last name and age of the person: ");
System.out.println("(first last age)");
String line = input.nextLine();
Scanner scan = new Scanner(line);
String first = scan.next();
String last = scan.next();
int age = scan.nextInt();
System.out.printf("Person: %s, %s (%d)%n", last, first, age);
Grab a line and split the string:
Scanner input = new Scanner(System.in);
System.out.print("What is the First, Last, and Age of the person?");
String line = input.nextLine();
String[] parts = line.split(" ");
if(parts.length < 3){
//error, ask again
}
else{
String first = parts[0];
String last = parts[1];
String age = parts[2];
}
I'm trying to make a program that will ask for a number of people to go into an ArrayList and then pick a name out of it randomly. The code is working fine but the string asking for name input displays itself twice the first time you run it. Any clue why this happens?
What I want it to display:
Enter a name: ......
What it displays:
Enter a name:
Enter a name: ......
import java.util.*;
class RandomNumGen
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random random = new Random();
ArrayList<String> names = new ArrayList<String>();
int a, b;
System.out.print("\nEnter the number of people: ");
a = input.nextInt();
System.out.println();
for (int i = 0; i <= a; i++)
{
System.out.print("Enter a name: ");
names.add(input.nextLine());
}
b = random.nextInt(a);
System.out.print("\nRandom name: " +names.get(b)+ "\n");
}
}
The issue is that nextInt() just consumes an integer, but not the new-line character inputted when you press Enter.
To solve this you can add
input.nextLine();
after the call to nextInt() so it consumes the new-line character.
Another option would be reading a whole line, and then parsing its content (String) to a int:
a = Integer.parseInt(input.nextLine());
I already try to make a program it works as well but the problem is, that is not the same output what i want.
Note **
That is what i want..
enter starting base: it should be binary or octal or hexa
enter end base: it should be decimal
enter number: if 2 is entered as the starting base only 1s and 0s can be entered. If 16 is entered as the starting base 0-9 and A-F can be used.
and what i make :(
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a starting base: ");
String binaryNumber = scanner.nextLine();
System.out.println("Enter a end base: ");
String octalNumber = scanner.nextLine();
System.out.println("Enter a number: ");
String decimalNumber = scanner.nextLine();
int myInt = Integer.parseInt(binaryNumber, 2);
int myInt2 = Integer.parseInt(octalNumber, 8);
int x = myInt;
System.out.println(
binaryNumber + " in Binary, is "
+ Integer.toString(myInt, 8) + " in Octal" + " and "
+ Integer.toString(x, 10) +" in decimal");
This is what you need to do. Figure out the code and understand. You have Scanner#nextInt() method to read integers. You don't have to use nextLine() method for this. And more over, Scanner#nextInt(int radix) accepts the input in specified radix form. It throws an exception if you don't enter the input in that form. You can catch that exception to display the error message to the user.
Your goals startBase,endBase, and the variables used for them binaryNumber is mismatching. Please name your variables which convey the purpose of them.
See the modified version of your code here:
import java.util.*;
public class Tester{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a starting base: ");
int startBase = scanner.nextInt();
System.out.println("Enter a end base: ");
int endBase = scanner.nextInt();
int number=0;
try{
System.out.println("Enter a number: ");
number= scanner.nextInt(startBase);
System.out.println("Entered number:"+number+"(base"+startBase+")");
System.out.println("Converted number:"+Integer.toString(number,endBase)+"(enbase"+endBase+")");
}catch(InputMismatchException e){
System.out.println("Invalid input for the given radix");
e.printStackTrace(); //you can comment it if you don't need this.
}
}
}