Selection sort with arrays from keyboard in java - java

Good Morning,
I'm trying to write a code where the user writes some numbers in the keyboard (casually), and the program should write them in order, from the lower to greater.
I don't remember in particular how to insert the number from the keyboard to the array or to the arraylist class if i don't want any limit.
This is my code. i know it is not correct.
import java.util.*;
class Ordine {
public static void main (String [] args) {
Scanner s = new Scanner (System.in)
System.out.println; ("insert the number which you need to order");
int n = s.nextInt();
int [] x = new int [200];
for (int i=0; i<x.length; i++) {
x [i] = s.nextInt();
for (int j=i+1; j<x.length; j++) {
if (x[i] > x[j]) {
//cambia ELEMENTI
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
}
}
Thank you!

Since array have fixed size you will have to use arraylist. Below is the code
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class test{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
ArrayList<Integer> a = new ArrayList<Integer>(Arrays.asList(1,2,3,4,8,9,10,13));
try{
while (true)
{
int l=0;int r=a.size()-1,m=0;
int p=in.nextInt();
while(l<=r){
m=(l+r)/2;
if(a.get(m)>p){
l=l;r=m-1;
}
if(a.get(m)<p){
l=m+1;r=r;
}
if(a.get(m)==p){
l=m;
break;
}
}
a.add(l,p);
System.out.println("Entered number is: "+p);
System.out.print("Sorted arraylist is: ");
for(int j=0;j<a.size();j++){
System.out.print(a.get(j)+" ");
}
System.out.println();
}
}
catch(Exception e){
}
}
}
I have intitialized the arraylist. And it will print the ordered arraylist everytime you enter a new number.
Below is a sample output

Related

user needs to input 10 elements in the array with JOptionPane

How does the program will ask 10 elements for the array with JOptionPane and then in the end it will show the 10 elements? It only ask one element and its done.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Array1
{
public static void main(String[] args)
{
int n = 10;
Scanner sc=new Scanner(System.in);
int[] array = new int[10];
JOptionPane.showInputDialog(null, "Enter ten elements for the array: ");
for(int i=0; i<n; i++)
{
array[i]=sc.nextInt();
}
JOptionPane.showMessageDialog("The elements are: ");
for (int i=0; i<n; i++)
{
JOptionPane.showMessageDialog(null, array[i]);
}
}
}

Getting Odd numbers from Array

I've been working on this program and am currently stuck. The HW prompt is to prompt a user to input numbers, save it as an array, find the number of odd numbers & the percentages then display those values back to the user.
Currently I am trying to write to part of the code that finds the percentage of the odd numbers in the array but the return isn't displaying and i just cant figure it out. Any ideas? Thank you!
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
int inputs = Integer.parseInt(console.next());
int[] arraysize = new int[inputs];
Oddvalues(arraysize);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i = 1; i < size.length; i++) {
if(size[i] % 2 != 0) {
i++;
}
}
return countOdd;
}
}
Consider the following code, which appears to be working in IntelliJ locally. My approach is to read in a single line from the scanner as a string, and then to split that input by whitespace into component numbers. This avoids the issue you were facing of trying to directly create an array of integers from the console.
Then, just iterate over each numerical string, using Integer.parseInt(), checking to see if it be odd.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
String nextLine = console.nextLine();
String[] nums = nextLine.split(" ");
int oddCount = 0;
for (String num : nums) {
if (Integer.parseInt(num) % 2 == 1) {
++oddCount;
}
}
double oddPercent = 100.0*oddCount / nums.length;
System.out.println("Total count of numbers: " + nums.length + ", percentage odd: " + oddPercent);
}
In the function Oddvalues you promote i instead of promoting countOdd. And the loop should start from 0 not 1.
Try this
import java.util.*;
import java.lang.*;
import java.io.*;
public class OddVals{
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int[] array = new int[sc.nextInt()]; // Get the value of each element in the array
System.out.println("Please input a series of numbers");
for(int i = 0; i < array.length; i++)
array[i] = sc.nextInt();
System.out.println("Number of Odds:" +Oddvalues(array));
printOdd(array);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i=0; i < size.length; i++){
if(size[i]%2 != 0)
++countOdd;
}
return countOdd;
}
public static void printOdd(int[] arr)
{
for(int i=0;i<arr.length;++i)
{
if(arr[i]%2==1)
System.out.print(arr[i]+" ");
}
}
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
while (console.hasNext())
{
String str = console.next();
try
{
if(str.equals("quit")){
break;
}
int inputs = Integer.parseInt(str);
System.out.println("the integer values are" +inputs);
intList.add(inputs);
}
catch (java.util.InputMismatchException|NumberFormatException e)
{
console.nextLine();
}
}
console.close();
double d = Oddvalues(intList);
System.out.println("the percent is" +d);
}
public static double Oddvalues (List<Integer> list) {
int count = 0;
for( Integer i : list)
{
if(!(i%2==0))
{
count++;
}
}
double percentage = (Double.valueOf(String.valueOf(count))/ Double.valueOf(String.valueOf(list.size())))*100;
return percentage;
}
}
If this helps

Taking Space Separated Row Inputs in a Two dimensional Array

Im relatively new to programming and i was working with a problem that requires me to read space separated integers and input them into a two dimensional array but i dont seem to understand why I am not able to do so . any hint on possible approaches will be helpful
Eg. Input will look like this
2 //FOR DIMENSION
2 3 //ROW1
4 5 // ROW 2
import java.io.*;
import java.util.*;
import java.lang.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc= new Scanner(System.in);
System.out.println("Hello World");
System.out.println("Enter Dimension of Matrix");
int N= sc.nextInt();
int[][] m=new int [N][N];
for (int i=0;i<N;i++)
{ System.out.println("Enter Elements of row "+ i);
for(int j=0;j<N;j++ )
{
m[i]=sc.nextInt();
}
}
System.out.println(m);
}
}
I tested the above code and got the following result on the console
HelloWorld.java:16: error: incompatible types: int cannot be converted to int[]
m[i]=sc.nextInt();
^
First of all, I would like to know is my thinking(approach) right?
Second, what are the possible ways to do this correctly?
here you go:
import java.io.*;
import java.util.*;
import java.lang.*;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Dimension of Matrix");
int N = sc.nextInt();
int[][] m = new int[N][N];
for (int i = 0; i < N; i++) {
System.out.println("Enter Elements of row " + i);
for (int j = 0; j < N; j++) {
m[i][j] = Integer.valueOf(sc.next());//replaced line with proper code
}
}
sc.close();
System.out.println(Arrays.deepToString(m));//use this api to print arrays
}
}
m is a multidimensional array meaning you must specify m[i][?]. Like so
m[i][j]=sc.nextInt();
Your logic is a little off, you want to ask the user for input at row start i, and for the other columns j. Try this and happy coding :)
for (int i=0;i<N;i++){
for(int j=0;j<N;j++){
System.out.println("Enter Elements of row "+ i);
m[i][j]=sc.nextInt();
}
}
for (int i=0;i<N;i++){
for(int j=0;j<N;j++){
System.out.print(m[i][j]);
}
System.out.println();
}

How to compare user input in array?

Hi guys sorry I'm a newbie to Java, this is one of the exercise in my class.
I supposed to ask user input 5 numbers, then compare them if they are the same number that entered before.
These are my code so far, but I can't get it work.
Thanks.
import java.util.Scanner;
public class Source {
private static int num = 0;
private static int[] enterednum = new int[5];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
for(int count = 0; count < enterednum.length; count++) {
System.out.println("Enter a number.");
num = input.nextInt();
compare(enterednum);
}
System.out.println("These are the number you have entered: ");
System.out.println(enterednum);
}
public static void compare(int[] enterednum) {
for(int count = 0; count < 6; count++)
if(num == enterednum[count])
System.out.println("The number has been entered before.");
}
}
You may want something like this:
import java.util.Scanner;
public class Source
{
private static int enterednum[]=new int[5];
public static void main(String args[])
{
int num=0; // make this local variable since this need not be class property
Scanner input = new Scanner(System.in);
for(int count=0;count<enterednum.length;count++)
{
System.out.println("Enter a number.");
num = input.nextInt();
compare(num, count);
enterednum[count] = num; // store the input
}
System.out.println("These are the number you have entered: ");
// print numbers in array instead the array
for(int count=0;count<enterednum.length;count++)
{
System.out.println(enterednum[count]);
}
}
// change the method signature to let it get the number of input
public static void compare(int num, int inputcount)
{
for(int count=0;count<inputcount;count++)
{
if(num==enterednum[count])
System.out.println("The number has been entered before.");
}
}
}
You can do this way if you need.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Source {
public static void main(String[] args) throws IOException {
// I used buffered reader because I am familiar with it :)
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Create a Set to store numbers
Set<Integer> numbers = new HashSet<>();
for (int i = 0; i < 5; i++) {
System.out.print("Enter a number: ");
String line = in.readLine();
int intValue = Integer.parseInt(line);
// You can check you number is in the set or not
if (numbers.contains(intValue)) {
System.out.println("You have entered " + intValue + " before");
} else {
numbers.add(intValue);
}
}
}
}

How do I Store 6 integers from Scanner Console into a Set

I know this is simple. How would I take input from my console and store the input into a Set that can later be used to be returned on a Method. This is what I have so far.
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class InputConsole {
public static void main(String[] args) {
Set<Integer> s = new HashSet<Integer>(6);
int[] numbers = new int[6];
Scanner input = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
System.out.print("Please enter number ");
numbers[i] = input.nextInt();
{
}
}
}
}
I am using and Array just to test with. The Array is set to 6 so if I type 6 numbers in the console it will stop. I have instantiated the HashSet but I don't know how to go about storing the numbers from the console into it.
Use method Set::add()
for (int i = 0; i < numbers.length; i++)
{
System.out.print("Please enter number ");
s.add(input.nextInt());
}
You don't need int[] array
EDIT:
Whole main()
public static void main(final String ... args)
{
final int inputs = 6;
final Set<Integer> s = new HashSet<Integer>(6);
final Scanner input = new Scanner(System.in);
for (int i = 0; i < inputs; i++)
{
System.out.print("Please enter number #" + (i + 1) + ":");
s.add(input.nextInt());
}
System.out.println("Well done!");
System.out.println(s);
}
import java.util.*;
class Hashsetdemo
{
public static void main(String args[])
{
HashSet h=new HashSet(6);
int [] no = new int[6];
Scanner s=new Scanner(System.in);
for (int i=0;i<no.length;i++)
{
System.out.println("please enter number");
h.add(s.nextInt());
}
System.out.println(h);
}
}

Categories