I'm trying to split a string and return each sub-string to an array in Java (easier in c#) but the compiler is not having it. I keep getting an index out of bounds error when I try to call the value of any string in the array indexed higher than 0. Here's the code I'm using:
public class hello {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int setter = 3000;
String num = in.next();
String[] numbers = num.split(" ");
int j = numbers.length;
for (int i =0; i < numbers.length ; i++) {
System.out.println(numbers[i]);
}
System.out.println(j);
Even the length of the array being returned is 1.
As David Wallace said in comments: you should use nextLine from Scanner...
But... why read line to split into int?
public static void main(final String[] args) {
final Scanner in = new Scanner(System.in);
String line = null;
List<List<Integer>> all = new ArrayList<>();
while ((line = in.nextLine()) != null) {
final String[] tokens = line.split(" ");
List<Integer> forOneLine = new ArrayList<>();
for (final String token : tokens) {
try {
final Integer value = Integer.valueOf(token);
forOneLine.add(value);
} catch (final NumberFormatException e) {
// Not an Integer
}
}
all.add(forOneLine);
}
Is it ok now?
Ended up parsing to an integer
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String n = in.nextLine();
int ne = Integer.parseInt(n);
String m = in.nextLine();
String[] numbers = m.split(" ");
System.out.println(n);
System.out.println(m);
for (String string : numbers) {
System.out.println(string);
}
}
Related
Even though I have parsed it to an integer value I'm still getting an error. I need to get the integer value from a String input where I remove the comma and space, and store it in an array, then I convert that array to an integer array
import java.util.ArrayList;
import java.util.Scanner;
public class SeriesSolution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
ArrayList<Integer> modes = new ArrayList<>();
for (int x = 0; x < count; x++) {
String lines = sc.nextLine();
String[] strs = lines.split(", ");
int[] array = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
if (Integer.parseInt(strs[i]) > 0 && Integer.parseInt(strs[i]) < 100) {
array[i] = Integer.parseInt(strs[i]);
}
}
modes.add(mode(array));
}
for (int y:modes){
System.out.println(y);
}
}
private static int mode(int a[]) {
int maxValue=0, maxCount=0;
for (int anA : a) {
int count = 0;
for (int anA1 : a) {
if (anA1 == anA) ++count;
}
if (count > maxCount) {
maxCount = count;
maxValue = anA;
}
}
return maxValue;
}
}
The issue is mainly because Scanner accepts Enter keystroke as input. And because of which
String lines = sc.nextLine();
this peice of code stores an empty string into lines variable. This empty string throws NumberFormatException when passed to parseInt()
I would recommend you to use BufferedReader with InputStreamReader
BufferedReader br = new BuffereedReader(new InputStreamReader(System.in));
This is good for larger inputs and is error free. Though empty checks are must as prevention is better.
If you want to use Scanner, I would recommend you to update the code and use the below snippet of code.
String lines = "";
while (lines.equals("")) {
lines = sc.nextLine();
}
Do a check before the parseInt
if (strs[i] != null && !"".equals(strs[i]) && Integer.parseInt(strs[i]) ...
Or surround it with a try catch to catch the NumberformatException that will happen if a string is inserted instead of a number
import java.util.Scanner;
public class WordScrambler {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int chosenWord;
String[] words = {"hogwash","Rudolph","yule-log","Eggnog","CandyCane","Christmas","Fruitcake","gingerbread","Krampus","nutcracker"};
System.out.println("Pick a number between 1-10");
chosenWord=in.nextInt();
String a=words[chosenWord].substring(0,words[chosenWord].length()/2);
String b=words[chosenWord].substring(words[chosenWord].length()/2);
String c=b+a;
int x=(int)(Math.random()*(words[chosenWord].length()-1))+1;
String d=c.substring(0, words[chosenWord].length()-x);
String e=c.substring(words[chosenWord].length()-x);
String f=e+d;
System.out.println(f);
}
}
This is what i have so far.
I cant find a way to Scramble it anymore.
Right now the output is for example: Hogwash :shhogwa.
Thats the only word that Scrambles.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int chosenIndex;
String[] words = { "hogwash", "Rudolph", "yule-log", "Eggnog", "CandyCane", "Christmas", "Fruitcake",
"gingerbread", "Krampus", "nutcracker" };
System.out.println("Pick a number between 1-10");
chosenIndex = in.nextInt();
String chosenWord = words[chosenIndex - 1];
System.out.println(chosenWord);
StringBuilder scrambled = new StringBuilder();
List<Character> letters = new ArrayList<Character>();
for (char x : chosenWord.toCharArray()) {
letters.add(x);
}
while (letters.size() != 0) {
int random = (int) (Math.random() * letters.size());
scrambled.append(letters.remove(random));
}
System.out.println(scrambled.toString());
}
use meaningful variable names so its clear what its referring to
I'm asked to write a program that finds the common characters in two strings using the indexOf(char) method and a for loop. Here's what I have so far - the output comes out blank still.
import java.util.Scanner;
public class ClassName {
public static void main (String args []) {
Scanner input = new Scanner (System.in);
String a = "";
String b = "";
String c = "";
System.out.print("Enter two words: ")
a = input.nextLine();
b = input.nextLine();
for (int i = 0; i < a; i++){
char ch = a.charAt(i);
if (b.indexOf(ch) != -1){
c = c+String.valueOf(ch);
}
}
System.out.print("Common letters are: "+c);
}
}
output here
I'm not sure where to go from here.
thanks
Your code will duplicate common characters for example if you compare "developper" to "programmer" your result string will contain three time the e character
If you don't want that behaviour I suggest that you also use a Set like this:
public class CommonCharsFinder {
static String findCommonChars(String a, String b) {
StringBuilder resultBuilder = new StringBuilder();
Set<Character> charsMap = new HashSet<Character>();
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i); //a and b are the two words given by the user
if (b.indexOf(ch) != -1){
charsMap.add(Character.valueOf(ch));
}
}
Iterator<Character> charsIterator = charsMap.iterator();
while(charsIterator.hasNext()) {
resultBuilder.append(charsIterator.next().charValue());
}
return resultBuilder.toString();
}
// An illustration here
public static void main(String[] args) {
String s1 = "developper";
String s2 = "programmer";
String commons = findCommonChars(s1, s2);
System.out.println(commons);
}
}
Result from the example:
public Set<Character> commonChars(String s1, String s2) {
Set<Character> set = new HashSet<>();
for(Character c : s1.toCharArray()) {
if(s2.indexOf(c) >= 0) {
set.add(c);
}
}
return set;
}
public class CommonCharFromTwoString {
public static void main(String args[])
{
System.out.println("Enter Your String 1: ");
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
System.out.println("Enter Your String 2: ");
String str2 = sc.nextLine();
Set<String> str = new HashSet<String>();
for(int i=0;i<str1.length();i++){
for (int j = 0; j < str2.length(); j++) {
if(str1.charAt(i) == str2.charAt(j)){
str.add(str1.charAt(i)+"");
}
}
}
System.out.println(str);
}
}
Why in my program am i getting the output on one single line ? like abc123... I want my output to be printed on multiple lines, same as my inputs..
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}
It should be for example like this :
input: abc
123
...
output:cba
321
...
Here's one way of doing it:
import java.util.Scanner;
class Reverse {
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
StringBuilder output = new StringBuilder();
while (kbd.hasNextLine())
{
original = kbd.nextLine();
StringBuilder sb = new StringBuilder(original);
output.append(sb.reverse().toString()).append("\n");
}
System.out.println(output.toString());
}
}
EDIT I noticed that in your question it seems that you only want to print the output after all input has been provided. I've modified the code from my original answer to do this.
import java.io.*;
import java.util.*;
public class reverseString {
public static void main(String[] args) {
String input="";
System.out.println("Enter the input string");
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
char[] try1= input.toCharArray();
for (int i=try1.length-1;i>=0;i--)
System.out.print(try1[i]);
}
catch (IOException e) {
e.printStackTrace();
}
}}
try this:
package stackoverflow;
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
//befor you add the reversed string add a jump line firs
if(reverse.length()>0)reverse=reverse+"\n";
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}
You should change this part
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
in
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
reverse = reverse + '\n';
This will add new line character.
I have one advice for you - use StringBuilder for new reverse string
Like this:
public static void main(String args[]) {
String original;
StringBuilder sbReverse = new StringBuilder();
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
sbReverse.append(original.charAt(i));
}
sbReverse.append('\n');
}
System.out.println(sbReverse.toString());
}
The reason - in Java, strings are immutable.
That mean every time it execute reverse = reverse + original.charAt(i); it will be created a new string in memory.
You're getting the output in a single line because you are using System.out.printf(). Use System.out.println() instead.
PS: an easier way to reverse a string would be to use reverse() from StringBuilder.
reverse = new StringBuilder(original).reverse().toString();
So I'm trying to read the first 100 strings, which are words into an array of 100 Strings. and while doing that I'm trying to set each corresponding integer in an array of integers to 1, so counting each word the first time its read.
It's reading a book, 100 words at a time, and counting those words. So far I have this, how would I just make a switch statement of 100 cases?
Thanks in advance for any help!
package program6;
import java.util.Scanner;
public class Program6 {
static Scanner keyboard = new Scanner(System.in);
static String input;
String[] StringArray = new String[100];
int[] IntArray = new int[100];
String filename = "myths.txt";
String stringnumber;
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
HashMap<String,Integer> map = new HashMap();
public void count(String file){
Scanner in = null;
try{
in = new Scanner(new File(file));
}catch(IOException ex){
}
String val = in.next();
for(String currentKey : map.keySet()){
if(map.containsKey(val)){
map.put(currentKey,map.get(currentKey)+1);
}else{
map.put(val,1);
}
}
}
Try this :
Map<String, Integer> record = new HashMap<String, Integer>();
for(String temp: StringArray){
if(record.containsKey(temp)){
Integer num = record.get(temp) + 1;
record.put(temp, num);
}
else{
record.put(temp, 1);
}
}