Always getting the same answer in java - 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

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());
}

Array/ArrayList to make order with scanner input

so my teacher ordered me to make a program that
ask the user for the size of the array with a scanner
the program is required to understand if there is a scanner with the word "add" it will add the word after it to the array
The commands that are required to exist are ADD, DELETE, VIEW for display index-n and DISPLAY for display all of them
this is an example I've made but it's still far from correct, please help me!!!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
String arr[] = new String[a];
for (int i = 0; i < a; i++) {
for (int j=0;j<arr.length;j++){
arr[i] = input.nextLine();
}
}
for( String b : arr ){
System.out.println(b);
}
enter code here
an example of the scanner input is
7
ADD this
ADD IS
ADD not
ADD real
VIEW 2
DELETE not
DISPLAY
and the output will be
not
this is real
There's no reason to ask how long the array should be because we are using ArrayList which is a dynamic array. You can make this code easier to read but here's just an example of what you are looking for:
public final static void main(final String[] args)
{
final List<String> list = new ArrayList<String>();
final Scanner scan = new Scanner(System.in);
while (true)
{
final String command = scan.nextLine().toLowerCase();
if (command.contains("add "))
{
list.add(command.replace("add ", ""));
} else if (command.contains("delete "))
{
final String toDelete = command.replace("delete ", "");
if (!list.remove(toDelete))
System.out.format("\"%s\" didn't exist in the array!", toDelete);
} else if (command.contains("view "))
{
System.out.println(list.get(Integer.parseInt(command.replace("view ", ""))));
} else if (command.equals("display"))
{
for (final String str : list)
{
System.out.println(str);
}
break;
} else
{
System.out.println("Unknown command!");
}
}
scan.close();
}

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("");
}
}
}

Java, basic array error

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

Categories

Resources