I want print single variable, array and maybe double array,
I use following code, add a type when I need it,
but ... as you see ... it works but not smart.
So, question is "Is there a smart way to print Arrays?"
import java.util.Arrays;
class Rec{
int val;
public String toString(){
return "" + val;
}
Rec(int val){this.val=val;}
}
public class Main
{
public static void main(String[] args) {
Rec r = new Rec(0);
Boolean[] ba = new Boolean[]{true, false, true, true};
Rec[] ra = new Rec[]{new Rec(1), new Rec(2), new Rec(3)};
int[][] iaa = new int[][]{{1,2,3}, {3,4,5}};
System.out.printf("r=%s ba=%s ra=%s iaa=%s \n", s(r), s(ba), s(ra), s(iaa));
}
static <T> String s(T n) {
if(n instanceof int[]){
return Arrays.toString((int[])n);
}else if(n instanceof int[][]){
return Arrays.deepToString((int[][])n);
}else if(n instanceof boolean[]){
return Arrays.toString((boolean[])n);
}else if(n instanceof boolean[][]){
return Arrays.deepToString((boolean[][])n);
}else if(n instanceof Boolean[]){
return Arrays.toString((Boolean[])n);
}else if(n instanceof Rec[]){
return Arrays.toString((Rec[])n);
//}else if(n instanceof T[]){ // error: illegal generic type for instanceof
// return Arrays.toString((T[])n);
}else{
return "" + n;
}
}
}
If you really want to customize your printing for variable arrays then why not do the following:
public static String s(Object s) {
return s.toString();
}
public static String s(Object[] s) {
return Arrays.toString(s);
}
public static String s(Object[][] s) {
return Arrays.deepToString(s);
}
// For each primitive type of your single or multi dimension
// declare the following for either single or multi dimensional
public static String s(int[][] s) {
return Arrays.deepToString(s);
}
public static String s(int[] s) {
return Arrays.toString(s);
}
But keep in mind you are basically repackaging what the API already does.
Related
My code looks like
public void convertValues(String sourceValue,String targetValue) {
if (sourceValue.equals(targetValue)) {
//dosomething
} else if (sourceValue.equals(value1) && targetValue.equals(value2)) {
//dosomething
} else if (sourceValue.equals(value2) && targetValue.equals(value1)) {
//dosomething
}
}
like that I have some 40 condition, I know writing those if else condition is stupidity.
Is it good approach to use enums or hashmaps?
To speedup entering a spaghetti code, you probably need to prepare a helper class that would simplify adding the repeated lines.
If you don't like using else if, use return; (Caution: snobbish people are allergic to seeing return not at the end).
Use a helper class / method for checking values.
Example:
public class Main {
String value1 = "a";
String value2 = "b";
String value3 = "c";
String value4 = "d";
// use a nested private class where you could add all long
// and repetitive methods that need to be done
// with source and target
private class Helper {
private String src;
private String tgt;
Helper(String src, String tgt) {
this.src = src;
this.tgt = tgt;
}
public boolean eq(String val, String val1) {
return src.equals(val) && tgt.equals(val1);
}
// add other repetitive functions here
}
public void convertValues(String sourceValue, String targetValue) {
// use a simple name for the helper class.
Helper $ = new Helper(sourceValue, targetValue);
if (sourceValue.equals(targetValue)) {
// put your execution lines into a separate method.
// this way, it will become reusable and much easier to maintain
// call a method1
return;
}
if ($.eq(value1, value2)) {
// call a method2
return;
}
if ($.eq(value2, value1)) {
// call a method3
return;
}
if ($.eq(value1, value3)) {
// call a method4
return;
}
// ....
}
// public void method1()
// public void method2()
public static void main(String[] args) throws java.lang.Exception {
// Everything else
}
}
Using lambda expressions in Java 8, it can be implemented like:
Define Value class:
public class Value {
private final String value1;
private final String value2;
// Function to exetute
private final BiConsumer<String, String> f;
public Value(String value1, String value2, BiConsumer<String, String> f) {
super();
this.value1 = value1;
this.value2 = value2;
this.f = f;
}
public boolean execute(String src, String tgt) {
if(src.equals(value1) && tgt.equals(value2)) {
f.accept(src, tgt);
return true;
}
return false;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value1 == null) ? 0 : value1.hashCode());
result = prime * result + ((value2 == null) ? 0 : value2.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Value other = (Value) obj;
if (value1 == null) {
if (other.value1 != null)
return false;
} else if (!value1.equals(other.value1))
return false;
if (value2 == null) {
if (other.value2 != null)
return false;
} else if (!value2.equals(other.value2))
return false;
return true;
}
}
// Initialize values
Set<Value> values = new HashSet<>();
values.add(new Value("value1", "value2", (src, tgt) -> {/* do something here */}));
values.add(new Value("value2", "value1", (src, tgt) -> {/* do something here */}));
values.add(new Value("value4", "value5", (src, tgt) -> {/* do something here */}));
// Execute
if (sourceValue.equals(targetValue)) {
//dosomething
} else {
for(Value v:values) {
if(v.execute(src, tgt)) {
break;
}
}
}
Currently trying to find a little information on how to find an index of a substring in an existing string. For instance if my String was "HelloWorld" and my Substring passed to my method was "world" the return index would be 5. I don't want to use the indexOf method simply because I want to actually learn how the indexOf method actually works from scratch.
public class TestMiniString
{
public static void main(String[] args)
{
String n1 = new String("Helloworld, welcome");
System.out.println(n1.findIndexOf("wo"));
System.out.println(n1.findIndexOf("we"));
System.out.println(n1.findIndexOf("llo"));
}
public class MiniStr
{
private String str;
public MiniStr(String x)
{
this.str = x;
}
public int findIndexOf(String x)
{
}
}
I believe you want to do something like this..
Edited: this should check if there is a substring in your objects string which is equal to the parameter, and if yes returns the starting index, otherwise return -1
public class TestMiniString {
public static void main(String[] args) {
MiniStr n1 = new MiniStr("Helloworld");
System.out.println(n1.findIndexOf("wo"));
}
public class MiniStr {
private String str;
public MiniStr(String x){
this.str = x;
}
public getStr() {
return this.str;
}
public int findIndexOf(String sub) {
for (int i=0; i<getStr().length(); i++) {
if (getStr().charAt(i) == sub.charAt(0)) {
int sumEq = 1;
for (int j=1; j<sub.length(); j++) {
if (sub.charAt(j) != getStr().charAt(i+j)) break;
else sumEq++;
}
if (sumEq == sub.length()) return i;
}
}
return -1; //in case it is not an actual substring
}
}
You can learn how indexOf method actually works in here
ECMAScript 5.1 (ECMA-262)
Is there a single line implementation for the getInt method?
If not - can one implement it without using instanceof?
public class ParseInt {
public static void main(String[] args) {
Object intArr[] = { "131", 232, new Integer(333) };
for (Object intObj : intArr) {
System.out.println(getInt(intObj));
}
}
private static int getInt(Object obj) {
return // ???
}
}
Use Integer.valueOf(obj.toString)
private static int getInt(Object obj) {
return Integer.valueOf(obj.toString());
}
This will work for your object array
Try something like...
private static int getInt(Object obj) {
if (obj instanceof String) {
return Integer.parseInt((String) obj);
} else if(obj instanceof Integer){
return (Integer) obj;
} else{
return 0; // or else whatever you want
}
}
Is there a "typeof" like function in Java that returns the type of a primitive data type (PDT) variable or an expression of operands PDTs?
instanceof seems to work for class types only.
Try the following:
int i = 20;
float f = 20.2f;
System.out.println(((Object)i).getClass().getName());
System.out.println(((Object)f).getClass().getName());
It will print:
java.lang.Integer
java.lang.Float
As for instanceof, you could use its dynamic counterpart Class#isInstance:
Integer.class.isInstance(20); // true
Integer.class.isInstance(20f); // false
Integer.class.isInstance("s"); // false
There's an easy way that doesn't necessitate the implicit boxing, so you won't get confused between primitives and their wrappers. You can't use isInstance for primitive types -- e.g. calling Integer.TYPE.isInstance(5) (Integer.TYPE is equivalent to int.class) will return false as 5 is autoboxed into an Integer before hand.
The easiest way to get what you want (note - it's technically done at compile-time for primitives, but it still requires evaluation of the argument) is via overloading. See my ideone paste.
...
public static Class<Integer> typeof(final int expr) {
return Integer.TYPE;
}
public static Class<Long> typeof(final long expr) {
return Long.TYPE;
}
...
This can be used as follows, for example:
System.out.println(typeof(500 * 3 - 2)); /* int */
System.out.println(typeof(50 % 3L)); /* long */
This relies on the compiler's ability to determine the type of the expression and pick the right overload.
You can use the following class.
class TypeResolver
{
public static String Long = "long";
public static String Int = "int";
public static String Float = "float";
public static String Double = "double";
public static String Char = "char";
public static String Boolean = "boolean";
public static String Short = "short";
public static String Byte = "byte";
public static void main(String[] args)
{
//all true
TypeResolver resolver = new TypeResolver();
System.out.println(resolver.getType(1) == TypeResolver.Int);
System.out.println(resolver.getType(1f) == TypeResolver.Float);
System.out.println(resolver.getType(1.0) == TypeResolver.Double);
System.out.println(resolver.getType('a') == TypeResolver.Char);
System.out.println(resolver.getType((short) 1) == TypeResolver.Short);
System.out.println(resolver.getType((long) 1000) == TypeResolver.Long);
System.out.println(resolver.getType(false) == TypeResolver.Boolean);
System.out.println(resolver.getType((byte) 2) == TypeResolver.Byte);
}
public String getType(int x)
{
return TypeResolver.Int;
}
public String getType(byte x)
{
return TypeResolver.Byte;
}
public String getType(float x)
{
return TypeResolver.Float;
}
public String getType(double x)
{
return TypeResolver.Double;
}
public String getType(boolean x)
{
return TypeResolver.Boolean;
}
public String getType(short x)
{
return TypeResolver.Short;
}
public String getType(long x)
{
return TypeResolver.Long;
}
public String getType(char x)
{
return TypeResolver.Char;
}
}
There are two ways that you can use to determine the type of the Primitive type.
package com.company;
public class Testing {
public static void main(String[] args) {
int x;
x=0;
// the first method
System.out.println(((Object)x).getClass().getName());
if (((Object)x).getClass().getName()=="java.lang.Integer")
System.out.println("i am int");
// the second method it will either return true or false
System.out.println(Integer.class.isInstance(x));
}
}
So I'm trying to write a method that reverses a given string but the catch is that it has to be a void method rather than a return method which is making this difficult. My code seems logical to me but it doesn't work so I'm hoping someone can help me figure out where I'm going wrong.
public class Reverser {
public String text, revText;
/**
* #param args
*/
public static void main(String[] args) {
Reverser greeting = new Reverser("Buildings");
greeting.reverse();
System.out.println(greeting.getText());
}
public Reverser(String _text){
text = _text;
}
public void reverse(){
int len = text.length();
if(len >= 1){
String last = text.substring(text.length() - 1, text.length());
revText += last;
text = text.substring(0, text.length() - 1);
Reverser loop = new Reverser(text);
loop.reverse();
}
}
public String getText(){
return revText;
}
}
Here's an idea:
public class Reverser {
private int idx;
private String text, revText;
public static void main(String[] args) {
Reverser greeting = new Reverser("Buildings");
greeting.reverse();
System.out.println(greeting.getText());
}
public void reverse() {
if (idx == text.length())
return;
revText = text.charAt(idx) + revText;
idx++;
reverse();
}
public Reverser(String _text) {
idx = 0;
text = _text;
revText = "";
}
public String getText() {
return revText;
}
}
The fundamental difference with respect to your answer, is that I'm using an index attribute to keep track of where exactly I am in the recursion. In that way, I don't have to modify the original text attribute.
A slighty different version to what Oscar Lopez responded is this
public class Sentence{
private String sntce, rvrse;
private int idx;
public Sentence(String sentence){
sntce = sentence;
rvrse = "";
}
/**
A method to reverse a string recursively.
#return void.
*/
void reverse(){
if (idx == sntce.length()){
sntce = rvrse;
return;
}
rvrse = sntce.charAt(idx) + rvrse;
idx++;
reverse();
}
/**
To test reverse gives the appropriate value.
#return the value of sntce.
*/
public String getText(){
return sntce;
}
}
Here's a version that uses as few instance variables as possible. Unfortunately you need at least one instance variable to hold the final result (result). Otherwise the state is passed into each recursive call.
(PS, is this homework?)
public class RecursiveVoidStringReverser {
public static void main(String[] args) {
final RecursiveVoidStringReverser reverser = new RecursiveVoidStringReverser();
reverser.reverse("Welcome to the jungle!");
System.out.println("reverser.result = " + reverser.result());
}
private String result;
public void reverse(String s) {
if ("".equals(s)) {
result = s;
} else {
reverse(s.toCharArray(), 0);
}
}
private void reverse(char[] chars, int index) {
if (index > chars.length / 2) {
result = new String(chars);
} else {
char t = chars[index];
chars[index] = chars[chars.length - index - 1];
chars[chars.length - index - 1] = t;
reverse(chars, index+1);
}
}
public String result() {
return result;
}
}
Given that a string is immutable, you cannot change it in situ. If the only requirement is that there be no return value, and it's okay simply to print out the final string (or to place it into a class variable), then this would work fine for any strings of at least one character:
public static void main(String args[])
{
reverse("", "original string");
}
public static void reverse(String reversed, String original)
{
if(original.length() <= 1)
{
System.out.println(original.charAt(0) + reversed);
// (or set it into a shared variable)
return;
}
reverse(original.charAt(0) + reversed, original.substring(1));
}
This solution is going for procedural simplicity, not memory efficiency. This produces quite an unpleasant memory footprint, essentially creating two in-memory strings for each character in the original. It is, however, very logically simple.
Of course, if you're just dumping out to console, then you can achieve the same thing using an algorithm that's pretty much the same as one with a return value:
public static void reverse(String original)
{
if(original.length() < 1) return;
System.out.print(original.charAt(original.length() - 1));
reverse(original.substring(0, original.length() - 1));
}