I just want to write a program that sorts 3 integers. The integers are entered from the input dialog. My code is really simple. I just need to get some data and put them in array called num. and then I create a method to sort the data by using bubble-sort logic. that method called sort. I have added command to display the sorted result with System.out.println("Sorted Result : "+Arrays.toString(num)) but that's not working.
The output just let me input data and then nothing happen.
Can anyone please tell me something I miss or what I did wrong?
Thank you.
package numThree;
import java.util.Scanner;
import java.util.Arrays;
public class sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[3];
//INPUT DATA
System.out.println("Enter integers : ");
for(int i=0;i<=num.length;i++){
num[i]=sc.nextInt();
}
sort(num);
}
//SORTING
public static void sort (int[] num){
for(int i=0;i<=num.length-1;i++){
for(int j=0;j<=num.length-i;j++){
if(num[j-1]>num[j]){
int temp = num[j];
num[j] = num[j-1];
num[j-1] = temp;
}
}
System.out.println("Sorted Result : "+Arrays.toString(num));
}
}
}
I believe you need a boolean flag to implement a bubble sort as you cannot know in advance how many times the loop will perform the swapping of consecutive elements.
Try this:
package numThree;
import java.util.Scanner;
import java.util.Arrays;
public class sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] num = new int[3];
//INPUT DATA
System.out.println("Enter integers : ");
for(int i=0;i<=num.length;i++){
num[i]=sc.nextInt();
}
sort(num);
}
//SORTING
public static void sort (int[] num){
boolean swapped = true;
while(swapped){
swapped = false;
for(int i=0;i<num.length-1;i++){
if(num[i]>num[i+1]){
int temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
swapped = true;
}
}
}
System.out.println("Sorted Result : "+Arrays.toString(num));
}
}
Note that it can still be slightly improved: each time around the loop the largest number will end up as far as it can get towards the end of of the array: there's no need to check or swap till the end each time.
By using a variable as the upper limit of the index i and decreasing its value after the for loop you can reduce the total number of iterations.
int end = num.length-1;
while(swapped){
swapped = false;
for(int i=0;i<end;i++){
if(num[i]>num[i+1]){
int temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
swapped = true;
}
}
end--;
}
Related
import java.util.ArrayList;
import java.util.Scanner;
public class SecondPlusThird {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();
while (true) {
int number = Integer.valueOf(scanner.nextLine());
if (number == 0) {
break;
}
}
System.out.println(numbers.get();
}
}
I tried it with System.out.println(numbers.get(1)+(2));
But it didn't work. I have to print the sum of the second and third numbers given by the user.
If you want to do sum of two numbers, i would recommend you to use an array.
Arraylist is dynamic array & you are not utilizing its potential so don't use it.
Anyways, if you still want to do it.
ArrayList<Integer> a1 = new ArrayList<Integer> ();
a1.add(1);
a1.add(2);
sum = a1.get(0) + a1.get(1);
1.Output: print remainder when sum is divided by max element.
2.Constraints: 1<=n<=100;
0<=A[i]<=1000
I need this code to validate array elements as such:
pseudocode:
if (arr_elmt>=0 and arr_elmt<=1000) ->Then execute succeeding commands.
else ->stop program, even though other elements obey constraint
3.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner val = new Scanner(System.in);
System.out.print("Enter no of values:");
int n;
int A[] = new int[n=val.nextInt()];
//First constraint
if(n>=1 && n<=100)
{
int i=0;
for(i=0;i<A.length;i++)
{
A[i]=val.nextInt();
}
for(i=0;i<A.length;i++)
{ //Second constraint
if(A[i]>=0 && A[i]<=1000)
{
int sum=0;
//Using for-each loop to print array values and get total sum
for(int t:A)
{
System.out.print(t+" ");
sum+=t;
}
//To get largest value
int largest=A[0];
for(i=0;i<A.length;i++)//i=1 can work
{
if(A[i]>largest)
{
largest=A[i];
}
}
//To get and print remainder
int rem;
rem=sum%largest;
System.out.print("\n"+ rem);
}
}
}
}
}
e.g: input: 3;
Values: 2988 67 5.
I expect an error due to 2988>1000, but the code
still runs and gives me output! output obtained:(2988+67+5)mod(2988)
Hi so your problem is that you do not specified that program should stop (or do whatever you want) when find number which does not match your second constraint.
So right now when does not match second constraint for 2688 it keeps iterating to second item and keep executing rest of your code.
So to make your program end when second constraint is not match you should add something like this
import java.util.Scanner;
public class test {
public static void main(String args[]) {
Scanner val = new Scanner(System.in);
System.out.print("Enter no of values:");
int n;
int A[] = new int[n=val.nextInt()];
//First constraint
if(n>=1 && n<=100)
{
for(int i=0;i<A.length;i++)
{
A[i]=val.nextInt();
}
for(int i=0;i<A.length;i++)
{ //Second constraint loop through all elements of A[]
// if one of it does not obey constraint exit the program
if(A[i]<=0 || A[i]>=1000) // notice here I change '>'
{
System.exit(0); // this else is attached to your second constraint
}
}
for(int i = 0; i < A.length; i++){
int sum=0;
//Using for-each loop to print array values and get total sum
for(int t:A)
{
System.out.print(t+" ");
sum+=t;
}
//To get largest value
int largest=A[0];
for(int j=0;j<A.length;j++)//i=1 can work
{
if(A[j]>largest)
{
largest=A[j];
}
}
//To get and print remainder
int rem;
rem=sum%largest;
System.out.println(rem);
}
}
}
}
I'm in the process of making a program that can take the #'s from a credit card and check to see if it's valid.
here is my code so far:
import java.util.Scanner;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader=new Scanner(System.in);
System.out.println("Please enter your credit card #");
String Ccard=reader.nextLine();
int length=Ccard.length();
doubleDig(Ccard,length);
int []digits=doubleDig(Ccard,length);
/*for(int x=0;x<digits.length;x++){
System.out.println(digits[x]);
}test array*/
}
public static int[] doubleDig(String cardNum,int length){
int []nums=new int[length];
for(int x=0;x<cardNum.length();x++){
nums[x]=cardNum.charAt(x);
System.out.println(cardNum.charAt(x));
}//makes array
//System.out.println(nums.length);
for(int x=nums.length;x<0;x-=2){
nums[x]=nums[x]*2;
}
return nums;
}//end doubleDig
}
I went to see if the array was set up correctly so I used:
System.out.println(nums[x]); in the loop but got values that I didn't understand. I then went and used:
System.out.println(cardNum.charAt(x)); in the loop to see what was up.
I then noticed that the array was somehow being displayed a 2nd time. The size of the array should be equal to the length of the string the user put in (I'm using 5491946915444920 as my test value), which is 16 in this case. 16 numbers display, but then it loops over itself again somehow and the values display a 2nd time(displaying 32 total #'s). Any clues?
you can use this:
public static int[] doubleDig(String cardNum, int length) {
int[] nums = new int[length];
int num;
for (int x = 0; x < cardNum.length(); x++) {
nums[x]=Integer.parseInt(cardNum.substring(x, x+1));
}
System.out.println(nums.length);
return nums;
}
Because at this line of code nums[x] = cardNum.charAt(x); you are actually printing char values i.e [53, 52, 57,etc] for 5491946915444920
This code shows "Terminated due to timeout" error on some large inputs on Hackerrank but works fine for the rest of the cases. Help me improve this code please.
John Watson performs an operation called a right circular rotation on an array of integers, . After performing one right circular rotation operation, the array is transformed from to .
Watson performs this operation times. To test Sherlock's ability to identify the current element at a particular position in the rotated array, Watson asks queries, where each query consists of a single integer, , for which you must print the element at index in the rotated array (i.e., the value of ).
Input Format
The first line contains space-separated integers, , , and , respectively.
The second line contains space-separated integers, where each integer describes array element (where ).
Each of the subsequent lines contains a single integer denoting .
Constraints
Output Format
For each query, print the value of the element at index of the rotated array on a new line.
Sample Input
3 2 3
1 2 3
0
1
2
Sample Output
2
3
1
MY CODE
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int n,k,q,temp=0,c=0;
Scanner sc=new Scanner(System.in);
try{
n=sc.nextInt();
k=sc.nextInt();
q=sc.nextInt();
int[] arr=new int[n];
int qrr[]=new int[q];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
while(sc.hasNext()){
qrr[c++]=sc.nextInt();
}
for(int j=1;j<=k;j++){
temp=arr[n-1];
for(int i=n-2;i>=0;i--){
arr[i+1]=arr[i];
}
arr[0]=temp;
}
for(int i=0;i<q;i++){
System.out.println(arr[qrr[i]]);
}
}
catch(Exception ae){
System.out.println(ae.getMessage());
}
}
}
import java.io.*;
import java.util.*;
public class Solution {
public static int m,n,k,q,i=0,c=0;
public static int errorflag = 0;
public static int array[];
public static int rotated[];
public static Scanner in = new Scanner(System.in);
public static int[] getArray(int n){
array = new int[n];
for(i=0;i<n;i++){
array[i] = in.nextInt();
}
return(array);
}
public static int[] rotate(int[] original){
int[] rotated = new int[original.length];
for(i=0;i<original.length;i++){
rotated[(i+k)%original.length] = original[i];
}
return(rotated);
}
The above function works with a worst case O(n) complexity.
Basically what you're doing is assigning a new index for the elements such that they are right rotated or incremented by an amount k and the overflow is taken care of by the modulus operation.
public static void main(String[] args) {
n = in.nextInt();
k = in.nextInt();
q = in.nextInt();
array = getArray(n);
int m[] = new int[q];
for(i=0;i<m.length;i++){
m[i] = in.nextInt();
}
rotated = rotate(array);
for(i=0;i<m.length;i++){
System.out.println(rotated[m[i]]);
}
}
}
I'm currently stuck on a problem, let's say I want to find the middle value the user inputted, is there a function in Java wherein I can peek or return the middle value?
import java.util.*;
public class PQueue {
public static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int arr;
PriorityQueue<Integer> queueB = new PriorityQueue<Integer>();
for(int j=0; j<=4; j++)
{
System.out.println("Input Intergers: ");
arr = console.nextInt();
queueB.add(arr);
}
System.out.print(queueB.peek());
}
}
Just pop half the values off the PQ. The last one popped is the middle one.
The case where N is even is left as an exercise for the reader.
Of course this is assuming that by 'middle' you mean 'median'. If you mean 'mean', you're using the wrong data structure: you should use an array, sort it, and evaluate (array[0]+array[last])/2.