Runtime error in java about selection sort - java

I have learnt selection sort, and i try to code it with java. But it has an error, i think it a runtime error. I don't know what to fix in my code.
This is the code:
import java.util.Scanner;
public class Main {
public static void main(String args[])
{
int temp;
Scanner sc=new Scanner(System.in);
int number;
int input=sc.nextInt();
int [] carriage;
carriage=new int[input];
for(int i=0;i<input;i++)
{
number=sc.nextInt();
carriage[i]=number;
}
int n=carriage.length;
for(int i=0;i<n-1;i++)
{
for(int j=i+1;i<n;j++)
{
if(carriage[j]<carriage[i])
{
temp=carriage[i];
carriage[i]=carriage[j];
carriage[j]=temp;
}
}
System.out.println(carriage[i]+ " ");
}
sc.close();
}
}

I think you want to sort the number of integer provided by user. Your code is having 2 errors. One in the for loop starting with i, the condition should be i
public class Main {
public static void main(String args[]) {
int temp;
Scanner sc = new Scanner(System.in);
int number;
System.out.println("Enter the number of integers to be sorted - ");
int input = sc.nextInt();
int[] carriage;
carriage = new int[input];
for (int i = 0; i < input; i++) {
System.out.println("Enter the "+ i+1 +"number - ");
number = sc.nextInt();
carriage[i] = number;
}
int n = carriage.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (carriage[j] < carriage[i]) {
temp = carriage[i];
carriage[i] = carriage[j];
carriage[j] = temp;
}
}
System.out.println(carriage[i] + " ");
}
sc.close();
}
}

Related

Run Time Error_String index out of bound Exception_Printing string odd and even indexes

Code :
import java.io.;
import java.util.;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] sa = new String[n];
for(int i=0;i<n;i++){
sa[i] = sc.nextLine();
}
String odd="";
String even="";
for(int i=0;i<n;i++)
{
for(int j=0;j<sa[i].length();j++)
{
if(j%2!=0){
odd = odd+sa[j].charAt(j);
}
else {
even = even+sa[j].charAt(j);
}
}
System.out.println(odd+" "+even);
}
}
}
ISsue : GEtting run time exception while running the code. --> String index out of bound exception
You can try below code. It is because of calling a method like nextInt() before sc.nextLine()
The problem is that nextInt() does not consume the '\n', so the next call to nextLine() consumes it and then it's waiting to read the input for next element.
You need to consume the '\n' before calling nextLine() or You can directly call nextLine() for array size as well.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Array size");
int n = Integer.parseInt(sc.nextLine());
String[] sa = new String[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter Element "+i);
String val = sc.nextLine();
sa[i]=val;
}
String odd = "";
String even = "";
for (int i = 0; i < n; i++) {
for (int j = 0; j < sa[i].length(); j++) {
if (j % 2 != 0) {
odd = odd + sa[j].charAt(j);
} else {
even = even + sa[j].charAt(j);
}
}
System.out.println(odd + " " + even);
}
}

Getting a weird output on my program lost on what to do next to fix it

So i've ben at this program for awhile and i've gotten everything to work without compiling error but now I'm getting a weird output, first ill post the program the the problem.
import java.util.Scanner;
import java.util.*;
public class project3 {
private static double[] payrate;
private static String[] names;
public static void SortData(double payrate[]) {
int first;
int temp;
int i;
int j;
for (i = payrate.length - 1; i > 0; i--) {
first = 0;
for (j = 1; j <= i; j++) {
if (payrate[j] < payrate[first]) {
first = j;
}
}
temp = (int) payrate[first];
payrate[first] = payrate[i];
payrate[i] = temp;
}
}
public static void GetData() {
Scanner input = new Scanner(System.in);
System.out.println("How many names do you want to enter?");
String strNum = input.nextLine();
int num = Integer.parseInt(strNum);
int array[] = new int[num];
for (int i = 0; i < array.length; i++) {
names = new String[num];
System.out.println("enter employee's name: ");
names[i] = input.nextLine();
//while(names[i].length < 2)
//{
//System.out.println("enter valid employee's name: ");
//names[i] = input.nextLine();
//}
}
for (int j = 0; j < array.length; j++) {
payrate = new double[num];
System.out.println("enter employee's payrate: ");
payrate[j] = input.nextDouble();
while (payrate[j] > 100 || payrate[j] < 0) {
System.out.println("enter valid employee's payrate: ");
payrate[j] = input.nextDouble();
}
}
}
public static void DisplayData(double payrate[], String names[]) {
System.out.printf("Name PayRate\n");
for (int l = 0; l < names.length; l++) {
//for(int i=0;i<names.length;i++)
// {
System.out.print(names[l]);
System.out.printf("\n", payrate[l]);
//}
}
}
public static void main(String[] args) {
GetData();
SortData(payrate);
DisplayData(payrate, names);
}
}
The program Is suppose to print out something like this
Name Payrate
Daniel 54.76
josh 73.12
kyle 12.54
but the program is printing out this
Name PayRate
null
null
null
null
qt
Here are some point you can correct it.
in GetData(), you should put names = new String[num]; anywhere
before loop start, so deos payrate = new double[num];.
in SortData(), why not use double temp;? then you don't have to turn payrate[first] into int type.
in DisplayData(), System.out.printf("\n", payrate[l]); disply
nothing but change line. I think it's better to do like
System.out.printf("Name\tPayRate\n");
for (int l = 0; l < names.length; l++) {
System.out.print(names[l]);
System.out.println("\t"+payrate[l]);
}
well, it's eaiser to explain with code than English. :'(
public static void SortData(double payrate[]) {
int first;
double temp;
String tempString;
int i;
int j;
for (i = payrate.length - 1; i > 0; i--) {
first = 0;
for (j = 1; j <= i; j++) {
if (payrate[j] < payrate[first]) {
first = j;
}
}
temp = payrate[first];
payrate[first] = payrate[i];
payrate[i] = temp;
tempString = names[first];
names[first] = names[i];
names[i] = tempString;
}
}

Error when entering array from keyboard

package array;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
n = input.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = input.nextInt();
}
System.out.println(a);
}
}
You cannot print an array directly, you have to iterate through it's values.
for (int j=0;j<a.length;j++){
System.out.println(a[j]);
}

How to tell this Java method to execute itself again under a certain condition?

Please refer to this UVa OJ problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=27&page=show_problem&problem=2595
It's working for a single test case. However, there is no given input for the number of test cases, which means that the program should know when to continue and when to stop just by reading the input for the variables of the problem
I'm think about using the scanner.hasNextLine()method as a conditional; and if it's true, make main start again, but I'm not sure how to do it. Any clue?
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
int N = scanner.nextInt();
int B = scanner.nextInt();
int H = scanner.nextInt();
int W = scanner.nextInt();
int [] priceArray = new int [H];
int [] availableBeds = new int [W];
int cheapestStay = 999999999;
for (int i=0; i<H; i++){
priceArray[i] = scanner.nextInt();
for (int j=0; j<W; j++){
availableBeds[j] = scanner.nextInt();
if (availableBeds[j] >= N && priceArray[i]*N <= B && priceArray[i]*N < cheapestStay){
cheapestStay = priceArray[i]*N;
}
}
}
if (cheapestStay != 999999999){
System.out.println(cheapestStay);
}else{
System.out.println("stay home");
}
/*if (!scanner.hasNextLine)
repeat*/
}
You could use a while loop to repeat the instructions of your main method as long as hasNextLine() evaluates to true.
public static void main(String[] args) {
while(scanner.hasNextLine()){
...
}
}
You can wrap all the code in your main(...) method into a while(scanner.hasNextLine()) loop
This is a best usecase of do-while
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
do {
int N = scanner.nextInt();
int B = scanner.nextInt();
int H = scanner.nextInt();
int W = scanner.nextInt();
int [] priceArray = new int [H];
int [] availableBeds = new int [W];
int cheapestStay = 999999999;
for (int i=0; i<H; i++){
priceArray[i] = scanner.nextInt();
for (int j=0; j<W; j++){
availableBeds[j] = scanner.nextInt();
if (availableBeds[j] >= N && priceArray[i]*N <= B && priceArray[i]*N < cheapestStay){
cheapestStay = priceArray[i]*N;
}
}
}
if (cheapestStay != 999999999){
System.out.println(cheapestStay);
}else{
System.out.println("stay home");
}
/*if (!scanner.hasNextLine)
repeat*/
} while (scanner.hasNextLine());
}

Using scanner to produce arrays

I am using java and want to use a Scanner to get user input and then output arrays.
I've created a file that works for one and a separate file for the other, but I want to ask the user questions and get custom array properties back (variable number of arrays, variable rows, variable columns, variable addition, subtraction, and multiplication of the array)
import java.util.Scanner;
import java.io.IOException;
public class ScannerDemoforNetbeans
{
public static void main (String [] args)throws IOException
{
//`enter code here`
System.out.println ("Okay, you got it! How many rows do you want");
Scanner rc= new Scanner (System.in);
public static rows;
rows= rc.nextInt();
System.out.println ("How many columns do you want?");
Scanner c = new Scanner (System.in);
public static columns;
columns = c.nextInt();
System.out.println ("Rows" + rows);
System.out.println ("Columns:" + columns);
}
// }
// public static void createarray (String [] args)
// {
int matWidth = ScannerDemoforNetbeans.columns;
int matHeight = ScannerDemoforNetbeans.rows;
int maxCellValue = 70;
int [][] mat1 = new int [matHeight][matWidth];
int [][] mat2 = new int [matHeight][matWidth];
int [][] sum = new int [matHeight][matWidth];
for (int i=0; i<matHeight; ++i)
{
for (int j=0; j<matWidth; ++j)
{
java.util.Random r = new java.util.Random();
mat1 [i][j]= r.nextInt (maxCellValue);
mat2 [i][j] = r.nextInt (maxCellValue);
}
}
print2Darray (mat1);
System.out.println ();
print2Darray (mat2);
for (int i=0; i<matHeight; ++i)
{
for (int j=0; j<matWidth; ++j)
{
sum [i][j]= mat1 [i][j] + mat2 [i][j];
}
}
System.out.println ();
print2Darray (sum);
}
public static void print2Darray (int[][]arr)
{
for (int [] i : arr)
{
for (int j : i)
{
System.out.print (j + " ");
}
System.out.println();
}
System.out.println ();
}
}
Any help is appreciated.
package araay;
import java.util.Scanner;
public class Araay {
public static void main(String[] args)
{
Scanner a=new Scanner(System.in);
int i=0;
int j=0;
int arr[][]=new int [3][3];
System.out.println ("Enter the numbers");
for (i=0;i<=3;i++)
for(j=0;j<=3;j++)
arr[i][j]=a.nextInt();>>>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at araay.Araay.main(Araay.java:18)//this error is occur in this code plz solve it
for (i=0;i<=3;i++)
for(j=0;j<=3;j++)
System.out.println("The matrix of array is "+arr[i][j]+"\t");
System.out.println();
}
}

Categories