how can i print the result without brackets
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int i=0; i < n; i++){
arr[i] = in.nextInt();
}
int[] reverse =new int[n];
for (int i = 0; i < reverse.length; i++) {
reverse[i]=arr[arr.length-1-i];
}
in.close();
}
}
In java8, you can conveniently do any kind of String output using join, there you will have to do some manual reversing though:
String output = String.join(", ", arr);
You can't change the implementation of Arrays.toString() so you can't print your array like that.
Although, you can assign it to an string variable and then manipulate that string as you desire.
String str = Arrays.toString(reverse);
str = str.substring(1, str.length() - 1);
Related
This question already has answers here:
Removing duplicates from a string
(7 answers)
Closed 2 years ago.
i have tried this
public static void duplicateRemover(){
//removes all the duplicate words in a string from the user
//ask the user to enter his/her input
System.out.println("Enter your sentence: ");
//get user input
Scanner string = new Scanner(System.in);
String UserInput = string.nextLine();
//add comas into string and create an array
String[] arrayString = UserInput.split(",");
System.out.print(Arrays.toString(arrayString));
//create a new array that stores the non duplictes
String[] newArray = new String[arrayString.length];
Arrays.asList(newArray);
//loop through array to find duplicates
for (int i = 0 ; i < arrayString.length; i ++){
for (int j = 0; i < arrayString.length; i ++){
//try to remove duplicates
if (i != j){
//this is tha part i am struggling with, how would i removes a duplicate after looping through he array
String a = Integer.toString(i);
String b = Integer.toString(j);
newArray.add(a);
}
This seems to be the easier way:
List<String> arr = Arrays.asList(source.split("\\s"));
Set<String> distincts = new LinkedHashSet<>(arr);
String result String.join(" ", distincts);
Rewriting above using Java 8 streams
public void duplicateRemover() {
String source = "my name is this and that this and that";
List<String> distincts = Arrays.stream(source.split("\\s")).distinct().collect(Collectors.toList());
String result = String.join(" ", distincts);
System.out.println(result);
}
In Array It will work
public class RemoveDuplicateInArrayExample{
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1];
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}
public static void main (String[] args) {
int arr[] = {10,20,20,30,30,40,50,50};
int length = arr.length;
length = removeDuplicateElements(arr, length);
//printing array elements
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}
My code is as below. It first takes input from user and prints it in reverse. I'm new to Java. I achieve this by using two 'for loops' to first iterate through the input and another for-loop to print the numbers in reverse. My question is if there's any way to improve my code - by using just a single loop perhaps? Any suggestion is appreciated. Thank you.
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for (int arr_i = 0; arr_i < n; arr_i++) {
arr[arr_i] = in.nextInt();
}
for (int reverse_i = n-1; reverse_i >= 0; reverse_i--) {
System.out.print(arr[reverse_i]);
if (reverse_i != 0) {
System.out.print(" ");
}
}
}
An example input:
4
1 2 3 4
Expected output:
4 3 2 1
Use a StringBuilder and always insert at 0 index.
See: Oracle » JavaDocs » 1.7 » java.lang.StringBuilder.insert(int, int)
StringBuilder bld = new StringBuilder();
for (int arr_i = 0; arr_i < n; arr_i++) {
int i = in.nextInt();
bld.insert(0, i);
}
System.out.println(bld.toString());
The simplest approach I found is to use String Builder here:
Scanner in = new Scanner(System.in);
StringBuilder stringBuilder = new StringBuilder();
while (in.hasNext()) {
stringBuilder.append(in.next());
if(in.hasNext()) {
stringBuilder.append(" ");
}
}
System.out.print(stringBuilder.reverse());
First, you might reverse your elements as you insert them in the array. Then, assuming you are using Java 8+, you could use an IntStream instead of a loop and print with a basic Collector. Like,
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
IntStream.range(0, n).forEachOrdered(i -> arr[n - i - 1] = in.nextInt());
System.out.println(IntStream.of(arr).mapToObj(String::valueOf)
.collect(Collectors.joining(" ")));
I am not sure about the requirements of your request, but you do not necessarily have to use an array for this. You can concatenate the inputs into a String in reverse order like so.
public static void main(String[] args) {
System in = new Scanner(System.in);
int n = in.nextInt();
String allNumbers = "";
for (int i = 0; i < n; i++) {
int current = in.nextInt();
allNumbers = current + " " + allNumbers;
}
if(allNumbers != ""){
allNumbers = allNumbers.substring(0,allNumbers.length()-1);
}
System.out.println(allNumbers);
}
Java has inbuilt String method for the same. If your input is a String, you can use the below-
String s1 = new String("new");
String s2 = s1.reverse();
System.out.println(s2) // wen
I know this is a basic question but I have been trying hard to find Which method I can use if I have to take 2 {123,456} as the input from console where 2 is the number of inputs to the array and {123,456} are inputs to the array. Should I be using Regex for this since it has { symbols or can it be done by scanner alone??
You can read the array part as String and then strip the curly braces using substring. Convert the String to int and store into an array.
import java.util.Scanner;
public class ReadArray {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int count = read.nextInt();
String arrayLine = read.next();
int array[] = new int[count];
String elements[] = arrayLine.split(",");
elements[0] = elements[0].substring(1);
elements[count-1] = elements[count-1].substring(0, elements[count-1].length()-1);
for (int i=0; i<count; i++) {
array[i] = Integer.parseInt(elements[i]);
}
for (int i : array) {
System.out.println(i);
}
}
}
Input :
2 {123,456}
Output :
123
456
Assuming you have read the input as a string, you can do the following:
String[] inputs = input.split(" ");
int arrayLength = Integer.parseInt(inputs[0]);
String inputStringData = inputs[1].substring(1, inputs[1].length());
String[] arrayElements = inputStringData.split(",");
int[] array = new int[arrayLength];
for(int i=0; i<array.length; i++) {
array[i] = Integer.parseInt(arrayElements[i]);
}
I need help sorting this array in alphabetical order using the bubble sort algorithm.
My code is:
public class Strings
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t=0; t<t1.length-1; t++)
{
for (int i = 0; i<t1.length -1; i++)
{
if(t1[i+1].compareTo(t1[1+1])>0)
{
tempStr = t1[i];
t1[i] = t1[i+1];
t1[i+1] = tempStr;
}
}
}
for(int i=0;i<t1.length;i++)
{
System.out.println(t1[i]);
}
}
}
The code compiles, but it does not sort alphabetical. Please help me.
You have three errors in your code.
The first error is in the inner for loop, in the place where you do the check statement, it should be i < t1.length - t -1 not i < t1.length -1. You subtract t because you do not want to loop through the whole array again, only the first part of it.
The second and third errors are in the if statement. You need to turn the greater than symbol into a lesser than symbol, because the way you have the compareTo method set up, it will return a negative number.
The other error in this line is that in the compareTo parameter you put 1 + 1 it actually should be just i, because you want one less than the object it is comparing to.
The fixed working code is below (Comments are what you originally had):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String tempStr;
System.out.print("Enter the strings > ");
String s1 = new String(reader.nextLine());
String[] t1 = s1.split(", ");
for (int t = 0; t < t1.length - 1; t++) {
for (int i= 0; i < t1.length - t -1; i++) {
if(t1[i+1].compareTo(t1[i])<0) {
tempStr = t1[i];
t1[i] = t1[i + 1];
t1[i + 1] = tempStr;
}
}
}
for (int i = 0; i < t1.length; i++) {
System.out.println(t1[i]);
}
}
please change
String[] t1 = s1.split(", ");
to
String[] t1 = s1.split("");
This will solve the issue.
My main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf("First integer: %s \n", firstInt.display());
}
LargeInteger class:
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result = "";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
You did not instantiate your array. You need something like:
private int[] intArray = new int[SIZE];
where size is the length of your array.
You are not initialize the array intArray, that way you are getting error, here is the complete program
import java.util.Scanner;
class TestForNull {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf ("First integer: %s \n", firstInt.display());
}
}
and this is LargeInteger
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result="";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
private int[] intArray;
Member variables are null by default, so you need to initialize this.
Most likely you want it the same size as your string:
public LargeInteger(String s) {
intArray = new int[s.length()]; // Create the actual array before you try to put anything in it
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
Or you should use a container that resizes itself, like ArrayList.
Diferent approach through Integer.parseInt
Integer.parseInt("yourInt");
To achieve your goal:
String a = "12345667788" //sample
String b = "";
int [] vecInt = new int[a.length()]; // The lack of initialization was your mistake as the above stated
for(int i=0; i< a.length(); i++)
{
b = a.substring(0,1);
a= a.substring(1);
vecInt[i] = Integer.parseInt(b);
}
Please be aware of Double, long have far higher range then Integer which might be enough in your case to avoid an array!
you forgot to initialize the array intArray
I would recommend to use a java.util.List
You forgot to initialize the array. You have written it in constructor and the variables declared in method or constructor needs to be initialize at the same time.
Note : Implementing your logic in Constructor is not recommended unless and until you dont have any other choice.