This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 months ago.
i am very new to programming. I am implementing FirstComeFirstServe(FCFS) Scheduling. I am getting array index out of bound exception while entering first input in ArrivalTime array. It can be a silly mistake, but I cannot figure it out,
Please help me, Thank You for your time.
import java.util.Scanner;
public class FCFS_Practice {
public static Scanner scanner = new Scanner(System.in);
static int numberOfProcess;
int[]ProcessID = new int[numberOfProcess];
int[]ArrivalTime = new int[numberOfProcess];
int[]BurstTime = new int[numberOfProcess];
int[]CompletionTime = new int[numberOfProcess];
int[]TurnAroundTime = new int[numberOfProcess];
int[]WaitingTime = new int[numberOfProcess];
float avgWaitingTime,avgTurnAroundTime;
public void takeInput(){
System.out.println("Enter the number of process: ");
numberOfProcess = scanner.nextInt();
}
public void inputArrivalAndBurstTime(){
for(int i = 0;i < numberOfProcess;i++){
System.out.printf("Enter Arrival Time for Process %d: ",i+1);
ArrivalTime[i] = scanner.nextInt();
scanner.nextLine(); // Buffer Flush
System.out.printf("Enter Burst Time for Process %d: ",i+1);
BurstTime[i] = scanner.nextInt();
scanner.nextLine(); // buffer flush
ProcessID[i] = i+1;
}
}
public void calculateCompletionTime(){
for(int i = 0 ; i < numberOfProcess ; i++){
if(i==0){
CompletionTime[0]=BurstTime[0];
} else if (ArrivalTime[i]<CompletionTime[i-1]) {
CompletionTime[i]=CompletionTime[i-1]+BurstTime[i];
} else {
CompletionTime[i]=ArrivalTime[i]+BurstTime[i];
}
}
}
public void calculateTurnAroundAndWaitingTime(){
for(int i = 0 ; i < numberOfProcess ; i++){
TurnAroundTime[i]=CompletionTime[i]+ArrivalTime[i];
WaitingTime[i]=TurnAroundTime[i]-BurstTime[i];
}
}
public void getAvgWaitingTimeAndAvgTurnAroundTime(){
for(int i = 0 ; i<numberOfProcess;i++){
avgTurnAroundTime+=TurnAroundTime[i];
avgWaitingTime+=WaitingTime[i];
}
avgWaitingTime = avgWaitingTime/numberOfProcess;
avgTurnAroundTime = avgTurnAroundTime/numberOfProcess;
}
public void getTable(){
System.out.println("ProcessNo. ArrivalTime BurstTime CompletionTime TurnAroundTime WaitingTime");
for(int i = 0 ; i < numberOfProcess ; i++){
System.out.println(ProcessID[i]+"\t\t"+ArrivalTime[i]+"\t\t"+BurstTime[i]+"\t\t"+CompletionTime[i]+"\t\t\t"+TurnAroundTime[i]+"\t\t\t"+WaitingTime[i]);
}
scanner.close();
}
}
OutPut
The problem with your code is that you initialize arrays of int (ProcessID..) with the static int numberOfProcess - which initialized by default as 0.
You update it from Scanner at takeInput method but length of the arrays have been already initialized as 0 length.
You have to work with the initialization process to set initial arrays values only after you get your numberOfProcesses variable value from Scanner. You can read more about default initialization at Java Official Documentation.
As fast workaround for learning purpose just change default value. But remember that error returns if numberOfProcess will be higher, so to modify code is mandatory for solid code practice and passing of automation tests.
static int numberOfProcess = 10;
As more solid (but not a very nice one solution) initialize your arrays only after you know the correct value of numberOfProcess variable:
int numberOfProcess;
int[]ProcessID;
int[]ArrivalTime;
int[]BurstTime;
int[]CompletionTime;
int[]TurnAroundTime;
int[]WaitingTime;
public void takeInput(){
System.out.println("Enter the number of process: ");
numberOfProcess = scanner.nextInt();
ProcessID = new int[numberOfProcess];
ArrivalTime = new int[numberOfProcess];
BurstTime = new int[numberOfProcess];
CompletionTime = new int[numberOfProcess];
TurnAroundTime = new int[numberOfProcess];
WaitingTime = new int[numberOfProcess];
}
If you use ArrayList instead of []int you don't need to set array length. However, you have also to learn deep the difference between ArrayList (resizable array) and array - there are tasks where array is preferable.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 months ago.
I am very new to programming and to stackOverflow. I am implementing First Come First Serve(FCFS).But I am getting array index out of bound exception, while entering input in []ArrivalTime I can be a silly mistake but i can not figure out why ,Please help me
import java.util.Scanner;
public class FCFS_Practice {
public static Scanner scanner = new Scanner(System.in);
static int numberOfProcess = 0;
int[]ProcessID = new int[numberOfProcess];
int[]ArrivalTime = new int[numberOfProcess];
int[]BurstTime = new int[numberOfProcess];
int[]CompletionTime = new int[numberOfProcess];
int[]TurnAroundTime = new int[numberOfProcess];
int[]WaitingTime = new int[numberOfProcess];
float avgWaitingTime = 0,avgTurnAroundTime = 0;
public void takeInput(){
System.out.println("Enter the number of process: ");
numberOfProcess = scanner.nextInt();
}
public void inputArrivalAndBurstTime(){
for(int i = 0;i < numberOfProcess;i++){
System.out.printf("Enter Arrival Time for Process %d: ",i+1);
ArrivalTime[i] = scanner.nextInt();
scanner.nextLine(); // Buffer Flush
System.out.printf("Enter Burst Time for Process %d: ",i+1);
BurstTime[i] = scanner.nextInt();
scanner.nextLine(); // Buffer flush
ProcessID[i] = i+1;
}
}
public void calculateCompletionTime(){
for(int i = 0 ; i < numberOfProcess ; i++){
if(i==0){
CompletionTime[0]=BurstTime[0];
} else if (ArrivalTime[i]<CompletionTime[i-1]) {
CompletionTime[i]=CompletionTime[i-1]+BurstTime[i];
} else {
CompletionTime[i]=ArrivalTime[i]+BurstTime[i];
}
}
}
public void calculateTurnAroundAndWaitingTime(){
for(int i = 0 ; i < numberOfProcess ; i++){
TurnAroundTime[i]=CompletionTime[i]+ArrivalTime[i];
WaitingTime[i]=TurnAroundTime[i]-BurstTime[i];
}
}
public void getAvgWaitingTimeAndAvgTurnAroundTime(){
for(int i = 0 ; i<numberOfProcess;i++){
avgTurnAroundTime+=TurnAroundTime[i];
avgWaitingTime+=WaitingTime[i];
}
avgWaitingTime = avgWaitingTime/numberOfProcess;
avgTurnAroundTime = avgTurnAroundTime/numberOfProcess;
}
public void getTable(){
System.out.println("ProcessNo. ArrivalTime BurstTime CompletionTime TurnAroundTime WaitingTime");
for(int i = 0 ; i < numberOfProcess ; i++){
System.out.println(ProcessID[i]+"\t\t"+ArrivalTime[i]+"\t\t"+BurstTime[i]+"\t\t"+CompletionTime[i]+"\t\t\t"+TurnAroundTime[i]+"\t\t\t"+WaitingTime[i]);
}
scanner.close();
}
}
[Output](https://i.stack.imgur.com/z1CEd.png)
You asked
Why getting IndexOutOfBoundsException with in shared snippet.
You declared static int numberOfProcess = 0; and creating many arrays of length 0, so every time you try to access those array you will get IndexOutOfBoundsException which thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.
Workaround ?
Many ways to resolve it, one practice is to declare your array implementation size after reading numberOfProcess through your scanner and make their pointer static.
public static void main(String[] args) {
System.out.println("Enter the number of process: ");
numberOfProcess = scanner.nextInt();
processID = new int[numberOfProcess];
arrivalTime = new int[numberOfProcess];
burstTime = new int[numberOfProcess];
completionTime = new int[numberOfProcess];
turnAroundTime = new int[numberOfProcess];
waitingTime = new int[numberOfProcess];
...
}
static int[] processID;
static int[] arrivalTime;
static int[] burstTime;
static int[] completionTime;
static int[] turnAroundTime;
static int[] waitingTime;
static Scanner scanner = new Scanner(System.in);
...
Other practice is just change the declaration type to list and traverse/allocate values accordingly.
Extra point
Please follow language model standards as well, like naming convention
An ordinary array can not be resized once declared. So use ArrayList instead
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FCFS_Practice {
public static Scanner scanner = new Scanner(System.in);
static int numberOfProcess = 0;
ArrayList<Integer> processID = new ArrayList();
ArrayList<Integer> arrivalTime = new ArrayList();
ArrayList<Integer> burstTime = new ArrayList();
ArrayList<Integer> completionTime = new ArrayList();
ArrayList<Integer> turnAroundTime = new ArrayList();
ArrayList<Integer> waitingTime = new ArrayList();
float avgWaitingTime = 0,avgTurnAroundTime = 0;
public static void main(String[] args) throws IOException
{
FCFS_Practice practice = new FCFS_Practice();
practice.takeInput();
practice.initializeArrayList();
practice.inputArrivalAndBurstTime();
practice.calculateCompletionTime();
practice.calculateTurnAroundAndWaitingTime();
practice.getTable();
}
public void initializeArrayList()
{
for(int i=0; i < numberOfProcess;i++)
{
processID.add(0);
arrivalTime.add(0);
burstTime.add(0);
completionTime.add(0);
turnAroundTime.add(0);
waitingTime.add(0);
}
}
public void takeInput(){
System.out.println("Enter the number of process: ");
numberOfProcess = scanner.nextInt();
}
public void inputArrivalAndBurstTime(){
for(int i = 0;i < numberOfProcess;i++){
System.out.printf("Enter Arrival Time for Process %d: ",i+1);
arrivalTime.set(i, scanner.nextInt());
scanner.nextLine(); // Buffer Flush
System.out.printf("Enter Burst Time for Process %d: ",i+1);
burstTime.set(i, scanner.nextInt());
scanner.nextLine(); // Buffer flush
processID.set(i, i+1);
}
}
public void calculateCompletionTime(){
for(int i = 0 ; i < numberOfProcess ; i++){
if(i==0){
completionTime.set(0,burstTime.get(0));
} else if (arrivalTime.get(i)<completionTime.get(i-1)) {
completionTime.set(i,completionTime.get(i-1)+burstTime.get(i));
} else {
completionTime.set(i, arrivalTime.get(i)+burstTime.get(i));
}
}
}
public void calculateTurnAroundAndWaitingTime(){
for(int i = 0 ; i < numberOfProcess ; i++){
turnAroundTime.set(i,completionTime.get(i)+arrivalTime.get(i));
waitingTime.set(i,turnAroundTime.get(i)-burstTime.get(i));
}
}
public void getAvgWaitingTimeAndAvgTurnAroundTime(){
for(int i = 0 ; i<numberOfProcess;i++){
avgTurnAroundTime+=turnAroundTime.get(i);
avgWaitingTime+=waitingTime.get(i);
}
avgWaitingTime = avgWaitingTime/numberOfProcess;
avgTurnAroundTime = avgTurnAroundTime/numberOfProcess;
}
public void getTable(){
System.out.println("ProcessNo. ArrivalTime BurstTime CompletionTime TurnAroundTime WaitingTime");
for(int i = 0 ; i < numberOfProcess ; i++){
System.out.println(processID.get(i)+"\t\t"+arrivalTime.get(i)+"\t\t"+burstTime.get(i)+"\t\t"+completionTime.get(i)+"\t\t\t"+turnAroundTime.get(i)+"\t\t\t"+waitingTime.get(i));
}
scanner.close();
}
}
You have started variable names with Upper case alphabet.. java coding conventions
I have changed variable names accordingly
ArrayList explained
Hello I've been getting this error in Kattis, 'Run time error' while all my test cases are correct in my own machine. Tested everything but as soon as i run this in kattis i get a run time error. Can you guys help me figure this out? Ive been debugging for hours but i am struggling.
https://open.kattis.com/problems/throwns?editsubmit=9372235 :Link of the problem
import java.util.*;
import java.io.*;
public class GOT{
public static void main(String[] args)throws IOException{
BufferedReader bi = new BufferedReader(new I
nputStreamReader(System.in));
int[] parseLine1 = new int[2];
String[] strLine1;
strLine1 = bi.readLine().split(" ");
//Parsing of 1st line of inputs i.e. N and K
for (int i = 0; i < strLine1.length; i++) {
parseLine1[i] = Integer.parseInt(strLine1[i]);
}
//init of Kids array
int[] nKids = new int[parseLine1[0]];
String[] commands = new String[parseLine1[1]];
int i;
for(i = 0; i < nKids.length; i++){
nKids[i] = i;
}
//parsing of 2nd line which are the commands
String strLine2;
String[] nCommands;
Scanner sc = new Scanner(System.in);
strLine2 = sc.nextLine();
nCommands = strLine2.split(" ");
int holder=0;
ArrayList<Integer> tracker = new ArrayList<Integer>();
int exit;
int throwns;
int undoCtr=0;
for(i = 0; i<nCommands.length; i++){
if(nCommands[i].equals("undo")){
nCommands[i] = nCommands[i].replaceAll("undo","101");
}
}
exit = nCommands.length;
i = 0;
while(exit != 0){
//System.out.println(Integer.parseInt(nCommands[i]));
if(Integer.parseInt(nCommands[i]) > 0){
for(int k = 0; k< Integer.parseInt(nCommands[i]); k++){
holder++;
if(holder==nKids.length){
holder = 0;
}
}
}if(Integer.parseInt(nCommands[i]) < 0){
for(int k = Integer.parseInt(nCommands[i]); k<0 ; k++){
holder--;
if(holder==0){
holder = nKids.length;
}
}
}else if(Integer.parseInt(nCommands[i]) == 101){
i++;
undoCtr = Integer.parseInt(nCommands[i]);
while(undoCtr!=0){
tracker.remove(tracker.size()-1);
undoCtr--;
}
exit--;
}
tracker.add(holder);
exit--;
i++;
}
System.out.println(tracker.get(0));
}`
}`
Your approach is too complex for a 2.8 difficulty problem. If you find yourself writing more than 25 lines of code, it's usually time to take a step back and re-think your approach.
Here's the algorithm that worked for me:
Make a list of "final" throw commands, initially empty.
Loop over the input tokens and analyze each command:
If a command is a number, append to the command list.
If a command is an undo n, pop the command list n times.
Now sum the commands in the list and print the mod of this sum, taking care to keep the mod positive.
Here's the spoiler:
public class Throwns {
public static void main(String[] args) {
var sc = new java.util.Scanner(System.in);
int n = Integer.parseInt(sc.nextLine().split(" ")[0]);
var line = sc.nextLine().split(" ");
var commands = new java.util.ArrayList<Integer>();
int sum = 0;
for (int i = 0; i < line.length; i++) {
if (line[i].matches("^-?\\d+$")) {
commands.add(Integer.parseInt(line[i]));
continue;
}
for (int j = Integer.parseInt(line[++i]); j > 0; j--) {
commands.remove(commands.size() - 1);
}
}
for (int c : commands) {
sum += c;
}
System.out.println(Math.floorMod(sum, n));
}
}
I'm working on a problem that requires me to store a very large amount of integers into an integer array. The input is formatted so that one line displays the amount of integers and the next displays all of the values meant to be stored. Ex:
3
12 45 67
In the problem there is closer to 100,000 integers to be stored. Currently I am using this method of storing the integers:
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] iVau = new int[n];
String[] temp = scanner.nextLine().split(" ");
for(int i = 0; i < n; i++) {
iVau[i] = Integer.parseInt(temp[i]);
}
This works fine, however the problem I am solving has a strict time limit and my current solution is exceeding it. I know that there is a more efficient way to store this input using buffered readers and input streams, but I don't know how to do it, can someone please show me.
The way you are using Scanner makes your program save a String containing the whole numbers at once, in memory. With 100000 numbers in the 2nd line of your input, it is not so efficient, you could read numbers one after the other without keeping the previous one in memory. So, this way, avoiding using Scanner.readLine() should make your program run faster. You will not have to read the whole line one time, and read a 2nd time this String to parse the integers from it: you will do both of these operations only once.
Here is an example. The method testing() does not use any Scanner. The method testing2() is the one you provided. The file tst.txt contains 100000 numbers. The output from this program, on my Mac Mini (Intel Core i5#2.6GHz) is:
duration without reading one line at a time, without using a Scanner instance: 140 ms
duration when reading one line at a time with a Scanner instance: 198 ms
As you can see, not using Scanner makes your program 41% faster (integer part of (198-140)/140*100 equals 41).
package test1;
import java.io.*;
import java.util.*;
public class Test {
// Read and parse an Int from the stream: 2 operations at once
private static int readInt(InputStreamReader ir) throws IOException {
StringBuffer str = new StringBuffer();
int c;
do { c = ir.read(); } while (c < '0' || c > '9');
do {
str.append(Character.toString((char) c));
c = ir.read();
} while (!(c < '0' || c > '9'));
return Integer.parseInt(str.toString());
}
// Parsing the input step by step
private static void testing(File f) throws IOException {
InputStreamReader ir = new InputStreamReader(new BufferedInputStream(new FileInputStream(f)));
int n = readInt(ir);
int [] iVau = new int[n];
for (int i = 0; i < n; i++) iVau[i] = readInt(ir);
ir.close();
}
// Your code
private static void testing2(File f) throws IOException {
Scanner scanner = new Scanner(f);
int n = scanner.nextInt();
int[] iVau = new int[n];
scanner.nextLine();
String[] temp = scanner.nextLine().split(" ");
for(int i = 0; i < n; i++)
iVau[i] = Integer.parseInt(temp[i]);
scanner.close();
}
// Compare durations
public static void main(String[] args) throws IOException {
File f = new File("/tmp/tst.txt");
// My proposal
long t = System.currentTimeMillis();
testing(f);
System.out.println("duration without reading one line at a time, without using a Scanner instance: " + (System.currentTimeMillis() - t) + " ms");
// Your code
t = System.currentTimeMillis();
testing2(f);
System.out.println("duration when reading one line at a time with a Scanner instance: " + (System.currentTimeMillis() - t) + " ms");
}
}
NOTE: creating the input file is done this way, with bash or zsh:
echo 100000 > /tmp/tst.txt
for i in {1..100000}
do
echo -n $i" " >> /tmp/tst.txt
done
I believe this is what you're looking for. A BufferedReader can only read a line at a time, so it is necessary to split the line and cast Strings to ints.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] line = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(line[i]);
}
} catch (IOException e) {
e.getStackTrace();
}
Just a thought, String.split returns an array of Strings. You say the input can be around 100,000 values. So in order to split the array in this way, String.split must be iterating through each element. Now in parsing the new array of strings to Integers you have iterated through the collection twice. You could do this in one iteration with a few small tweaks.
Scanner scanner = new Scanner(System.in);
String tmp = scanner.nextLine();
scanner = new Scanner(tmp);
for(int i = 0; scanner.hasNextInt(); i++) {
arr[i] = scanner.nextInt();
}
The reason for linking the scanner to a String instead of leaving it on System.in is so that it ends properly. It doesn't open System.in for user input on the last token. I believe in big O notation this is the difference between O(n) and O(2n) where the original snippet is O(2n)
I am not quite sure why OP has to use Integer.parseInt(s) here since Scanner can just do the parsing directly by new Scanner(File source).
Here is a demo/test for this idea:
public class NextInt {
public static void main(String... args) {
prepareInputFile(1000, 500); // create 1_000 arrays which each contains 500 numbers;
Timer.timer(() -> readFromFile(), 20, "NextInt"); // read from the file 20 times using Scanner.nextInt();
Timer.timer(() -> readTest(), 20, "Split"); // read from the file 20 times using split() and Integer.parseInt();
}
private static void readTest() {
Path inputPath = Paths.get(Paths.get("").toAbsolutePath().toString().concat("/src/main/java/io/input.txt"));
try (Scanner scanner = new Scanner(new File(inputPath.toString()))) {
int n = Integer.valueOf(scanner.nextLine());
int[] iVau = new int[n];
String[] temp = scanner.nextLine().split(" ");
for (int i = 0; i < n; i++) {
iVau[i] = Integer.parseInt(temp[i]);
}
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
private static void readFromFile() {
Path inputPath = Paths.get(Paths.get("").toAbsolutePath().toString().concat("/src/main/java/io/input.txt"));
try (Scanner scanner = new Scanner(new File(inputPath.toString()))) {
while (scanner.hasNextInt()) {
int arrSize = scanner.nextInt();
int[] arr = new int[arrSize];
for (int i = 0; i < arrSize; ++i) {
arr[i] = scanner.nextInt();
}
// System.out.println(Arrays.toString(arr));
}
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
private static void prepareInputFile(int arrCount, int arrSize) {
Path outputPath = Paths.get(Paths.get("").toAbsolutePath().toString().concat("/src/main/java/io/input.txt"));
List<String> lines = new ArrayList<>();
for (int i = 0; i < arrCount; ++i) {
int[] arr = new int[arrSize];
for (int j = 0; j < arrSize; ++j) {
arr[j] = new Random().nextInt();
}
lines.add(String.valueOf(arrSize));
lines.add(Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
try {
Files.write(outputPath, lines);
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
}
Locally tested it with 1_000 arrays while each array has 500 numbers, reading all the elements cost about: 340ms using Scanner.nextInt() while OP's method about 1.5ms.
NextInt: LongSummaryStatistics{count=20, sum=6793762162, min=315793916, average=339688108.100000, max=618922475}
Split: LongSummaryStatistics{count=20, sum=26073528, min=740860, average=1303676.400000, max=5724370}
So I really have doubt the issue lies in the input reading.
Since in your case you are aware of the total count of elements all that you have to do is to read X integers from the second line. Here is an example:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = in.nextInt();
int array[] = new int[count];
for (int i = 0; i < count; i++) {
array[i] = in.nextInt();
}
}
If this is not fast enough, which I doubt, then you could switch to the use of a BufferedReader as follows:
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(in.readLine());
int array[] = new int[count];
for (int i = 0; i < count; i++) {
int nextInteger = 0;
int nextChar = in.read();
do {
nextInteger = nextInteger * 10 + (nextChar - '0');
nextChar = in.read();
} while (nextChar != -1 && nextChar != (int)' ');
array[i] = nextInteger;
}
}
In your case the input will be aways valid so this means that each of the integers will be separated by a single whitespace and the input will end up with EoF character.
If both are still slow enough for you then you could keep looking for more articles about Reading Integers in Java, Competative programming like this one: https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
Still my favorite language when it comes to competitions will always be C :) Good luck and enjoy!
My code is as below. It first takes input from user and prints it in reverse. I'm new to Java. I achieve this by using two 'for loops' to first iterate through the input and another for-loop to print the numbers in reverse. My question is if there's any way to improve my code - by using just a single loop perhaps? Any suggestion is appreciated. Thank you.
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for (int arr_i = 0; arr_i < n; arr_i++) {
arr[arr_i] = in.nextInt();
}
for (int reverse_i = n-1; reverse_i >= 0; reverse_i--) {
System.out.print(arr[reverse_i]);
if (reverse_i != 0) {
System.out.print(" ");
}
}
}
An example input:
4
1 2 3 4
Expected output:
4 3 2 1
Use a StringBuilder and always insert at 0 index.
See: Oracle » JavaDocs » 1.7 » java.lang.StringBuilder.insert(int, int)
StringBuilder bld = new StringBuilder();
for (int arr_i = 0; arr_i < n; arr_i++) {
int i = in.nextInt();
bld.insert(0, i);
}
System.out.println(bld.toString());
The simplest approach I found is to use String Builder here:
Scanner in = new Scanner(System.in);
StringBuilder stringBuilder = new StringBuilder();
while (in.hasNext()) {
stringBuilder.append(in.next());
if(in.hasNext()) {
stringBuilder.append(" ");
}
}
System.out.print(stringBuilder.reverse());
First, you might reverse your elements as you insert them in the array. Then, assuming you are using Java 8+, you could use an IntStream instead of a loop and print with a basic Collector. Like,
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
IntStream.range(0, n).forEachOrdered(i -> arr[n - i - 1] = in.nextInt());
System.out.println(IntStream.of(arr).mapToObj(String::valueOf)
.collect(Collectors.joining(" ")));
I am not sure about the requirements of your request, but you do not necessarily have to use an array for this. You can concatenate the inputs into a String in reverse order like so.
public static void main(String[] args) {
System in = new Scanner(System.in);
int n = in.nextInt();
String allNumbers = "";
for (int i = 0; i < n; i++) {
int current = in.nextInt();
allNumbers = current + " " + allNumbers;
}
if(allNumbers != ""){
allNumbers = allNumbers.substring(0,allNumbers.length()-1);
}
System.out.println(allNumbers);
}
Java has inbuilt String method for the same. If your input is a String, you can use the below-
String s1 = new String("new");
String s2 = s1.reverse();
System.out.println(s2) // wen
I need help sorting this array in alphabetical order using the bubble sort algorithm.
My code is:
public class Strings
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t=0; t<t1.length-1; t++)
{
for (int i = 0; i<t1.length -1; i++)
{
if(t1[i+1].compareTo(t1[1+1])>0)
{
tempStr = t1[i];
t1[i] = t1[i+1];
t1[i+1] = tempStr;
}
}
}
for(int i=0;i<t1.length;i++)
{
System.out.println(t1[i]);
}
}
}
The code compiles, but it does not sort alphabetical. Please help me.
You have three errors in your code.
The first error is in the inner for loop, in the place where you do the check statement, it should be i < t1.length - t -1 not i < t1.length -1. You subtract t because you do not want to loop through the whole array again, only the first part of it.
The second and third errors are in the if statement. You need to turn the greater than symbol into a lesser than symbol, because the way you have the compareTo method set up, it will return a negative number.
The other error in this line is that in the compareTo parameter you put 1 + 1 it actually should be just i, because you want one less than the object it is comparing to.
The fixed working code is below (Comments are what you originally had):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t = 0; t < t1.length - 1; t++) {
for (int i= 0; i < t1.length - t -1; i++) {
if(t1[i+1].compareTo(t1[i])<0) {
tempStr = t1[i];
t1[i] = t1[i + 1];
t1[i + 1] = tempStr;
}
}
}
for (int i = 0; i < t1.length; i++) {
System.out.println(t1[i]);
}
}
please change
String[] t1 = s1.split(", ");
to
String[] t1 = s1.split("");
This will solve the issue.