java Program does not wait for the user input - java

My program requires users to input some data. My problem is, when it runs, it shows the first question and then immediately moves to the second question, without waiting for the user input. My friend suggested putting sc.nextLine(), it did work for the first time, but when it looped back it gave me an additional space and actually saved the space to my obj.
To illustrate, when i run it, it shows:
Original: Enter position no 1: How many seats?(use can input)
With the additional sc.nextLine: Enter position no 1: (user can input)
How many seats:
BUT second time it shows: Enter position no 2: (user can input)
(and then space)
and then the succeeding question: How many seats:
Below is my whole code in my main class. Thanks in advance.
package election;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.StringBuilder;
public class Election {
public static void main(String[] args) {
int maxpos;
int count;
int maxcan;
int cancount;
String name;
int num;
String position;
int posnum;
int seat;
String party;
int vote;
Scanner sc = new Scanner(System.in);
ArrayList<Candidate> list = new ArrayList<Candidate>();
Candidate c;
do{
System.out.print("How many positions for this election: ");
maxpos = sc.nextInt();
for(count = 1; count<=maxpos; count++){
System.out.print("Enter position no. " + count + ": ");
position = sc.nextLine();
sc.nextLine();
posnum = count;
System.out.print("How many seats: ");
seat = sc.nextInt();
System.out.print("Enter number of candidates: ");
maxcan = sc.nextInt();
for(cancount = 1; cancount<=maxcan; cancount++){
System.out.print("Enter candidate no. " + cancount + " name: " );
name = sc.nextLine();
num = cancount;
System.out.print("Enter candidate no. " + cancount + " party: " );
party = sc.nextLine();
c = new Candidate(name, num, position, posnum, seat, party);
list.add(c);
}
}
}while(!(count > maxpos));
for(int i = 0; i<list.size(); i++){
list.get(i).displayInfo();
}
}
}

Whenever you use nextInt(), you need to put nextLine() after it
System.out.print("How many seats: ");
seat = sc.nextInt();
sc.nextLine();
System.out.print("Enter number of candidates: ");
maxcan = sc.nextInt();
sc.nextLine();
This will consume the unconsumed \n character from stream

Instead of using the Scanner, you can use readLine() of DataInputStream
DataInputStream din=new DataInputStream(System.in);
System.out.print("Enter number of candidates: ");
int maxcan =Integer.parseInt(din.readLine());

Related

Adding the code for ascending order of user input

import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
line = in.nextLine();
System.out.print("Input Number 1: " );
line = in.nextLine();
System.out.print("Input Number 2: ");
line = in.nextLine();
System.out.print("Input Number 3: " );
line = in.nextLine();
System.out.print("Input Number 4: ");
line = in.nextLine();
System.out.print("Input Number 5: " );
line = in.nextLine();
}
public static void sortAscending (double[]arr)
{
Arrays.sort(arr);
System.out.printf("Sorted arr[] = %s",
Arrays.toString(arr));
}}
I am stuck on what the code is for putting the what the user inputs in ascending order. I have looked up and tried multiple resources on ascending order but nothing seems to work. I tried:
System.out.print("Input number 1: "+(i+1+":");
to try and add the inputs instead of writing all of them out but i was an unknown variable.
You should use an array to store input and a loop to read input.
System.out.print("How many numbers you want to input?: ");
int num = in.nextInt();
double[] arr = new double[num];
for(int i = 0; i < num; i++){
arr[i] = in.nextDouble();
}
sortAscending(arr);
You have to create an array. Then put the stuff you are reading into the array and after that call your method.
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
sortAscending(values);
Note that the name sortAscending is not accurate, it is not just sorting (and then returning the result or in-place), but also printing. So maybe you should rename it to sortAndPrintAscending. Or just sort it and let your main method to the printing.
Or drop it completely, the method does not really serve any purpose as it is just calling Arrays.sort, might as well do that in main:
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
Arrays.sort(values);
System.out.println("Sorted: " + Arrays.toString(values));

Loop->Array Output

I'm writing a loop to fill an array. I think I have the coding down, but when I run the compiled code through Java, it doesn't come out right in the command prompt.
Here's the code:
import java.util.Scanner;
import java.io.*;
public class Pr42
{
public static void main(String[]args) throws IOException
{
int k,m,g;
String n;
//double g;
Scanner input1=new Scanner(System.in);
String[]Name=new String [5];
double[]Grade=new double[Name.length];
k=0;
while (k<Name.length)
{
m=k+1;
System.out.print("Enter the name of student "+m+": ");
Name[k]=input1.nextLine();
System.out.print("");
System.out.print("Please enter the grade of student "+m+": ");
Grade[k]=input1.nextInt();
k++;
}
}
}
Here's the output in the command prompt:
Enter the name of student 1:
Please enter the grade of student 1:
Please enter the name of student 2: Please enter the grade of student 2:
The problem is that line regarding the second student.
What did I do wrong in the code to get an output like that?
You need to identify name has input in next line with Name[k] = input1.nextLine();
int k, m, g;
String n;
//double g;
Scanner input1 = new Scanner(System.in);
String[] Name = new String[5];
double[] Grade = new double[Name.length];
k = 0;
while (k < Name.length) {
m = k + 1;
System.out.print("Enter the name of student " + m + ": ");
Name[k] = input1.nextLine();
System.out.print("");
System.out.print("Please enter the grade of student " + m + ": ");
Grade[k] = input1.nextDouble();
input1.nextLine();
k++;
}
EDITED: As per mentioned in Tom's comment under this answer when you have Name[k] = input1.nextLine(); instead of input1.nextLine(); program works correctly, but it messed up with value of array.
the nextInt of the Scannerdoes not read the "new line" character.
there are 2 ways to fix it.
1. call input1.nextLine(); after the input1.nextInt(); ignore what you get here, it is just to make it go to the next line.
Grade[k] = input1.nextInt();
input1.nextLine();
2. call input1.nextLine(); for the grade.
the String you get you can cast to int and save in Grade[k].
String str = input1.nextLine();
Grade[k] = Integer.parseInt(str);
This works:
public static void main(String[] args) throws IOException {
int k, m, g;
String n;
// double g;
Scanner input1 = new Scanner(System.in);
String[] Name = new String[5];
double[] Grade = new double[Name.length];
k = 0;
while (k < Name.length) {
m = k + 1;
System.out.print("Enter the name of student " + m + ": ");
Name[k] = input1.nextLine();
System.out.print("Please enter the grade of student " + m + ": ");
Grade[k] = input1.nextInt();
input1.nextLine();
k++;
}
}
I recommend you to please go through this question, you shall have your doubts clarified. Excerpt from the answer given in that post:
Scanner#nextInt method does not read the last newline character of your input, and thus that newline is consumed in the next call to Scanner#nextLine.
The problem is that: Grade[k] = input1.nextInt(); don't reads the end of line or anything after the number.
Try placing a input1.nextLine(); after Grade[k]=input1.nextInt(); should solve the issue:
while (k<Name.length)
{
m=k+1;
System.out.print("Enter the name of student "+m+": ");
Name[k]=input1.nextLine();
System.out.print("");
System.out.print("Please enter the grade of student "+m+": ");
Grade[k]=input1.nextInt();
input1.nextLine();
k++;
}

Having trouble getting user input into array without getting errors

I am creating a roommate bill splitter program and do not know what I am doing wrong. It gets hung up after asking what the roommates names are. Output is below code.
package roomBillSplit;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Roommate Bill Splitter!\n");
//Get Residence Name from User
System.out.print("Please Enter Name of Place or Address: ");
String place = input.nextLine();
roommates(place);
bills(place);
input.close();
}
public static void roommates(String place) {
int numRoom, i;
Scanner input = new Scanner(System.in);
//Get # of Roommates at Residence
System.out.print("How Many Total People Reside at " + place + ": ");
numRoom = input.nextInt();
String[] roommates = new String[numRoom];
//ArrayList<String> roommates = new ArrayList<String>(5);
//Get Names of Roommates
for(i = 0; i < roommates.length; i++) {
System.out.print("What is Person Number " + (i + 1) + "'s Name: ");
if(input.hasNext()) {
roommates[i] = input.nextLine();
input.next();
}
}
for(i = 0; i < roommates.length; i++) {
System.out.println(roommates[i]);
}
input.close();
}
}
public static void bills(String place) {
int numBills, i;
Scanner input = new Scanner(System.in);
//Get # of Bills Split Between Roommates
System.out.print("What is the Total Number of Bills to be Split at " + place + ": ");
numBills = input.nextInt();
String[] bills = new String[numBills];
//Get Names of Bills
for(i = 0; i < bills.length; i++) {
System.out.print("Please List Bill Number " + (i + 1) + ": ");
if(input.hasNext()) {
bills[i] = input.nextLine();
input.next();
}
}
for(i = 0; i < bills.length; i++) {
System.out.println(bills[i]);
}
int amount[] = new int[numBills];
//Get Amount of Each Bill
for(i = 0; i < bills.length; i++) {
System.out.print("What is the Total Amount of the " + bills[i] + " Bill: $");
if(input.hasNextInt()) {
amount[i] = input.nextInt();
input.next();
}
}
input.close();
for(i = 0; i < amount.length; i++) {
System.out.print(bills[i]);
System.out.print("\t$");
System.out.println(amount[i]);
}
}
}
Output:
Welcome to Roommate Bill Splitter!
Please Enter Name of Place or Address: 1212 Main
How Many Total People Reside at 1212 Main: 2
What is Person Number 1's Name: a
What is Person Number 2's Name: b
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at roomBillSplit.Main.bills(Main.java:62)
at roomBillSplit.Main.main(Main.java:19)
What is the Total Number of Bills to be Split at 1212 Main:
Your program waiting for user input. If you press any key it will resume. This is because
You have extra input.next() in remove that line it will work.
//Get Names of Roommates
for(i = 0; i < roommates.length; i++){
System.out.print("What is Person Number " + (i + 1) + "'s Name: ");
if(input.hasNext()){
roommates[i] = input.nextLine();
input.next();
}
}
UPDATE:
You don't need to use input.hasNext() and input.next() because input.nextLine() will block for the user input.
When you close the Scanner at the end of your roommates method, you also close System.in, so you can't scan from it any more when you need it in your bills method, and that's why your new Scanner there doesn't work.
Pass the Scanner you create in your main method as an argument to your roommates and bills method, instead of having those methods create a new Scanner, and remove all of the input.close() statements except for the one in main.
Edited to add:
It will fix your other problem if you change how you are reading from the scanner inside of your loops to look like this:
...
roommates[i] = input.next();
input.nextLine();
...
bills[i] = input.next();
input.nextLine();
...
amount[i] = input.nextInt();
input.nextLine();
...

reading input with Scanner; output is printed twice [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I have following class
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = sc.nextInt();
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
I can't type song name nr 1 because it Always shows first two together.
Like this if I type 3:
How many songs do your CD contain?
3
Please enter song nr 1:
Please enter song nr 2:
Change
int songs = sc.nextInt();
to:
int songs = Integer.parseInt(sc.nextLine().trim());
and it will work fine.
You should not mix usages of nextInt with nextLine.
add sc.nextLine(); after int songs = sc.nextInt();
Once you enter a number and read it using a scanner ( as a number) using sc.nextInt();, the newline character will be present in the input stream which will be read when you do sc.nextLine(). So,to skip(over) it, you need call sc.nextLine() after sc.nextInt();
Add a sc.nextLine() after sc.nextInt() and your code works fine.
The reason is the end of line after you type the nomber of songs.
Either use nextInt or nextLine, I would opt for nextLine:
import java.util.Scanner;
public class Album{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("How many songs do your CD contain?");
int songs = Integer.parseInt(sc.nextLine()); // instead of nextInt()
String[] songNames = new String[songs];
for (int i = 0; i < songs; i++) {
System.out.println("Please enter song nr " + (i+1) + ": ");
songNames[i] = sc.nextLine();
// What is wrong here? (See result for this line of code)
// It is working when I use "sc.next();"
// but then I can't type a song with 2 or more words.
// Takes every word for a new song name.
}
System.out.println();
System.out.println("Your CD contains:");
System.out.println("=================");
System.out.println();
for (int i = 0; i < songNames.length; i++) {
System.out.println("Song nr " + (i+1) + ": " + songNames[i]);
}
}
}
put a sc.nextLine(); after int songs = sc.nextInt();

JAVA beginner help needed string input in a loop

im a beginner in Java, and i have a problem to do:
the problem prompts the user 5 times to enter, the Name of a stock then the Share Price then the number of shares owned and we should calculate the sum of all the stock values, i wrote it using only two prompts using a loop, but my issue is that, in the second prompt time the loop Skips the String input for the second Name of stock instead of promting...bellow is the code:
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sharePrice =0,stockPrice = 0, temp = 0 ;
int i = 0;
double sum=0;
String name;
while (i < 2) {
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
stockPrice = sharePrice * (double)(numberOfshares);
sum += stockPrice;
i++;
}
System.out.println("the total stockprice owned is: " + sum );
}
}
And this is the output i get:
Enter the Name of the Stock
nestle
Enter the Share price
2
Enter the number of owned shares
4
Enter the Name of the Stock
Enter the Share price
What makes the input skip during the second loop?
Again as per my comment the problem is that your code doesn't handle the End Of Line (EOL) token when calling nextInt() or nextDouble().
The solution is to use input.nextLine() after getting your int and double in order to swallow the EOL token:
sharePrice = input.nextDouble();
input.nextLine(); // add this
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
input.nextLine(); // add this
stockPrice = sharePrice * (double)(numberOfshares);
The problem is that the last time you call
int numberOfshares = input.nextInt();
in the first iteration of the loop your first passes a carriage return as the next stock name. You could instead use:
double sharePrice = Double.parseDouble(input.nextLine());
and
int numberOfshares = Integer.parseInt(input.nextLine());
You should readout the newline characters after reading the share price and number of shares:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double sharePrice = 0, stockPrice = 0;
int i = 0;
double sum = 0;
String name;
while (i < 2)
{
System.out.println("Enter the Name of the Stock ");
name = input.nextLine();
System.out.println("Enter the Share price ");
sharePrice = input.nextDouble();
// Read out the newline character after the share price.
input.nextLine();
System.out.println("Enter the number of owned shares");
int numberOfshares = input.nextInt();
// Read out the newline character after the number of shares.
input.nextLine();
stockPrice = sharePrice * (double) (numberOfshares);
sum += stockPrice;
System.out.println(String.format("Name: %s, Price: %f, Shares: %d, Total: %f",
name,
sharePrice,
numberOfshares,
stockPrice));
i++;
}
System.out.println("the total stockprice owned is: " + sum);
}
See the lines with comments above:

Categories

Resources