Unexpected output while splitting and parsing a string into int (Java) [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 5 years ago.
public static void main (String args[]) {
Scanner io = new Scanner(System.in);
int a = io.nextInt();
io.nextLine();
for(int i = 0; i < a; i++ ) {
String input = io.nextLine();
String[] splitArr = input.split("\\s+");
int p[] = new int[input.length()];
int q = 0;
for (String par : splitArr) {
System.out.println(par);
p[q++] = Integer.parseInt(par);
System.out.println(p);
}
Sort(p);
}
}
The input: 2 121213
Output: 121213 [I#1f96302
The last line shows the array stored in p[]. That is incorrect. Help someone!

Your print line is incorrect, your print line should be:
System.out.println(Arrays.toString(p));
You also increment q in a wrong way, your increment code should be like:
p[q] = Integer.parseInt(par);
q++;
System.out.println(p);

Related

How to take multiple input using nextLine in java [duplicate]

This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(15 answers)
Closed 2 years ago.
I am getting error while running the below code "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0"
And I want to know the difference between next() and nextLine() method.
//Scanner
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
int q=sc.nextInt();
String str[] = new String[q];
for(int i=0;i<q;i++)
{
str[i] = sc.nextLine();
}
sc.next();
for(int i=0;i<q;i++){
System.out.println(str[i]);
if(str[i].charAt(0) == 'I' ){
String s1[] = str[i].split("\\s+");`enter code here`
System.out.println(s1[0]);`enter code here`
int value = Integer.valueOf(s1[1]);
arr[value]+= 1;
}
if(str[i].charAt(0) == 'U'){
String aa ="aman 2";
String s2[]= aa.split("\\s+");
int pos = Integer.valueOf(s2[1]);
int val = Integer.valueOf(s2[2]);
arr[pos] = val;
}
if(str[i].equalsIgnoreCase("left"))
{
int j = 0;
int tmp = arr[0];
for(j=0;j<n-1;j++){
arr[j]=arr[j+1];
}
arr[j]=tmp;
}
if(str[i].equalsIgnoreCase("right")){
int k = 0;
int temp = arr[0];
for(k=0;k<n-1;k++){
arr[k]=arr[k+1];
}
arr[k]=temp;
}
if(str[i].equals('?')){
String s4[] = str[i].split("\\s+");
int position = Integer.valueOf(s4[1]);
System.out.println(arr[position]);
}
}
I think the problem is the following line:
if(str[i].charAt(0) == 'I' ){
If str is an empty String, you cannot get the first character. You can test ifa String is empty by using .isEmpty().
Scanner#nextLine() reads (as the name says) the next line from an InputStream(in your case System.in).
Scanner#next() can read the next line butit can also read less. It reads until it reaches certain delimitors.
You can configure the delimitors. By default, it splits by delimitors like spaces, line breaks etc.

Java--make changes on argument without returning a new variable [duplicate]

This question already has answers here:
Modify an array passed as a method-parameter
(4 answers)
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 3 years ago.
I am trying to reverse words in a String in Java. It is initialliy passed as a char array. The way I tried is to convert it into a String array, make the change, and convert it back to a char array. However, changes are not made to the original array that is passed in as an argument, even if I tried to refer the new array to the original one. How do I handle this situation when we have to make modifications to the argument without returning anything in the function? Thanks.
public static void main(String[] args) {
char[] s = new char[] {'t','h','e',' ','s','k','y',' ','i','s',' ','b','l','u','e'};
reverseWords(s);
System.out.println(s);
}
public static void reverseWords(char[] s) {
String str = new String(s);
String [] strArray = str.split(" ");
int n = strArray.length;
int begin;
int end;
int mid = (n-1)/2;
for (int i=0; i<=mid; i++) {
begin = i;
end = (n-1) -i;
String temp = strArray[begin];
strArray[begin] = strArray[end];
strArray[end] = temp;
}
String s_temp = Arrays.toString(strArray).replace("[", "").replace("]", "").replace(",", "");
s = s_temp.toCharArray();
System.out.println(s);
}
You can't do s = ....
But, you can insert the characters into the existing s array and the caller will see the changed values.
Replace this:
s = s_temp.toCharArray();
with:
for(int i = 0; i < s_temp.length(); i++) {
s[i] = s_temp.charAt(i);
}
or use System.arraycopy().

Java text reverse [duplicate]

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 4 years ago.
I am just a beginner and do not know how to reverse text that I write on input so it is reversed on output. I wrote something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] pole = {s};
for (int i = pole.length; i >= 0; i--) {
System.out.print(pole[i]);
} // TODO code application logic here
}
}
but it is not working and I cannot figure out why.
Welcome to SO and java world.
As I understand the problem is not only reversing a String. The problem is also you do not know about Strings and arrays.
Let's see your code line by line;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read a String
String s = sc.nextLine();
// Put String into an array
String[] pole = { s };
// pole's length is 1, because pole has only one String
for (int i = pole.length; i > 0; i--) {
// pole[i-1] is the input String
// System.out.print(pole[i]); // pole[i] get java.lang.ArrayIndexOutOfBoundsException
System.out.print(pole[i - 1]); // this will print input string not reverse
}
// To iterate over a String
for (int i = s.length() - 1; i >= 0; i--) { // iterate over String chars
System.out.print(s.charAt(i)); //this will print reverse String.
}
}
Also as given on comments, Java have ready methods to reverse a String. Like;
new StringBuilder(s).reverse().toString()

Break down a long string into smaller string of given length [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I am trying to break down a long given string into a smaller string of given length x, and it returns an array of these small strings. But I couldn't print out, it gives me error [Ljava.lang.String;#6d06d69c
Please take a look at my code and help me out if I am doing wrong. Thanks so much!
public static String[] splitByNumber(String str, int num) {
int inLength = str.length();
int arrayLength = inLength / num;
int left=inLength%num;
if(left>0){++arrayLength;}
String ar[] = new String[arrayLength];
String tempText=str;
for (int x = 0; x < arrayLength; ++x) {
if(tempText.length()>num){
ar[x]=tempText.substring(0, num);
tempText=tempText.substring(num);
}else{
ar[x]=tempText;
}
}
return ar;
}
public static void main(String[] args) {
String[] str = splitByNumber("This is a test", 4);
System.out.println(str);
}
You're printing the array itself. You want to print the elements.
String[] str = splitByNumber("This is a test", 4);
for (String s : str) {
System.out.println(s);
}

Program skips everyother line, but not sure why [duplicate]

This question already has answers here:
Scanner skipping every second line from file [duplicate]
(5 answers)
Closed 4 years ago.
My program prints all the data on the line, but only prints every other line. I know that it has something to do with the "nextLine", but I cannot find whats causing the problem.
import java.io.*;
import java.util.*;
public class hw2
{
public static void main (String[] args) throws Exception
{
String carrier;
int flights;
int lateflights;
int ratio;
String[][] flightData= new String [221][3];
String[] temp;
File file = new File ("delayed.csv");
Scanner csvScan = new Scanner(file);
int c = 0;
while ((csvScan.nextLine()) != null){
String s = csvScan.nextLine();
temp = s.split(",");
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
flightData[c][0] = temp[1];
flightData[c][1] = temp[6];
flightData[c][2] = temp[7];
c = c+1;
}
}
}
Consider this approach (see doc here):
Scanner csvScan = new Scanner(file);
while (csvScan.hasNextLine()) {
String s = csvScan.nextLine();
// for testing
System.out.println(s);
// ... rest of code
}

Categories