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++;
}
Related
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));
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 6 years ago.
take a look at the following code:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();
String[] students = new String [numberOfStudents];
//input.nextLine();
for (int i = 0; i < students.length; i++){
System.out.println("Enter name for student " + (i+1) + ":" );
students[i] = input.nextLine();
}
for (int i = 0; i < students.length; i++){
System.out.println(students[i]);
}
}
}
You can see I commented out the statement "input.nextLine();" just before the first loop, and if I execute this code (this was my original code), the loop runs twice and then stops and waits for my input, then continues normally, so in order to fix this I need to put in that commented line and then it works normally, stops after every iteration and asks for input. Why is it like this, how exactly does Scanner work ?
Example output:
Without input.nextLine(); before the loop:
Enter the number of students: 4
Enter name for student 1:
Enter name for student 2:
name1 name2
Enter name for student 3:
name3
Enter name for student 4:
name4
And if I uncomment the input.nextLine(); the output is as follows:
Enter the number of students: 4
Enter name for student 1:
name1
Enter name for student 2:
name2
Enter name for student 3:
name3
Enter name for student 4:
name4
now it executes normally.
In the for loop, you need to replace input.nextLine(); with input.next(); as nextLine() method advances the scanner to next line and returns what was read whereas next() waits for next input. Below would work:
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();
String[] students = new String[numberOfStudents];
// input.nextLine();
for (int i = 0; i < students.length; i++) {
System.out.println("Enter name for student " + (i + 1) + ":");
students[i] = input.next();
}
for (int i = 0; i < students.length; i++) {
System.out.println(students[i]);
}
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();
...
When i put in the first input it prints the second and the third at the same time. Console:
Please enter the grade for course 1
A
Please enter the grade for course 2
Please enter the grade for course 3
Code:
import java.io.IOException;
public class MyGradeLoops {
public static void main(String[] args) throws IOException{
int grade;
for (int i=1; i<6; i++) {
System.out.println("Please enter the grade for course " + i);
grade = System.in.read();
}
System.out.println("Thank your for submitting your grades");
}
}
System.in.read(); will read the next byte from the user input. When you type a number and press Enter, it would count for at least three bytes (with the two additional bytes corresponding to \r and \n new line characters).
You can simply use a Scanner instance and read the integer using Scanner#nextInt().
Scanner in = new Scanner(System.in);
for (int i = 1; i < 6; i++) {
System.out.println("Please enter the grade for course " + i);
grade = in.nextInt();
}
If System.in.read() is a requirement and the grade is input as a string, here's a (sort of hacky) way to do it:
for (int i = 1; i < 6; i++) {
String grade = "";
System.out.println("Please enter the grade for course " + i);
char c;
while((c = (char) System.in.read()) != '\n') {
grade += c;
}
System.out.println(grade);
}
I need to create an array that prompts a professor to input how many students are in their class. Then prompts them to input their names until the number of students is met. What I have is clearly wrong but I was hoping for some insight.
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++)
{
System.out.println("Enter the name of student " + (i+1) + " in your class. ");
studentName[i] = console.nextLine();
System.out.println("Student name entered: " + studentName[i]);
}
EDIT: I changed the code a bit, mainly the array. With the for loop I am intending to simply have it go through each number and assign a student name to it. But with the last line of code it gives me an error saying its a confusing indentation.
EDIT 2: After proofreading my question and the code myself I've noticed very basic mistakes and have dealt with them, but one last question. Right now while the code works, when it asks for me to input the name, it skips student 1, leaves it blank then moves onto student 2. As shown in this screenshot http://puu.sh/8fl8e.png
you weren't far...
Scanner console = new Scanner (System.in);
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++){
System.out.println("Enter the name of student" + (i+1) + "in your class. ");
studentName[i] = console.next();
}
to test the code:
for (int i=0; i<studentName.length; i++){
System.out.println(studentName[i]);
}
EDIT: an answer for your second edit:
use
console.next();
instead of
console.nextLine();
I guess that studentName should be String, not double. And maybe you should consider taking advantage of fact that Java is OO? :)
since you are taking names as input which is string type but you are using double(not possible to store string) and you also missed bracket after for loop.
change
double [] studentName = new double [numberOfStudents];
to
String [] studentName = new String [numberOfStudents];
final correct code:
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String[numberOfStudents];
for (int i=0; i< numberOfStudents; i++){
System.out.println("Enter the name of student" + (i+1) + "in your class. ");
studentName[i] = console.nextLine();
}
System.out.println("Please enter the number of students in the class: ");
int numberOfStudents = console.nextInt();
String [] studentName = new String [numberOfStudents];
for (int i=0; i<studentName.length; i++)
{
System.out.println("Enter the name of student " + (i+1) + " in your class. ");
studentName[i] = console.nextLine();
System.out.println("Student name entered: " + studentName[i]);
}