Adding the code for ascending order of user input - java

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));

Related

Java exception error for input string

I am a beginner in Java programming. I am trying to write a simple program to take size of input followed by list of numbers separated by spaces to compute the sum.
The first input is getting in fine for the second one system shows error as it is trying to parse a blank string into integer. Can you please help with the mistake I am making?
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(" Enter size of input ");
int num = scan.nextInt();
System.out.println("Enter data separated by spaces: ");
String line = scan.nextLine();
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}
The reason you get an exception in your code is because int num = scan.nextInt(); does not process the newline character after the number.
So when the statement String line = scan.nextLine(); is used, it processes the newline character and hence you get an empty string ""
You can either fetch the entire line and parse it to Integer, like this:
int num = Integer.parseInt(scan.nextLine());
or you can go with using nextInt() and then use a blank scan.nextLine() to process the new line after the number, like this:
int num = scan.nextInt();
scan.nextLine();
Your Program has only one error that you were making only one scan object of scanner class, you have to make two scanner class object one will help in getting array size while another will help in getting array element.
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scan1 = new Scanner(System.in); // change 1
System.out.print(" Enter size of input ");
int num = scan.nextInt();`enter code here`
System.out.println("Enter data separated by spaces: ");
String line = scan1.nextLine();// change 2
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}

How can I print out the int values from the array?

The code below shows my progress, but I cannot print the numbers that were entered. I don't know where to put println("you entered the following numbers") in the loop so that it'll show up when the loop stops.
import java.util.Scanner;
public class aufgabe5 {
public static void main(String[] args) {
int x;
Scanner input = new Scanner(System.in);
System.out.println("How much numbers do you want to enter?");
x = input.nextInt();
int j = 1;
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[x];
for (int i = 0; i < numbers.length; i++) {
System.out.println("Enter the " + j++ + ". number:");
numbers[i] = scanner.nextInt();
}
System.out.println("You entered following numbers");
System.out.println(x);
}
}
Change x like
System.out.println(x);
to Arrays.toString(int[]) like
System.out.println(Arrays.toString(numbers));
Edit
To print the array reversed,
String str = Arrays.toString(numbers).replace(", ", " ,");
str = str.substring(1, str.length() - 1);
System.out.println(new StringBuilder(str).reverse().insert(0, "[")
.append("]"));
Intialize the String before the loop, then keep adding the values to it.
After the loop finishes you can print the whole thing.
String someVar="You entered following numbers: ";
for(int 1=0;i<array.length;i++)
{
someVar=someVar+numbers[i]+",";
}
System.out.println(someVar);

Java - summing up Array list values

I am building an array that ask how many different inputs you have, then allowing you to enter each input. At the end I want to sum them up, but I keep getting an error.
Also when I go above 5 inputs, I lose one..... For example when I respond to the first question: Enter "10". When I start adding different numbers in it stops at nine. Please help.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int[] numArr = new int[size];
System.out.println("Enter the number of CUs for each course: ");
for (int i=0; i<numArr.length; i++)
{
numArr[i] = input.nextInt();
}
int totalSum = numArr + totalSum;
System.out.print("The sum of the numbers is: " + totalSum);
Change your logic and code to the following:
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
System.out.println("Enter the number of CUs for each course: ");
int totalSum = 0;
for (int i = 0; i < size; i++) {
totalSum+=input.nextInt();
}
System.out.print("The sum of the numbers is: " + totalSum);
try
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int totalSum = 0;
for (int i=0; i< size; i++)
{
System.out.println("Enter the number of CUs for each course: ");
int cuNum = input.nextInt();
totalSum += cuNum ;
}
System.out.print("The sum of the numbers is: " + totalSum);
Pretty sure your intended result is
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of courses you have left: ");
int size = input.nextInt();
int[] numArr = new int[size];
int totalSum = 0;
System.out.println("Enter the number of CUs for each course: ");
for (int i=0; i<numArr.length; i++)
{
numArr[i] = input.nextInt();
totalSum += numArr[i];
}
System.out.print("The sum of the numbers is: " + totalSum);
}
Your other code didn't work mainly because of
int totalSum = numArr + totalSum;
You can't define totalSum to defines itself! And you can't just use numArr... numArr is an array - you have to access indexes, not the array as a whole!

Lost first element in array? [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
Yes this is an assignment...
I've got 2 arrays; one for student names and one for their scores. I've asked the user to input the number of students to initialize the sizes of both, and then loop through the input process to fill the elements.
But the weirdest thing happens that hasn't happened before. It seems that the student array is cut short by one element when the code is run (after 4 entries the program jumps to the next input loop), but even weirder is that the truncation seems to be at the front of the array, because the scores loop starts with a blank where a name should be but allows for 5 inputs.
import java.util.Scanner;
public class Ex6_17SortStudents {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numOfStu;
String[] students;
double[] scores;
System.out.println("Enter the number of students being recorded: ");
numOfStu = input.nextInt();
students = new String[numOfStu];
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++)
students[i] = input.nextLine();
scores = new double[numOfStu];
for (int i = 0; i < students.length; i++) {
System.out.print("Enter score for " + students[i] + ": ");
scores[i] = input.nextDouble();
}
}
}
Any ideas why this happens?
There's eventually a sort but that's a mess i think i have a handle on.
Sorry if the format for the post is wrong -- first time posting; trying my best.
thanks
This debugging output should give you a clue to your problem:
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++) {
System.out.print("Name index " + i + ": ");
students[i] = input.nextLine();
}
And this answer to this question is exactly the answer you need.
Use students[i] = input.next();
Just checked it, and it works now.
nextLine() advances your scanner past the current line and returns the input that was skipped -- so you were pretty much skipping a line. The first time it enters the loop, you lose an i value, that is i is now 1, yet your scanner does not record user input. The second time around, when i is 1, it takes input, and so forth.
New code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numOfStu;
String[] students;
double[] scores;
System.out.println("Enter the number of students being recorded: ");
numOfStu = input.nextInt();
students = new String[numOfStu];
scores = new double[numOfStu];
System.out.println("Enter students' names: ");
for (int i = 0; i < students.length; i++) {
students[i] = input.next();
}
for (int i = 0; i < students.length; i++) {
System.out.print("Enter score for " + students[i] + ": ");
scores[i] = input.nextDouble();
}
}

java Program does not wait for the user input

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());

Categories

Resources