Java, basic array error - java

I am trying to do a Java program that will let me input 10 words, and then the words should be repeated in reverse order (the last first etc).
This is my current code:
import java.util.Scanner;
import java.lang.String;
public class Words {
public static void main(String[] args){
String word[] = {};
for(int x = 0; x < 10; x+=1) {
System.out.println("Input any word");
Scanner input = new Scanner(System.in);
word = new String[] { input.next() };
}
for(int y = 9; y >= 0; y-=1) {
System.out.println(word[y]);
}
}}
It gives me the following error when trying to compile:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at Words.main(Words.java:21)
I am new to Java and would appreciate help, thanks in advice.

That's not how arrays work.
Change String word[] = {}; to String word[] = new String[10];
Also, change word = new String[] { input.next() }; to word[x] = input.next().
It is also a good idea to move Scanner input = new Scanner(System.in); outside of the for loop. You should read up on how arrays work to make sure this doesn't happen again.

You could try use an ArrayList to do this like so:
import java.util.*;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList al = new ArrayList();
do{
System.out.println("Enter word");
String word = sc.nextLine();
al.add(word);
if(al.size()==10){
System.out.println("Words in reverse order");
for(int i = al.size()-1; i>= 0; i--){
System.out.println(al.get(i));
}
}
}while(al.size()<10);
}
}
I think this answers your question properly.
All the best
Sean

Related

Can't get last element in arrayList without knowing the length

import java.util.Scanner;
import java.util.ArrayList;
public class kek2 {
public static void main(String[] args) {
Scanner imeskanera = new Scanner(System.in);
ArrayList<String> wordlist = new ArrayList <String>();
while(true) {
System.out.println("Type a word: ");
String word = imeskanera.nextLine();
int lenght =wordlist.size();
if(word.equals("")) {
for(int i = 0;i<lenght; i++) {
System.out.println(wordlist.get(lenght-i));}
break;
}
wordlist.add(word);
}
}
}
Im trying to print out the array in reversed order but i get error in (lenght-i) part, everything looks fine to me, am'I doing something wrong that Java doesnt allow?
It may be better to limit while loop to reading the inputs and when user is done, print the list contents in any desired order.
Scanner imeskanera = new Scanner(System.in);
List<String> wordlist = new ArrayList<>();
String word;
System.out.println("Type a word: ");
while(!(word = imeskanera.nextLine()).isEmpty()) {
wordlist.add(word);
System.out.println("Type a word: ");
}
for (int i = wordlist.size(); i-- > 0;) { // index decremented in condition
System.out.println(wordlist.get(i));
}
Or ListIterator may be retrieved using List::listIterator and its methods hasPrevious() / previous() can be used to iterate in reverse direction -- however, the size of list is needed anyway:
for (ListIterator i = wordlist.listIterator(wordlist.size()); i.hasPrevious();) {
System.out.println(i.previous());
}

Always getting the same answer in java

Can anyone explain to me why I get only 40 as answer when I run the following code?
View problem in code coach
import java.util.*;
public class Program
{
public static void main(String[] args) {
Scanner var = new Scanner (System.in);
String n = var.nextLine();
int p = var.nextInt();
String[] a = var.nextLine().split(" ");
List<String> list = new ArrayList<String>();
for(int i=0;i<a.length;i++){
list.add(a[i]);
}
list.add(n);
Collections.sort(list);
int y = list.indexOf(n)+1;
if(y>p){
System.out.print(((y/p)*20)+(y%p)*20);
}
else{
System.out.print("20");
}
}
}
nextInt() cannot read newline character. so when you use nextLine() it reads that new line character.
This answer might help you

multiply output of string by using custom input

I am trying to write a program that would take an ArrayList containing "How", "Are" and "You?" and pass this to a 'stutter' method that will get the output to repeat the words after asking the user for number/how many times they want the word repeated.
Example: if user enters 4, i would pass How, Are and You? and 4 to this stutter method and the output would be How, How, How, How, Are, Are, Are, Are, You?, You?,You?,You?. This seems simple enough but i cannot get the output correct. Any help is appreciated!
import java.util.*;
public class Question3 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("how");
list.add("are");
list.add("you?");
Scanner input = new Scanner(System.in);
System.out.println("How many repeats?");
int repeat = input.nextInt();
System.out.println("Before stutter: " + list);
stutter(list, repeat);
}
public static void stutter(ArrayList<String> list, int repeat){
ArrayList<String> modifiedList = new ArrayList<String>();
for(String str : list) {
for(int i = 0; i < repeat; i++)
modifiedList.add(str);
System.out.print(modifiedList);
}
}
}
The print statement is running in the outer loop, so it prints modifiedList once for each str. Move it to the end of the method so it prints the final result once:
public static void stutter(ArrayList<String> list, int repeat){
ArrayList<String> modifiedList = new ArrayList<String>();
for(String str : list) {
for(int i = 0; i < repeat; i++)
modifiedList.add(str);
}
System.out.print(modifiedList);
}

Getting NZEC error in SPOJ with Java for this Code

This is my answer for half of half question in SPOJ( Question ID :12156) . I'm a beginner in JAVA. Please Help why am i getting an error. I'm able to get an expected answer while compiling in Ideone. Thanks
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan =new Scanner(System.in);
String[] name= new String[10];
int size,count;
String temp,news;
char[] chars= new char[20];
temp=scan.nextLine();
count=Integer.parseInt(temp);
for(int i=0;i<count;i++)
{
name[i]=scan.nextLine();
}
for(int j=0;j<count;j++)
{
news=name[j];
size=news.length();
chars=news.toCharArray();
for(int k=0;k<size/2;k=k+2)
{
System.out.print(chars[k]);
}
System.out.println();
}
}
}
Pay attention to the following points in the problem description:
In the first line of input your are given the positive integer t
(1 <= t <= 100) - the number of test cases.
In your code, you can handle 10 (and not 100) strings at maximum.
String[] name = new String[10];
In the each of the next t lines, you are given a sequence of 2*k
(1 <= k <= 100) characters.
In your code, you can handle 20 (and not 200) characters at maximum.
char[] chars = new char[20];
I did attempt same question half of half at SPOJ, my code is accepted.
I think array initialisation should be based on input.
import java.util.Scanner;
class Main {
public static void main(String[] args) throws java.lang.Exception {
Scanner scan = new Scanner(System.in);
int testCase = scan.nextInt();
scan.nextLine();
String[] inputStringArray = new String[testCase];
for (int x = 0; x < testCase; x++) {
String input = scan.nextLine();
input = input.replaceAll("\\s+", "");
inputStringArray[x]=input;
System.out.println("#-"+x);
}
for(int y=0;y<testCase;y++){
String text = inputStringArray[y];
char[] inputArray = text.toCharArray();
int len = inputArray.length/2;
for(int z=0;z<len;z=z+2){
System.out.print(inputArray[z]);
}
System.out.println("");
}
}
}

read csv file into 2d array

CSV File:
515.30,516.81
516.81,514.27
516.74,517.68
517.54,516.72
517.61,517.64
517.22,516.99
517.21,517.33
516.99,516.92
516.96,517.5
517.38,516.91
No blank lines in between.
My program so far:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class CSVRead
{
public static void main(String arg[]) throws Exception
{
double[][] test = new double[9][2];
String[] testStr = new String[19];
String delimiter = ",";
Scanner sc = new Scanner("kort.csv");
while (sc.hasNextLine())
{
String line = sc.nextLine();
testStr = line.split(delimiter);
}
for (int i=0; i<10; i++)
{
for (int j=0; j<2; j++)
{
test[i][j] = Double.parseDouble(testStr[2*i+j]);
}
}
for (int y=0; y<10; y++)
{
for (int x=0; x<2; x++)
{
System.out.print(test[y][x] +" ");
}
}
} //main()
} // CSVRead
Exception in thread "main" java.lang.NumberFormatException: For input string: "AEX2008kort.csv"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
at CSVRead.main(CSVRead.java:26)
Java Result: 1
Change to
Scanner sc = new Scanner(new File("kort.csv"));
You want to parse the content of the file, not the String "kort.csv"
After you have done what Alex mentioned, you need to change the way testStr is being used. In your current code, testStr will always have the last line elements (517.38 and 516.91). What you probably want to do is to store the Double numbers in a List perhaps,
List<Double> mynumbers = new ArrayList<Double> ();
and use it later on to populate your 2D array. Once you have split the line into testStr, you should add these numbers to the list,
mynumbers.add(testStr[0]);
mynumbers.add(testStr[1]);
Finally, in the parseDouble method, instead of passing testStr you should pass your list:
mynumbers.get(index_you_want);

Categories

Resources