How to work around java workspace and change to double - java

so I have to write a program that asks the user to enter in the number of students, then asks to input name of first student and then asks the grade of the student, then it goes on to the next student. For example it asks how many students and I say 5, then it asks me the name of the first student, and I say bob smith, then it asks me the grade, so I say 12.5, then it asks me the next students name and so on till I finish all five students. It then sorts everyone in descending order by their grade. I have it working, but there are two problems. 1.I cant put in a first and last name because of the white space. It works fine if I put in bob but not when I put bob smith. 2. I cant get it to read in double variables for the grade, only int. so 5 works but not 5.3.Here is my code:
import java.util.*;
public class assignment5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numofstudents = input.nextInt();
String[] names = new String[numofstudents];
int[] array = new int[numofstudents];
for(int i = 0; i < numofstudents; i++) {
System.out.print("Enter the student's name: ");
names[i] = input.next();
System.out.print("Enter the student's score: ");
array[i] = input.nextInt();
}
selectionSort(names, array);
System.out.println(Arrays.toString(names));
}
public static void selectionSort(String[] names, int[] array) {
for(int i = array.length - 1; i >= 1; i--) {
String temp;
int currentMax = array[0];
int currentMaxIndex = 0;
for(int j = 1; j <= i; j++) {
if (currentMax > array[j]) {
currentMax = array[j];
currentMaxIndex = j;
}
}
if (currentMaxIndex != i) {
temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
array[currentMaxIndex] = array[i];
array[i] = currentMax;
}
}
}
}

Use Scanner.nextDouble() instead of nextInt().

For your name problem set the delimiter to end of line
input.useDelimiter("\\n");
And for the grades issue you need to make array variable an array of floats or doubles and then use input.nextFloat() or input.nextDouble().
See: http://ideone.com/Qz7hD8

Related

Array shows indexs out of exceptions,but dont know where?

import java.util.Scanner;
public class Question1 {
public static void main(String[] args){
System.out.println(" Welcome to Shopping");
System.out.println("Please enter your shopping (item$price and seperate by comma): ");
Scanner scanner = new Scanner(System.in);
String list = scanner.next();
//here is my code
System.out.println("Here is the list of items:");
int p = 0;
int count = 0;
for(int i = 0; i < list.length(); i++) {
if(list.charAt(i) == ',')
count++;
}
int[] price = new int[count];
String[] temp = list.split("\\,");
for(int i=0;i<=count;i++){
int a = i+1;
**price[i] = Integer.parseInt(temp[i].substring(temp[i].indexOf("$")+1,temp[i].length()));**
p+=price[i];
System.out.println("No."+a+" "+temp[i].substring(0,temp[i].indexOf("$")));
}
System.out.println("The total price is: $"+p+".");
System.out.println("Thank you for using this program!!");
}
}
}
//I dont know why it couldnt print out,and shows something like arrary
out of ...
I try to print out something like Type nameoftheitem$price,nextone.It
will looks like
mango$12,
tomato$14,
print out like
1.mango
2.tomato
at the end,print out its sum cost 26
It works with changing the i to 1 for the first for loop ,and it works well accompanying with setting i<count

#Help. Java code, getting the marks of 5 students and displaying the students who got A using Arrays method

I have a problem. I am tasked to write a Java program, using the array method, that receives the marks of 5 students, and then finds and displays the number of students getting A grade. The marks are (60,56,78,99,92.5). The criteria needed to get grade A is 80 marks and above.
Everything in my code went well, except for the last statement:
System.out.println("The number of students "+count);
This is my code:
import javax.swing.JOptionPane;
public class Q2 {
public static void main(String [] args) {
double[] marks = new double[6];
int numbers = 1;
// This is for asking input
for (int i = 0; i < marks.length; i++,numbers++) {
String marksString = JOptionPane.showInputDialog (null,
"Enter the marks for student "+numbers+": ");
marks[i] = Double.parseDouble(marksString);
int count = 0;
if(marks[i] >= 80.0) {
count++;
}
}
System.out.println("The number of students "+count);
}
}
Everything in my code went well, except for the last statement:
System.out.println("The number of students "+count);
I received an error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - Erroneous tree type:
Is there anyone who can explain and correct my mistakes? :D
You wrongly declared count inside the for loop. As a result, it is not accessible outside the loop (hence the compilation error), and in addition, it's overwritten to 0 in each iteration of the loop, which means it will always have a value of 0 or 1 (before exiting the loop), instead of the correct count.
Move it outside the loop:
double[] marks = new double[6];
int numbers = 1;
int count = 0;
// This is for asking input
for (int i = 0; i < marks.length; i++,numbers++) {
String marksString = JOptionPane.showInputDialog (null,
"Enter the marks for student "+numbers+": ");
marks[i] = Double.parseDouble(marksString);
if(marks[i] >= 80.0) {
count++;
}
}
System.out.println("The number of students who got A is " + count);
public class Q2 {
public static void main(String [] args) {
double[] marks = new double[6];
int numbers = 1;
int count = 0;
// This is for asking input
for (int i = 0; i < marks.length; i++,numbers++) {
String marksString = JOptionPane.showInputDialog (null,
"Enter the marks for student "+numbers+": ");
marks[i] = Double.parseDouble(marksString);
if(marks[i] >= 80.0) {
count++;
}
}
System.out.println("The number of students "+count);
}
}
Your mistake is that you initialize the count inside the loop, and over each iteration, the compiler assigns the value 0 to your count. Put it above the loop.
You have declared and initialized the count variable inside the loop.As a result you will unable to get access to the count variable outside that for loop.And each time when the loop goes on count variable will assign to 0.Those are the two errors that you have been done.
import javax.swing.JOptionPane;
public class Demo {
public static void main(String [] args) {
double[] marks = new double[6];
int numbers = 1;
int count=0;
// This is for asking input
for (int i = 0; i < marks.length; i++,numbers++) {
String marksString = JOptionPane.showInputDialog (null,
"Enter the marks for student "+numbers+": ");
marks[i] = Double.parseDouble(marksString);
//int count = 0;
if(marks[i] >= 80.0) {
count++;
}
}
System.out.println("The number of students "+count);
}
}
You should declare the count variable outside the for loop.

Java using a while loop to load user input into an array

I was wondering how to load up an array (with user input) using a while loop. The code below prints a 0.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0;
int n = 0;
int[] myArray = new int[10];
System.out.printf("enter a value>>");
while (scan.nextInt() > 0) {
for (i = 0; i > 0; i++) {
myArray[i] = scan.nextInt();
}
System.out.printf("enter a value>>");
}
System.out.printf("array index 2 is %d", myArray[2]);
}
There are multiple things wrong with your code:
First of all
while(scan.nextInt() > 0){
Scanner.nextInt() returns an int from your standard input so you actually have to pick up that value. You are checking here what the user typed but then not using it at all and storing the next thing that the user types by saying:
myArray[i] = scan.nextInt();
You don't really need the outer while loop, just use the for loop, its enough.
However, your for loop is off as well:
for(i = 0; i > 0; i++){
It starts at i equal to 0 and runs while i is greater than 0. This means it will never actually run the code within the loop because 0 is never greater than 0. And if it did run (you started it at some number < 0), you would end up in an infinite loop because your condition i > 0 is always true for positive numbers.
Change the loop to:
for(i = 0; i < 10; i++){
Now, your loop could look like:
for(i = 0; i < 10; i++){ // do this 10 times
System.out.printf("enter a value>>"); // print a statement to the screen
myArray[i] = scan.nextInt(); // read an integer from the user and store it into the array
}
one other way to do it
Scanner scan = new Scanner(System.in);
List list = new ArrayList();
while(true){
System.out.println("Enter a value to store in list");
list.add(scan.nextInt());
System.out.println("Enter more value y to continue or enter n to exit");
Scanner s = new Scanner(System.in);
String ans = s.nextLine();
if(ans.equals("n"))
break;
}
System.out.println(list);
public static void main(String[] args)
{
Scanner input =new Scanner(System.in);
int[] arr=new int[4];
int i;
for(i=0;i<4;i++)
{
System.out.println("Enter the number: ");
arr[i]=input.nextInt();
}
for(i=0;i<4;i++)
{
System.out.println(arr[i]);
}
}
Hope this code helps.

Handling out of bounds on a fixed array

My problem is that for example there's only three passing grades, the user entered then the size of passGrade array would only be three, same with failGrade: if the user entered two failing grades then the size of failGrade array would only be two, in short I want the two arrays to be of fixed lengths. In my program it goes out of bounds.
Here's the piece of code I'm referring to:
Scanner input=new Scanner(System.in);
int gradeSize=0;
int fixedPassed=0;
int fixedFail=0;
int grades[]=new int[gradeSize];
int passGrade[]=new int[fixedPassed];
int failGrade[]=new int[fixedFail];
System.out.print("Enter Grade Size: ");
gradeSize=input.nextInt();
System.out.println();
System.out.print("Enter Grades: ");
for(int i=0; i<gradeSize; i++)
{
grades[i]=input.nextInt();
while(grades[i]<1 || grades[i]>100)
{
grades[i]=input.nextInt();
}
if(grades[i]>=75)
{
fixedPassed++;
passGrade[i]=grades[i];
}
else if(grades[i]<75)
{
fixedFail++;
failGrade[i]=grades[i];
}
}
for(int i=0; i<fixedPassed; i++)
{
System.out.print(passGrade[i]+" ");
}
for(int i=0; i<fixedFail; i++)
{
System.out.print(failGrade[i]+" ");
}
Java arrays are fixed size. So you need to get the input, then count the pass/fails. Then create your pass fail arrays and then copy the grades into them. You could do something like this,
System.out.print("Enter Grade Size: ");
int gradeSize = input.nextInt();
int passCount = 0;
int grades[]=new int[gradeSize];
System.out.println();
System.out.print("Enter Grades: ");
for (int i = 0; i < gradeSize; i++) {
grades[i] = input.nextInt();
if(grades[i] >= 75) {
passCount++;
}
}
int passGrade[] = new int[passCount];
int failGrade[] = new int[grades.length - passCount];
int failCount = passCount = 0;
for (int grade : grades) {
if (grade >= 75) {
passGrade[passCount++] = grade;
} else {
failGrade[failCount++] = grade;
}
}
System.out.println("Passing Grades: " + Arrays.toString(passGrade));
System.out.println("Failing Grades: " + Arrays.toString(failGrade));
Since you don't know in advance the length of the input, and you don't know in advance how many passed and how many failed, you can't create the arrays before first processing the input.
You should use 3 collections (HashSet, ArrayList, etc ...) to store the input grades, passed grades and failed grades. Once you are done, you can initialize your 3 arrays based on the size() of the collections, and then iterate over the collections to copy their contents to the arrays.

need scanner input for array

does anyone know how to set a user input for an array, I cant find the command anywhere. my array 'grades' have 20 locations. im not so sure about 'grades.length' function but I think it prompts 20 times. BUT I added a while statement to override BUT ITS TOTALLY IGNORING THE FOR STATEMENT. if I could set user input for array I could get rid of the while statement...
program has to accept grade for number of students the user inputs btw..
import java.util.Scanner;
public class gradesaverage {
public static void main(String[] args) {
int [] grades = new int [20];
int i;
int numStudents;
System.out.print("Enter number of students: ");
Scanner scanint = new Scanner (System.in);
numStudents = scanint.nextInt();
for ( i = 1; i <= grades.length; ++i)
{
System.out.println("Enter grade: ");
grades[i] = scanint.nextInt();
}
while(i <= numStudents );
}
}
Not sure what you mean, but assuming all input is correct,
int [] grades = new int [numStudents ];
Should work if you move this line after declaration and assignment of numStudents. There is no problem in java with variable length arrays.
Also note - your iterator i starts from 1, while in java arrays start from 0.
public static void main(String[] args) {
int i;
int numStudents;
System.out.print("Enter number of students: ");
Scanner scanint = new Scanner (System.in);
numStudents = scanint.nextInt();
int [] grades = new int [numStudents]; //the size we wanted
for ( i = 0; i < grades.length; ++i) //starting from 0, not 1.
{
System.out.println("Enter grade: ");
grades[i] = scanint.nextInt();
}
//print the array - for checking out everyting is ok
System.out.println(Arrays.toString(grades));
}

Categories

Resources