Printing contents of a char array gives outofbound exception - arrays

I'm trying to get the mid, first & last character of a string. Here is what i've done. I'm not sure about what exactly need to be done.
import java.util.*;
class Test11{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String input=sc.nextLine();
int length=input.length();
int even_odd=length%2;
if(even_odd==1){
int mid=length/2;
char mid_letter[]=input.toCharArray();
int first=0; int last=length;
System.out.println(mid_letter[mid]+mid_letter[first]+mid_letter[last]);
}
else System.out.println("Even String has no mid point. Try Again!");
}

Your last variable needs to be
last = length-1
since java is '0 based'.

Related

string accept error name accept part getting skipped

This is the my code and the problem is using array i am taking names and their marks input and want to print then serially but the name accepting part is not working it is taking number inputs but not the names
import java.util.Scanner;
public class ST_test
{
public static void main(String[] args)
{
int i;
Scanner sc= new Scanner(System.in);
String a[]= new String[5];
int num[]= new int[5];
for(i=0;i<5;i++)
{
System.out.println("position mrks"+i);
num[i]=sc.nextInt();
System.out.println("position name "+i);
a[i]=sc.nextLine();
}
for(i=0;i<5;i++)
{
System.out.print(" "+a[i]+" ");
System.out.print(" "+num[i]+" ");
}
}
}
I used to encounter this error early on in my Java journey. The problem is with the Scanner class, probably a bug.
The solution that I used was to create 2 scanner class objects. One for the numeric values and the other for String values. Here is the modified code:-
import java.util.Scanner;
public class ST_test
{
public static void main(String[] args)
{
int i;
Scanner sc= new Scanner(System.in);
Scanner sc1 = new Scanner(System.in); // new scanner object for Strings
String a[]= new String[5];
int num[]= new int[5];
for(i=0;i<5;i++)
{
System.out.println("position mrks"+i);
num[i]=sc.nextInt();
System.out.println("position name "+i);
a[i]=sc1.nextLine();
}
for(i=0;i<5;i++)
{
System.out.print(" "+a[i]+" ");
System.out.print(" "+num[i]+" ");
}
}
}
While this helps, it would be better to switch to BufferedReader and BufferedWriter class :)

make a for loop update twice

i want to print out the four chinese letters over and over again one at a time
package matrixArrayLoop;
public class MatrixArrayLoop {
public static void main(String[] args) {
char[] kai = {'开', '凯', '開', '楷'};
int i=0;
for(i=0;i<kai.length;i++)
System.out.println(kai[i]);
if(i==kai.length)
i=0;
}
}
i used a while loop with an if and bracketed them so they would run
char[] kai = {'开', '凯', '開', '楷'};
int i=0;
while(i<=kai.length) {{{
System.out.println(kai[i]);}
i++;}
if(i==kai.length)
i=0;}

Why isn't my write method initialised?

I have been trying to write words that are given by the user in the command shell,but for some reason my program instantly quits after the read() function,so the text in main() :"in main2\n" is never even written. I have been trying to locate my problem for about an hour now and can't seem to find it.
# include <stdio.h>
void write_zin(const char* zin,int length_zin){
const char * runner =zin;
printf("out of loop\n");
while(runner!=(runner+length_zin)){
printf("%c",*runner);
runner++;
}
}
void read(char* zin,int NUMBER_LETTERS,int NUMBER_WORDS){
int i ;
char woord[NUMBER_LETTERS+1];
zin[0]='\0';
for(i =0;i<NUMBER_WORDS;i++){
printf("Give a word with %i letters\n",NUMBER_LETTERS);
scanf("%s",woord);
strcat(zin,woord);
strcat(zin,'\0');
}
strcat(zin,'\0');
}
int main(){
const int NUMBER_LETTERS = 5;
const int NUMBER_WORDS = 2;
char zin[(NUMBER_LETTERS+1)*NUMBER_WORDS];
printf("in main 1\n");
read(zin,NUMBER_LETTERS,NUMBER_WORDS);
printf("in main 2\n");
write_zin(zin,(NUMBER_LETTERS+1)*NUMBER_WORDS);
printf("in main3\n");
return 0;
}
There are a couple errors in your code:
Function void read(char* zin,int NUMBER_LETTERS,int NUMBER_WORDS)
If you concatenate words separated by '\0' you will end having just one string, because every string function will stop at the first '\0' and will not process further characters. So you cannot use strcat(zin,'\0');
If you want to mark the separation between strings use another special character as '\n' The final function will be:
void read(char* zin,int NUMBER_LETTERS,int NUMBER_WORDS){
int i ;
char woord[NUMBER_LETTERS+1];
for(i =0;i<NUMBER_WORDS;i++){
printf("Give a word with %i letters\n",NUMBER_LETTERS);
scanf("%s",woord);
strcat(zin,woord);
}
}
2. Function void write_zin(const char* zin,int length_zin)
You cannot ever change the condition of a loop inside a loop. That is what you are doing, because runner is always changing inside the loop, and in addition it is part of your condition.
while(runner!=(runner+length_zin)){
printf("%c",*runner);
runner++;
}
The final function is:
void write_zin(const char* zin,int length_zin){
const char * runner =zin;
printf("out of loop");
while(*runner){
printf("'%c'",*runner);
runner++;
}
}

Program that gets input and reverse the string

My code is suppose to use loops only, I am suppose to make a string reverse and return that reverse value. I have a problem return the reverse value and I have no clue how to do it.`
public static String reverseString(String str){
for(int i =str.length()-1;i>=0;i--)
return str.charAt(i);// This wont return the value, gives me a error
// any tips?
}
Assuming you use Java you can change your code to this:
public static String reverseString(String str){
StringBuilder sb = new StringBuilder();
for(int i =str.length()-1;i>=0;i--){
sb.append(str.charAt(i));
}
return sb.toString();
}
The change is that you create a StringBuilder object. The code you posted tries to return the first char you extract from your string which is not what you want. You want to build the string in reverse, so in each iteration you add the next reversed char to your StringBuilder, and when the loop terminates, you return the string representation of the StringBuild by using toString().
You can do this implementation smarter and faster, but I assume that this task is part of a learning process, so it is more important that you understand why your code should not place a return statement in a loop, when you actually want the loop to iterate multiple times and save each intermediate result before returning anything.
Documentation:
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
UPDATE:
Based on ohiodoug's comment about StringBuilder it would be appropriate to also show how it is done without the StringBuilder class:
import java.lang.StringBuilder;
public class Main
{
public static void main(String [ ] args){
String resultSimple = simpleReverseString("Hello World!");
String resultSB = betterReverseString("Hello World!");
System.out.println(resultSimple);
System.out.println(resultSB);
//Prints:
//!dlroW olleH
//!dlroW olleH
}
//Simple string concatenation.
//Uses the += operator.
//Since s is already a String we don't need to use
//toString() on it.
public static String simpleReverseString(String str){
String s = "";
for(int i =str.length()-1;i>=0;i--){
//s += str.charAt(i) is equal to
//s = s + str.charAt(i)
s += str.charAt(i);
}
return s;
}
//Same as simpleReverseString, but uses the StringBuilder class
public static String betterReverseString(String str){
StringBuilder sb = new StringBuilder();
for(int i =str.length()-1;i>=0;i--){
sb.append(str.charAt(i));
}
return sb.toString();
}
}
Updated answer:
public static String reverseString(String str){
char[] temp = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
temp[i] = str.charAt(str.length() - (i + 1));
}
return new String(temp);
}
Good luck!

how to solve Java heap space Exception for ArrayList Size?

When i run the below program which displays subsets of a given array, where array size is <=19 , it works fine. But if array size >19 it throws Java Heap Space Exception. How to overcome this problem in order to get subsets where array size > 19?
import java.lang.*;
import java.util.*;
class def
{
static List<List<Integer>> subset(int ele,List<List<Integer>> w)
{
if(w.size()==0)
{
List<Integer> temp=new ArrayList<Integer>();
temp.add(ele);
w.add(temp);
}
else
{
int i,len=w.size();
for(i=0;i<len;i++)
{
List<Integer> temp=new ArrayList<Integer>();
for(Integer agh:w.get(i))
{
temp.add(agh);
}
temp.add(ele);
w.add(temp);
}
List<Integer> ghi=new ArrayList<Integer>();
ghi.add(ele);
w.add(ghi);
}
return w;
}
static void sub(int set[])
{
List<List<Integer>> ints = new ArrayList<List<Integer>>();
int len=set.length,i;
for(i=0;i<len;i++)
{
ints=subset(set[i],ints);
}
int count=0;
for(List<Integer> temp:ints)
{
System.out.println("SET---"+count++);
for(Integer agh:temp)
{
System.out.println(agh);
}
}
}
public static void main(String args[])
{
int a[]={3,4,9,14,15,19,28,37,47,50,54,56,59,61,70,73,78,81,92,95,97,99};
sub(a);
}
}
Here is the exception:
C:\Program Files (x86)\Java\jdk1.6.0_07\bin>javac def.java
C:\Program Files (x86)\Java\jdk1.6.0_07\bin>java def
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:2760)
at java.util.Arrays.copyOf(Arrays.java:2734)
at java.util.ArrayList.ensureCapacity(ArrayList.java:167)
at java.util.ArrayList.add(ArrayList.java:351)
at def.subset(def.java:22)
at def.sub(def.java:39)
at def.main(def.java:55)
It seems that you are making too much instance of ArrayList. You can increase the heap size. but I think you can make a small modification in your code
else
{
int i,len=w.size();
List<Integer> temp=new ArrayList<Integer>(); ///reuse this arraylist
for(i=0;i<len;i++)
{
for(Integer agh:w.get(i))
{
temp.add(agh);
}
temp.add(ele);
w.add(temp);
temp.clear();
}
List<Integer> ghi=new ArrayList<Integer>();
ghi.add(ele);
w.add(ghi);
}
return w;
Though this may not solve your problem fully. But obviously it will help the garbage collector to take some rest. :D
The reason you are getting a heap error is because you are creating billions of lists.
Do not create sublists just display them.
public static void sub(int[] input){
sub(new int[0],input);
}
public static void sub(int[] current, int[] remaining){
System.out.println(Arrays.toString(current));
int[] newCurrent = Arrays.copyOf(current, current.length+1);
for(int i = 0;i < remaining.length;i++){
newCurrent[newCurrent.length-1] = remaining[i];
sub(newCurrent , Arrays.copyOfRange(remaining, i + 1, remaining.length));
}
}
otherwise you will need a smarter data structer than a list of lists.
To reduce memory consumption you can store sets as bit fields, for example set with elements 3, 9, 14 will be represented as 10110000000000000000 - so for each subset you will need only one int

Resources