How can I shorten this Java code? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
/* This program sorts out name in orders from
their first alphabetical orders .*/
package nameorder;
public class NameOrder {
public static void sayName(String a, String s, String d){
System.out.println("Name By Alphabetical Order: \n1."+a+"\n"+"2."+s+"\n3."+d+"\n");
}
public static void stringOrder(String a ,String s ,String d){
int i= a.compareTo(s) ;
int j= a.compareTo(d) ;
int k= d.compareTo(s) ;
int l= d.compareTo(a) ;
String first="";
String second="";
String third="";
if(i<0&&j<0){
first=a;
if(k>0&&l>0){
third = d;
second = s;
}else{
second = d;
third = s;
}
}else if(i>0&&j>0){
third=a;
if(k<0&&l<0){
first = d;
second = s;
}else{
second = s;
first = d;
}
}else{
second=a;
if(k<0&&l<0){
first = d;
third = s;
}else{
first = s;
third = d;
}
}
sayName(first,second,third);
}
public static void main(String[] args) {
String a ="C";
String s ="a";
String d ="h";
stringOrder(a.toUpperCase(),s.toUpperCase(),d.toUpperCase());
}
}
I'm just wondering if I'm doing this right or there is a better shorter version for this?

From just the perspective of "sorting three strings", you could just need to do three comparisons and lose all those temp variables.
public static void stringOrder(String a, String s, String d) {
String tmp;
if (a.compareTo(s) > 0) {
tmp = a;
a = s;
s = tmp;
}
if (a.compareTo(d) > 0) {
tmp = a;
a = d;
d = tmp;
}
if (s.compareTo(d) > 0) {
tmp = s;
s = d;
d = tmp;
}
sayName(a, s, d);
}
But from a maintainability perspective, just use the facilities built into Java to sort multiple strings at a time:
public static void stringOrder(String a, String s, String d) {
String [] arr = {a, s, d};
java.util.ArrayList<String> list = new ArrayList<String>(Arrays.asList(arr));
java.util.Collections.sort(list);
sayName(list.get(0), list.get(1), list.get(2));
}

I used Collections.List here so that your code is more dynamic, allowing for any
amount of strings to be ordered. With yours, you hard-coded that 3 strings would be entered. Here, you can enter as many strings as you'd like within the main function.
The Collections.Sort method will sort your list in the most efficient way. Whenever you can, use methods made by the guys at Java, as they've spent years optimizing these functions.
public static void main(String[] args){
// Create a collection to store the strings in
List<String> list = new ArrayList<String>();
// Add the strings to the Collection
list.add("C");
list.add("A");
list.add("H");
// Use the Collections library to sort the strings for you, by their
// defined ordering
Collections.sort(list);
// Print the ordered strings
System.out.println("Names By Alphabetical Order: ");
for(String string: list){
System.out.println(string);
}
}

Related

How to return a class object? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I have seen ArrayList examples but I want to know how to add objects guitar and ukulele to array i.
And also, how to return the object which has the highest number of strings?
public class Demo{
public static void main(String[] args) {
Instrument guitar = new Instrument("Guitar", 6);
Instrument ukulele = new Instrument("Ukulele", 4);
Instrument i[] = new Instrument[2];
// Adding objects guitar and ukulele to class array i
// Returning object with maximum number of strings
}
}
class Instrument{
private String name;
private int numOfStrings;
public Instrument(String name, int numOfStrings){
this.name = name;
this.numOfStrings = numOfStrings;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStrings() {
return numOfStrings;
}
public void setStrings(int numOfStrings) {
this.numOfStrings = numOfStrings;
}
}
I think you are asking for this:
// Adding objects guitar and ukulele to class array i
i[0] = guitar;
i[1] = ukulele;
// Returning object with maximum number of strings
int max = i[0].getStrings();
for (Instrument inst : i) {
if(inst.getStrings() > max)
max = inst.getStrings();
}
System.out.println(max);
First of all assign the objects to the array. Then iterate them keeping track of the highest value. I suggest you to study deeper the basics of Java to solve this simple problems :)
Here's some code showing the implementation you were asking about, hope it helps (I'd suggest looking more at object and array fundamentals)
public class Demo{
public static void main(String[] args) {
Instrument guitar = new Instrument("Guitar", 6);
Instrument ukulele = new Instrument("Ukulele", 4);
Instrument i[] = new Instrument[2];
// Since you declared your array with empty elements, you'll have to get the current element and set the new vals manually (or use iteration)
i[0] = guitar;
i[1] = ukulele;
//Alternatively, you could initialise your array with the values already set like this
Instrument arr[] = new Instrument[] {guitar, ukulele};
// Returning object with maximum number of strings
Instrument highestStrung = getHighestStrungInstrument(arr);
System.out.println("Highest: " + highestStrung.getName());
}
private static Instrument getHighestStrungInstrument(Instrument[] arr){
//Var to hold current highest strings
int highestStrings = 0;
//Var to hold the obj with the current highest strings
Instrument currentHighest = null;
//loop through all the objects in the array
for(Instrument inst : arr)
//compare the current instrument's strings with that of the var's val
if(inst.getStrings() > highestStrings){
//set the new highest
currentHighest = inst;
highestStrings = inst.getStrings();
}
//Return the highest obj (Keep in mind that the val could be null)
return currentHighest;
}
}
class Instrument{
private String name;
private int numOfStrings;
public Instrument(String name, int numOfStrings){
this.name = name;
this.numOfStrings = numOfStrings;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStrings() {
return numOfStrings;
}
public void setStrings(int numOfStrings) {
this.numOfStrings = numOfStrings;
}
}

I am trying to reverse an array the user inputs like {hello, Donald, Trump} -> pmurT, dlanoD etc but it outputs [null] [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm new to java and wanted to reverse an array the user inputs (including character) so apple, banana becomes ananab, elppa. But it outputs [null]
package test;
import java.util.Arrays;
import java.util.Collections;
import javax.swing.JOptionPane;
public class WhileWarmup{
public static void main(String[] args) {
String shoppinglist = JOptionPane.showInputDialog("What do you want to manipulate");
String[]Shoppinglist = shoppinglist.split(",");
String[]Shoppinglist1 = shoppinglist.split(",");
int num = Shoppinglist.length;
String bruh = "";
String bruh1 = "";
while (num >= 0) {
Shoppinglist1 = Arrays.copyOfRange(Shoppinglist,num,num + 1);
Collections.reverse(Arrays.asList(Shoppinglist1));
bruh1 = Arrays.toString(Shoppinglist1);
bruh = bruh + bruh1;
num = num - 1;
System.out.println(bruh);
}
}
}
When it comes to reversing a String, StringBuilder#reverse is always there:
public static void main(String[] args) {
List<String> wordList = Arrays.asList("hello", "Donald", "Trump");
System.out.println(reverseListAndItsElements(wordList));
}
public static List<String> reverseListAndItsElements(List<String> list) {
List<String> reversed = new ArrayList<>(list);//Create a copy
Collections.reverse(reversed);
return reversed.stream().map(s -> new StringBuilder(s).reverse().toString())
.collect(Collectors.toList());
}
Prints:
[pmurT, dlanoD, olleh]
And in case you do not want to mess with lists:
public static void main(String[] args) {
String original = "hello,Donald,Trump";
String[] split = original.split(",");
String[] reversedSplit = new String[split.length];
IntStream.range(0, split.length).forEach(index -> {
reversedSplit[index] = new StringBuilder(split[index]).reverse().toString();
});
System.out.println(Arrays.toString(reversedSplit));
}
Try this.
String[] input = {"hello", "Donald", "Trump"};
String[] reversed = new StringBuilder(String.join(",", input))
.reverse().toString().split(",");
System.out.println(Arrays.toString(reversed));
output:
[pmurT, dlanoD, olleh]
you can use the following code
public static List<String> reverseList(List<String> list) {
List<String> reversed = new ArrayList<>(list);
Collections.reverse(reversed);
return reversed.stream().collect(Collectors.toList());
}
This code can be used for String array reverse implementation. There are many ways of reversing a string. One is using StringBuilder I have used.
public class Main
{
static String[] arr={"hello", "Donald", "Trump"};
public static void main (String[]args)
{
String[] strA= reverseTheString(arr);
for(int i=0;i<strA.length;i++){
System.out.println(""+strA[i]);
}
}
// This is actual method for reverse an array elements.
public static String[] reverseTheString(String[] arr){
String[] reverseArray=new String[arr.length];
int j=arr.length-1;
for(int i=0;i<arr.length;i++)
{
StringBuilder sb=new StringBuilder(arr[i]);
reverseArray[j]=sb.reverse().toString();
j--;
}
return reverseArray;
}
}

appending an array of string to arraylist of type Integer in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an ArrayList<Integer> called nodes. I want to assign elements from array[] to elements in ArrayList. Such that 1st element in arraylist will have first element in array as its property.. and so on. However, there are only 6 elements in array and thus for 7th element its again first element from array[]. Array is of type Integer.
public static String[] Interest = new String[] {"I1","I2","I3","I4","I5","I6"};
public static void main(String[] args){
System.out.println("Enter number of nodes");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0;i<=n;i++) {
nodes.add(i);
}
System.out.println(nodes);
}
I want to set up an interest profile for each element in node. For that I have an array called Interest which has 6 elements in it. Now say for the first element in node, I want to set up preferences for Interests. For example, the first element could have interest profile as I1 = 10, I2 = 8, ..., I6 = 2 and so on.
I am thinking of using a method like SetIntensity(ArrayList element, array of integers) which will set interest profile for an element passed as a parameter. I am not sure if it's correct but I am expecting something like this:
public static void setInterest(List<String> array){
String[] Interest = new String[]{"I1","I2","I3","I4","I5","I6"};
for(int k=0;k<array.size();k++){
array.get(k);
for(int j=0;j<Interest.length;j++){
}
}
}
Sounds like you need a Node class with a Map to store preferences.
class Node {
Integer id;
Map<String, Integer> interestPreferences;
public Node(Integer id) {
this.id = id;
this.interestPreferences = new HashMap<String, Integer>();
}
void setPreference(String key, Integer value) {
interestPreferences.put(key, value);
}
Interest getPreference(String key) {
return interestPreferences.get(key);
}
}
Then use it like this:
public static List<Node> nodes = new ArrayList<Node>();
public static String[] Interest = new String[] {"I1","I2","I3","I4","I5","I6"};
public static void main(String[] args){
System.out.println("Enter number of nodes");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0;i<=n;i++) {
Node node = new Node(i);
node.setPreference("I1", 10);
node.setPreference("I2", 8);
//....
node.setPreference("I6", 2);
nodes.add(node);
}
System.out.println(nodes);
}

Array of strings from array of pairs? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is there anyway I could return an array of strings from an array of pairs? I'm guessing it's something to do with hashmap since two values are involved. Any simple example with some explanation would help :)
As pointed out by #dasblinkenlight, if the input is (y,3),(t,2) and I want the output as "yPP","tP" where the string should have the length of the numerical value given. and so after taking the character, the rest of the length is to be filled by P.
Suppose I've got the static method,
public static Line[] get(Couple[] temp)
I need to complete it so that my main method would produce the following result:
get (new Couple[]{new Couple(ā€™eā€™,4), new Couple(ā€™nā€™,2)})
should return the array of Strings
{"ePPP", "nP"}
Hope this helps :)
class Pair{
public Pair(String st1,String st2){
string1=str;
string2=str;
}
private String string1;
private String string2;
// + getters and maybe setters for strings;
}
Later on create simple Pair[] and do whatever you want
With a Pair class implemented as
class Pair {
private final String s;
private final int i;
public Pair(String s, int i){
this.s = s;
this.i = i;
}
public String getS() {
return s;
}
public int getI() {
return i;
}
}
Initialize the Pair[] and invoke a converter method as
Pair[] pairArr = new Pair[2];
pairArr[0] = new Pair("Y", 3);
pairArr[1] = new Pair("T", 2);
System.out.println(Arrays.toString(convertPairsToStrArray(pairArr, "P")));
Output :
[YPP, TP]
Here's a sample converter implementation:
private static String[] convertPairsToStrArray(Pair[] pairArr, String padStr) {
String[] strArr = null;
if (pairArr != null) {
strArr = new String[pairArr.length];
for (int i = 0; i < pairArr.length; i++) {
String s = pairArr[i].getS();
StringBuilder sb = new StringBuilder();
if (s != null) {
sb.append(s);
int j = 0;
if ((j = pairArr[i].getI() - s.length()) > 0) {
while (j-- > 0) {
sb.append(padStr);
}
}
}
strArr[i] = sb.toString();
}
}
return strArr;
}
Like many things, the question contains the answer.
Create a class to hold the pairs. Add a method, to that class, to produce the desired output. Here is some code:
Pairzor.java:
public class Pairzor
{
private final static char FILL_CHARACTER = 'P';
private final char theChar;
private final int theCount;
public Pairzor(
final char newChar,
final int newCount)
{
theChar = newChar;
theCount = newCount;
}
public final String blammy()
{
StringBuilder buffer = new StringBuilder();
buffer.append(theChar);
for (int count = 1; count < theCount; ++count)
{
buffer.append(FILL_CHARACTER);
}
return buffer.toString();
}
}
Main.java
public class Main
{
/**
* #param args
*/
public static void main(String[] args)
{
Pairzor one = new Pairzor('y', 3);
Pairzor two = new Pairzor('t', 2);
System.out.println(one.blammy());
System.out.println(two.blammy());
}
}

java : return multiple values from a method [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return multiple objects from a Java method?
lets say N= a+b;
for a number N i want to generate the all possible values a and b. like
if N =7 a and b are (1+6),(2+5),(3+4).
i have coded this logic in a method.
static void sumofNum(int N){
for(int a=1; a<N; a++){
//a+b=N
int b = N-a;
System.out.println(a+","+b);
int next =a+1;
if(next==b | a==b)
return;
}
}
i want to return (1,6),(2,5),(3,4) from this method. next for any N there can be more (a,b) combinations to be returned from this method.
Return a List<String> (assuming "(1,6)" is to be stored as a String). Use one of the implementations of List, such as ArrayList, to construct the list:
static List<String> sumofNum(int N)
{
List<String> result = new ArrayList<String>();
for(int a=1; a<N; a++)
{
int b = N-a;
result.add("(" + a + "," + b + ")");
int next =a+1;
if(next==b || a==b)
return result;
}
return result;
}
If you want to return them as ints, define a object that contains two ints (or abuse points as I have done below) and return a list of those objects. If you define your own object, just replace point with that.
static ArrayList<Point> sumofNum(int N){
ArrayList<Point> result = new ArrayList<Point>();
for(int a=1; a<N; a++){
//a+b=N
int b = N-a;
System.out.println(a+","+b);
int next =a+1;
if(next==b | a==b)
result.add(new Point(a,b));
}
return result;
}
You can get your results from the list with:
results = sumofNum(7);
int a = results.get(0).x; //a = 1
int b = results.get(0).y; //b = 6
In an object oriented (and also functional) style of programming you can pass the result to a consumer an avoid the overhead of storing results in collections or lists.
Example:
static void sumofNum(int N){
for (int a=1; a<N; a++){
//a+b=N
int b = N-a;
consumer.consume(a,b);
int next =a+1;
if (next==b || a==b)
return;
}
}
[ Further improvements of the code are possible (e.g. avoid the inner if and return), ... ]
Consider the nos as (1,6),(2,5),(3,4)
- Now return an ArrayList<String> which contains each value in String form as "1,6" , "2,5", "3,4".
- When you receive the returned ArrayList, then use split() method "," as delimiter to get the 1 and 6 out of "1,6" and so on....

Categories

Resources