My Java program refuses to take a string input [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 4 years ago.
I have an array of strings - name[]. When I try to take an input from the user using the Scanner class the program seems to ignore the statement and go on to the next.
import java.util.Scanner;
class Student { //start of class
public static void main(String[] args) { //start of method main
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + totalmarks[i]; //calculating total marks
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++) {
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
} //end of method main
} //end of class

That's because the sc.nextInt() method does not read the newline character in your input and so you need to call sc.nextLine()
From the docs
Advances this scanner past the current line and returns the input that
was skipped.
This method returns the rest of the current line, excluding any line
separator at the end. The position is set to the beginning of the next
line.
Since this method continues to search through the input looking for
a line separator, it may buffer all of the input searching for the
line to skip if no line separators are present.
You code will now look like :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
sc.nextLine(); // <----- observe this
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
sc.nextLine(); // <----- observe this
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + totalmarks[i];
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++) {
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
}

Try this.. Your sc.nextLine() is reading empty String after you input integer value
import java.util.Scanner;
class Student
{//start of class
public static void main(String[] args)
{//start of method main
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
String emp = sc.nextLine();
String name[] = new String[n];
int totalmarks[] = new int[n];
for (int i=0;i<n;i++)
{
System.out.println("Student " + (i + 1));
System.out.print("Enter name: ");
name[i] = sc.nextLine();
System.out.print("Enter marks: ");
totalmarks[i] = sc.nextInt();
emp = sc.nextLine();
}
int sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + totalmarks[i];//calculating total marks
}
double average = (double) sum / n;
System.out.println("Average is " + average);
for (int i = 0; i < n; i++)
{
double deviation = totalmarks[i] - average;
System.out.println("Deviation of " + name[i] + " is " + deviation);
}
}//end of method main
}//end of class

Related

Error: incompatible types: possible lossy conversion from double to int. Problem with code for a java course i'm doing

I have this task for my Java course but keep getting this error and don't know where i've gone wrong.
Here is the code:
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double[] values = new double[4];
for (double i = 0; i < values.length; i++) {
System.out.print("Enter a number: ");
values[i] = sc.nextInt();
}
double sum = (values[0] + values[1] + values[2] + values[3]);
System.out.println("The sum is " + sum + ".");
sc.close();
}
}
for (double i = 0; i < values.length; i++) {
Why should i be a double here?
This causes problems when you later use i as an index to an array, which converts it to an int and causes the error.
Just make i an int
for(int i = 0; i < values.length; i++) {
About the exception you mention in the comments
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at ArraySum.main(ArraySum.java:12)
that's because you're using nextInt instead of nextDouble, so when you enter a value with a decimal separator, Scanner throws an error because it can't interpret the input as an integer.
Here's the full working code
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double[] values = new double[4];
for (int i = 0; i < values.length; i++) {
System.out.print("Enter a number: ");
values[i] = sc.nextDouble();
}
double sum = (values[0] + values[1] + values[2] + values[3]);
System.out.println("The sum is " + sum + ".");
sc.close();
}
}

How to calculate sum of elements of an array

I have this code where I'm able to calculate the average of marks but unable to calculate the sum and percentage.
And I want to print the name of the student under student name but I'm getting only the student number.
I tried understand more about these, but was unable to get through.
Could you please help me out?
package cube;
import java.io.*;
import java.util.Scanner;
public class ReportCard {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int DB[][], nos = 0;
String arrayOfNames[] = new String[nos];
String S = "";
Scanner s = new Scanner(System.in);
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
DB = new int[nos + 1][6];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter " + arrayOfNames[i] + "'s English Score : ");
DB[i][0] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Science Score : ");
DB[i][1] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Maths Score : ");
DB[i][2] = Integer.parseInt(br.readLine());
DB[i][3] = (int) (DB[i][0] + DB[i][1] + DB[i][2] / 3); //calculating the Average Marks of Each Student
DB[i][4] = (int) (DB[i][0] + DB[i][1] + DB[i][2]);
}
}
void PrintReport() {
System.out.println("\nGenerated Report Card :\n\nStudent Name. English Science Maths Average Total\n");
for (int i = 0; i < nos; i++) {
Padd("Student Name. ", (i + 1));
Padd("English ", DB[i][0]);
Padd("Science ", DB[i][1]);
Padd("Maths ", DB[i][2]);
Padd("Average", DB[i][3]);
Padd("Total", DB[i][4]);
System.out.println(S);
S = "";
}
}
void Padd(String S, int n) {
int N = n, Pad = 0, size = S.length();
while (n != 0) {
n /= 10;
Pad++;
}
System.out.print(" " + N);
for (int i = 0; i < size - Pad - 5; i++)
System.out.print(" ");
}
public static void main(String args[]) throws Exception {
ReportCard obj = new ReportCard();
obj.Input();
obj.PrintReport();
}
}
You are initializing your arrayOfNames array to a length of zero always. You should be initializing it once you get the value of the variable nos ( similar to your initialization of 2d array DB)
You are creating the array of names, i.e, arrayOfNames as an array of length 0 because nos is initially zero.
Observe this:
int DB[][],nos=0; //nos is initialized to 0
String arrayOfNames[] = new String[nos]; //arrayOfNames is of size = nos,which is in turn equal to 0, hence arrayOfNames is basically an array which can't hold anything.
instead do this: just declare arrayOfNames and don't initialize it. ==> String arrayOfNames[];
define the string size after you accept the size, i.e, nos. So it should be as follows:
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
arrayOfNames[] = new String[nos]; //now define the size
...
This would ensure that the string is accessible outside the Input() function as well as is defined with a valid size.
Following corrections can make your code run..
package testProgram;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ReportCard {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int DB[][], nos = 0;
//here initaialise reference will null
String arrayOfNames[] = null;
String S = "";
Scanner s = new Scanner(System.in);
void Input() throws Exception {
System.out.print("Enter The Number Of Students : ");
nos = Integer.parseInt(br.readLine());
DB = new int[nos + 1][6];
//create string array object here
arrayOfNames = new String[nos];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter the name of student:");
arrayOfNames[i] = s.nextLine();
System.out.print("\nEnter " + arrayOfNames[i] + "'s English Score : ");
DB[i][0] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Science Score : ");
DB[i][1] = Integer.parseInt(br.readLine());
System.out.print("Enter " + arrayOfNames[i] + "'s Maths Score : ");
DB[i][2] = Integer.parseInt(br.readLine());
//take extra variable that holds total, it increases the readability of the code
int total = DB[i][0] + DB[i][1] + DB[i][2];
DB[i][3] = (total) / 3; //calculating the Average Marks of Each Student
DB[i][4] = total;
}
}
void PrintReport() {
System.out.println("\nGenerated Report Card :\n\nStudent Name. English Science Maths Average Total\n");
for (int i = 0; i < nos; i++) {
Padd("Student Name. ", (i + 1));
Padd("English ", DB[i][0]);
Padd("Science ", DB[i][1]);
Padd("Maths ", DB[i][2]);
Padd("Average", DB[i][3]);
Padd("Total", DB[i][4]);
System.out.println(S);
S = "";
}
}
void Padd(String S, int n) {
int N = n, Pad = 0, size = S.length();
while (n != 0) {
n /= 10;
Pad++;
}
System.out.print(" " + N);
for (int i = 0; i < size - Pad - 5; i++)
System.out.print(" ");
}
public static void main(String args[]) throws Exception {
ReportCard obj = new ReportCard();
obj.Input();
obj.PrintReport();
}
}
Arrays are not dynamic. either you declare its size before hand or you use Arraylist..
boolean loopNaming = true;
int i = 0;
//you are creating array of zero size, use ArrayList instead
// String[] name = new String[i];
ArrayList<String> nameList = new ArrayList<>();
while (loopNaming == true) {
System.out.printf("Enter name of student or done to finish: ");
String name = keyboard.nextLine();
//check if name is 'done'
if (name.equals("done")) {
loopNaming = false;
} else {
nameList.add(name);
System.out.println("Enter score: ");
score = keyboard.nextDouble();
//nextLine positions cursor to next line
keyboard.nextLine();
}
i = i + 1;
}
System.out.println(nameList);

Java Simple program using Loop structure [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
Sample input : 3456
Sample output :
Digits : 3, 4, 5, 6
Sum : 18
This is the code that I had try, but unfortunately it is wrong since i do not use loop.Please anybody can help me?
import java.util.Scanner;
public class Lab1_5 {
public static void main (String args[])
{
int insert1, insert2, insert3, insert4;
int sum ;
Scanner console = new Scanner(System.in);
System.out.print("Please enter First Number: ");
insert1 =console.nextInt();
System.out.print("Please enter Second Number: ");
insert2 =console.nextInt();
System.out.print("Please enter Third Number: ");
insert3 =console.nextInt();
System.out.print("Please enter Fourth Number: ");
insert4 =console.nextInt();
System.out.println("Digits: "+ insert1+","+insert2+","+insert3+","+insert4);
sum = insert1+insert2+insert3+insert4;
System.out.print("Sum: "+ sum);
}
}
You can use a for loop as seen in this example:
public static void main(String args[]){
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Number: ");
//get number input:
int num = sc.nextInt();
//convert number to String:
String str = Integer.toString(num);
//iterate through each char in string:
for(int i = 0; i < str.length(); i++){
//convert char value to int, and add it to the sum:
sum += Character.getNumericValue(str.charAt(i));
}
}
Here's how you can get the sum with a loop:
What this does is it gets one number from the user and loops trough the individual digits of the number.
public static void main(String[] args)
{
int sum = 0;
Scanner console = new Scanner(System.in);
System.out.print("Please enter a Number: ");
String num = console.nextLine();
try
{
num = num.trim();
int index = 0;
int n = Integer.parseInt(num);
System.out.print("Digits: ");
while (n > 0)
{
int digit = n % 10;
sum += n % 10;
n = n /10;
char d = num.charAt(index++);
System.out.print(d + ", ");
}
System.out.print("Sum: " + sum);
}
catch (NumberFormatException e)
{
System.out.print("Invalid Number entered");
}
// Close the scanner
console.close();
}
Here is another version that won't give you an integer overflow for input values over Integer.MAX_VALUE.
public static void main(String[] args)
{
int sum = 0;
Scanner console = new Scanner(System.in);
System.out.print("Please enter a Number: ");
String num = console.nextLine();
try
{
num = num.trim();
System.out.print("Digits: ");
for (int i = 0; i < num.length(); i++)
{
char d = num.charAt(i);
int n = Integer.parseInt(String.valueOf(d));
sum += n;
System.out.print(d + ", ");
}
System.out.print("Sum: " + sum);
}
catch (NumberFormatException e)
{
System.out.print("Invalid Number entered");
}
console.close();
}
public class Lab1_5 {
public static void main (String args[])
{
int insert;
int sum ;
int[] numArray = new int[4];
Scanner console = new Scanner(System.in);
for(int i=0; int<4; i++){
if(i == 1) {
System.out.println("Please enter First Number: ");
} else {
System.out.println("Please enter the next Number: ");
}
numArray[i] = console.nextInt();
sum += numArray[i];
}
System.out.println("Digits: "+ numArray[0]+","+numArray[1]+","+numArray[2]+","+numArray[3]);
System.out.println("Sum: "+ sum);
}
}

Ending a program with ctrl+Z

import java.util.Scanner;
public class ClassAverage
{
public static void main(String args[])
{
String names[] = new String[50];
int scores[] = new int[50];
int entries = 0;
Scanner in = new Scanner(System.in);
//System.out.println("Enter number of entries");
//int entry = in.nextInt();
System.out.println("Enter the names followed by scores of students: ");
for(int i = 0; i < 50; i++)
{
names[i] = in.next();
scores[i] = in.nextInt();
entries++;
}
Average avg = new Average();
double average = avg.CalcAvg(scores,entries);
System.out.println("The class average is: " + average);
avg.belowAvg(scores,average,names,entries);
avg.highestScore(scores,names, entries);
}
}
class Average
{
Average()
{
System.out.println("The averages: ");
}
double CalcAvg(int scores[], int entries)
{
double avg;
int total = 0;
for(int i = 0; i < entries; i++)
{
total += scores[i];
}
avg = total/entries;
return avg;
}
void belowAvg(int scores[],double average,String names[], int entries)
{
for(int i = 0; i < entries; i++)
{
if(scores[i] < average)
System.out.println(names[i] + "You're below class average");
}
}
void highestScore(int scores[],String names[], int entries)
{
int max = scores[1];
for(int i = 0; i < entries; i++)
{
if(scores[i]>=max)
max=scores[i];
}
System.out.println("The maximum score is: " + max);
System.out.println("The highest score acheivers list: ");
for(int i = 0; i < entries; i++)
{
if(scores[i] == max)
System.out.println(names[i]);
}
}
}
im suppose to hold the ctrlkey press z and then press the enter key to end the program but how do i do that?
if you are wondering the program is to write a program that lets the user input student names followed by their test scores and outputs the class average, names of students below the average, and the highest test score with the name of student
Ctrl-Z is the DOS command code for end of input (the UNIX equivalent is Ctrl-D). All command line programs should support this because it allows you to pipe output from one as input to the other. Kudos to your teacher!
When this key combo is pressed, Scanner.hasNextLine() will return false. Here's an example of a loop that reads line until you hit Ctrl-Z on Windows (or Ctrl-D on Linux/Unix):
while (in.hasNextLine()) {
System.out.println("You wrote " + in.nextLine());
}
You can listen for the control-z character in your scanner:
String nextLine = in.nextLine();
if(nextLine.length == 1 && nextLine.charAt(0) == KeyEvent.VK_Z)
// end program

Taking same output twice times

/*
* (Sort students) Write a program that prompts the user to enter the number of students,
*the students’ names, and their scores, and prints student names in decreasing
*order of their scores.
*/
package homework6_17;
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student: ");
names[i] = input.nextLine();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student: ");
scores[i] = input.nextDouble();
}
String temps = "";
double temp = 0;
double max = scores[0];
for(int i = 0; i<(scores.length-1); i++){
if(scores[i+1]>scores[i]){
temp=scores[i+1];
scores[i]=scores[i+1];
scores[i+1]=scores[i];
temps = names[i+1];
names[i]=names[i+1];
names[i+1]=names[i];
}
}
for(int i = 0 ; i<(scores.length-1); i++)
System.out.println(names[i]+ " " + scores[i]);
}
}
When i run this program;
run:
Enter number of students: 3
Enter the name of student:
Enter the name of student:
a
Enter the name of student:
b
Enter the score of student:
c
Exception in thread "main" java.util.InputMismatchException
// i got " Enter the name of student: " twice times instead of one.
The first thing that comes to mind (not sure if it is correct here) is that you type the number of students and press "enter". It reads the first int (the 3) and reads the "enter" as the first input for the first student.
Maybe try int numberOfStudents = Integer.ParseInt(input.nextLine());?
That way the newline wont be added to the students.
You just have to remove the first System.out.print("Enter number of students: "); as you are printing the phrase in your for loop for every student. Therefore you are printing it twice for the first student (one time before your loop and one time in your loop)
It's not a good idea to answer homework question in SO. But since you have tried some code, It's OK to answer the Q. Take a look:
import java.util.Scanner;
public class Homework6_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberOfStudents = input.nextInt();
String[] names = new String[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the name of student #" + (i + 1) + ":");
names[i] = input.next();
}
double[] scores = new double[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter the score of student " + names[i] + ":");
scores[i] = input.nextDouble();
}
String tempName;
double tempScore;
for (int i = 0; i < numberOfStudents; i++) {
for (int k = i + 1; k < numberOfStudents; k++) {
if (scores[k] > scores[i]) {
tempName = names[i];
tempScore = scores[i];
names[i] = names[k];
scores[i] = scores[k];
names[k] = tempName;
scores[k] = tempScore;
}
}
}
for (int i = 0; i < numberOfStudents; i++)
System.out.println(names[i] + " " + scores[i]);
}
}

Categories