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());
Related
I'm new to Java & I don't even know if what I'm trying to do is actually doable in cmd but I want to know if there's a way to ask the user for an input while displaying something at the right of the input, something like:
enter weight: _ kg
specifying the unit I want the weight in for example
here is the code sample I have so far
import java.util.*;
public class ScannerPrompt {
public static void main(String[] args) {
int[] listOfIntegers = new int[10];
Scanner s = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.print("Enter num: ");
int num = s.nextInt();
listOfIntegers[i] = num;
}
}
}
We can use \r in a tricky way:
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) {
int i=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter num: __kg\r");
System.out.print("Enter num: ");
i = s.nextInt();
System.out.println("\n"+i);
}
}
How it works:
we print Enter num: __kg and \r to make cursor at the begining of the line
Now if we print something, it will overwrite the fist message because cursor is in fist position, so we overwrite with same letters but just the part that will make the cursor at the desired position. Hence we print Enter num:
Dont use println because it insert \n at the end, and dont test in an IDE but use the console of your system.
You could use carriage return \r to relocate the cursor to the start of line
System.out.printf("%20skg\rEnter num: ", " ");
I have completed most of the code by myself (with the help of a bit of Googling) but I have run into an unexpected problem. First-off, I have to sort a user entered list of names in aplhabetical order of their last names using selection sort. Here is my code:
import java.util.*;
class Name_Sort
{
public static void main (String args[])
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n];
for (int i = 0; i<ar.length; i++)
{
System.out.print("Please enter the name: ");
ar[i]= in.nextLine();
}
String temp;
for (int b = 0; b<n; b++)
{
for (int j=b+1; j<n; j++)
{
if ((compareLastNames(ar[b], ar[j]))>0)
{
temp = ar[b];
ar[b] = ar[j];
ar[j] = temp;
}
}
}
System.out.println ("The names sorted in alphabetical order are: ");
for (int a = 0; a<n; a++)
System.out.print (ar[a]+"\t");
}
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
}
The problem (I think) is arising when I'm taking the names from the user, specifically, this part:
Scanner in = new Scanner (System.in);
System.out.print ("Enter the number of names you wish to enter: ");
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}
The output on the terminal window of BlueJ shows up as
Name_Sort.main({ });
Enter the number of names you wish to enter: 5
Please enter the name:
Please enter the name:
That is not what it's supposed to display. What could I be doing wrong? I've pondered over it for a while, but nothing comes to mind.
And, even if I do move forward and enter a few names despite the error above, I get another error in this part of my code here:
private static int compareLastNames(String a, String b)
{
int index_a = a.lastIndexOf(" ");
String surname_a = a.substring(index_a);// This is the line the compiler highlights.
int index_b = b.lastIndexOf(" ");
String surname_b = b.substring(index_b);
int lastNameCmp = surname_a.compareToIgnoreCase(surname_b);
return lastNameCmp;
}
the error is :
java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (injava.lang.String)
Does this mean that the white-space character " " is not present? But why?
This is a screenshot of the terminal window:
http://imgur.com/l7yf7Xn
The thing is, if I just initialize the array with the names first (and not take any input from the user) the codes runs fine and produces the desired result. Any help please?
Also, since I know some people here are very particular about this, yes, this is a homework assignment, yes, I did do all of the code by myself, I googled on how to sort the names in alphabetical order as I couldn't exactly code out the original idea I had.
Which was comparing the ASCII values of each character of two surnames to see which should come first. Like: if((int) surname1.charAt(0)>(int) surname2.charAt(0)) then surname2 should come before surname1, else if they both have the same first character, take the second character and so on.
Thanks for taking the time to read this.
The problem is with the in.nextInt() command it only reads the int value. So when you continue reading with in.nextLine() you receive the "\n" Enter key. So to get around this you will have to add an extra in.nextLine() before going into the loop. Or, use another scanner.
int n = in.nextInt();
String ar[] = new String [n]; //Array to store the names in.
in.nextLine(); // < --- an extra next Line
for (int i = 0; i<ar.length; i++)
{
System.out.println("Please enter the name: ");
ar[i]= in.nextLine();
}
My assignment asks me to write a program that will let the user input 10 players' name, age, position, and batting average. The program should then check and display statistics of only those players who are under 25 years old and have a batting average of .280 or better, then display them in order of age.
I've written my code for the input section (where it'll store them in an array):
static int players[] = new int [10];
static String name[] = new String [10];
static double average [] = new double [10];
static int age[] = new int [10];
static String position[] = new String [10];
//method to input names of Blue Jays
public static void inputInfo() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(int i = 0; i < players.length; i++)
{
System.out.println("Enter player information.");
System.out.println("Input first and last name: ");
name [i] = br.readLine();
System.out.println("Input position: ");
position[i] = br.readLine();
System.out.println("Input batting average (e.g. .246): ");
String averageString = br.readLine();
average [i] = Double.parseDouble(averageString);
System.out.println("Input age: ");
age[i] = br.read();
System.out.println(" ");
}
}
My problem is the input. For the first player I input it shows me this (as it should):
Input first and last name:
John Smith
Input position:
pitcher
Input batting average (e.g. .246):
.300
Input age:
27
But my second input skips the name section completely and jumps to the position input. I can't really figure out why it's doing this! Can anyone help me out? Thanks in advance!
The read method reads only a single character of input; the rest of the line you've entered remains in the stream.
When the next loop starts, readLine detects that it can read the rest of the line already, so it does with no user input. It thinks the user input is already given.
For the input age, use readLine instead of read, and you can use Double.parseDouble to convert the resulting String input to a double.
When you read in the age here:
System.out.println("Input age: ");
age[i] = br.read();
the newline from the user pressing <Enter> is still there. So, when you go back and do
System.out.println("Enter player information.");
System.out.println("Input first and last name: ");
name [i] = br.readLine();
the newline is still in the buffer and will be read in here.
read() only reads a single character at a time. When you press after entering your age, it appends a new line character to the end which triggers the .readLine() for name.
System.out.println("Input age: ");
age[i] = Integer.parseInt(br.readLine());
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);
I am trying to print from an ArrayList using an ListIterator, i'm pretty sure i'm doing it wrong because it's not working but I don't know how to fix it. All so the line that grabs the part number isn't working, not sure why ;P. Any help is always appreciated :).
package invoice;
import static java.lang.System.out;
import java.util.*;
public class InvoiceTest {
public static void print(){
}
public static void main (String args[]) {
Scanner imput = new Scanner (System.in);
ArrayList lInvoice = new ArrayList() ;
int counter = 0;
int partCounter;
out.println("Welcome to invoice storer 1.0!");
out.println("To start please enter the number of items: ");
partCounter = imput.nextInt();
while (counter < partCounter){
counter++;
out.println("Please enter the part number:");
Invoice invoice1 = new Invoice(); //Makes invoice 1 use the invoice class
String partNumber = imput.nextLine();// sets part number to the next imput
//invoice1.setPartNumber(partNumber);// Sets it to the private variable in invoice.java
lInvoice.add(partNumber);
out.println("Please enter in a discription of the part: ");
String partDis = imput.nextLine();
//invoice1.setPartDis(partDis);
lInvoice.add(partDis);
out.println ("Please enter the number of items purchased: ");
int quanity = imput.nextInt();
//invoice1.setQuanity(quanity);
lInvoice.add(quanity);
out.println ("Please enter the price of the item:");
double price = imput.nextDouble();
//invoice1.setPrice(price);
lInvoice.add(price);
}
ListIterator<String> ltr = lInvoice.listIterator();
while(ltr.hasNext());
out.println(ltr.next());
}
}
There is some other errors in your program.
First, you shoud add a type to your ArrayList. Since you're trying to add int, double and String, I recommend you to create an ArrayList<Object> lInvoice = new ArrayList<Object>() ;
Then just loop with your iterator :
ListIterator<Object> ltr = lInvoice.listIterator();
while(ltr.hasNext()){
out.println(ltr.next());
}
You actually don't print anything within the while loop, because your println() callback is out of the scope of the loop. Fix it like this:
ListIterator<String> ltr = lInvoice.listIterator();
while(ltr.hasNext()) {
out.println(ltr.next());
}
Putting on my psychic debugger hat, I'm guessing you meant to print out a line-item invoice. I'm making some assumptions about the contents of Invoice.java, but I'm guessing the below code is what you really wanted:
Scanner imput = new Scanner(System.in);
ArrayList<Invoice> lInvoice = new ArrayList<Invoice>();
int counter = 0;
int partCounter;
out.println("Welcome to invoice storer 1.0!");
out.println("To start please enter the number of items: ");
partCounter = imput.nextInt();
imput.nextLine();//skips the rest of the line (carriage return)
while (counter < partCounter) {
counter++;
out.println("Please enter the part number:");
Invoice invoice1 = new Invoice(); // Makes invoice 1 use the invoice
// class
String partNumber = imput.nextLine();// sets part number to the next
// imput
invoice1.setPartNumber(partNumber);// Sets it to the private
// variable in invoice.java
out.println("Please enter in a discription of the part: ");
String partDis = imput.nextLine();
invoice1.setPartDis(partDis);
out.println("Please enter the number of items purchased: ");
int quanity = imput.nextInt();
imput.nextLine();
invoice1.setQuanity(quanity);
out.println("Please enter the price of the item:");
double price = imput.nextDouble();
imput.nextLine();
invoice1.setPrice(price);
lInvoice.add(invoice1);
}
ListIterator<Invoice> ltr = lInvoice.listIterator();
while (ltr.hasNext()) {
Invoice next = (Invoice)ltr.next();
out.println(next.getPartNumber()+"\t"+next.getPartDis()+"\t"+next.getPrice()+"\t"+next.getQuanity());
}
Interesting changes:
I'm using a list of Invoice instead a list of strings, and then printing out each one
Scanner.nextInt() will leave the carriage return from its input, so you have to call nextLine() to clear it, or you'll miss the input you really wanted.