Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to create a program as described in the image linked below. I'm finding trouble with how to print the characters on the same line so that I can get 20 across and how to go to a new line after the first 20 characters have printed. Can you help me figure out a way to print the randomly selected characters into a 20 by 7 grid? Thank you for the help! Below is what I have so far but it's printing every new character on its own line and for gridArray[3] the forward-slash has to have two quotes otherwise it says that it's not a valid string. Does anyone know how I could solve these problems?
Link to Problem Directions
package edu.skidmore.cs106.lab09.problem14;
import java.util.Random;
public class GridGenorator {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] gridArray = new String[6];
gridArray[0] = "+";
gridArray[1] = "-";
gridArray[2] = "/";
gridArray[3] = "\"";
gridArray[4] = "|";
gridArray[5] = "_";
for (int elementx = 0; elementx < 7; elementx++) {
for(int elementy = 0; elementy<20; elementy++) {
Random rand = new Random();
int randomNum = rand.nextInt(6);
System.out.println(gridArray[randomNum]);
}
}
}
}
System.out.println prints a new line which you do not want to do every time, only after a group of 20, so try
for (int elementx = 0; elementx < 7; elementx++) {
for(int elementy = 0; elementy<20; elementy++) {
Random rand = new Random();
int randomNum = rand.nextInt(6);
System.out.print(gridArray[randomNum]);
}
System.out.println(); // now you want to print a newline
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
does anyone know whats wrong with my code? it keep getting error output in java GUI
the loop 2 and loop 3 getting error after debug, and i dont know whats wrong
private void butActionPerformed(java.awt.event.ActionEvent evt) {
String input1 = txtInput.getText();
String input2 = input1.toLowerCase();
char[] word1 = new char[input2.length()];
char[] word2 = new char[26];
for (int i = 0; i < word2.length; i++) {
word2[i] = (char) (97 + i);
}
int[] x = new int[26];
for (int i = 0; i < word1.length; i++) {
input1[i] = input2.charAt(i);
}
for (int i = 0; i < word2.length; i++) {
for (int j = 0; j < word1.length; j++) {
if (word2[i])==word1[j]) {
x[i]++;
}
}
}
txtOutput1.setText(Arrays.toString(word2));
txtOutput2.setText(Arrays.toString(x));
}
The first problem:
input1 is a string, but with input1[i] = input2.charAt(i); you are treating it as an array - this is not allowed in Java.
From your logic I think the corresponding line should be
word1[i] = input2.charAt(i);
The second problem: on the line
if (word2[i])==word1[j]) {
there is a closing parenthesis to much (after word2[i]), the line should read
if (word2[i]==word1[j]) {
input1 is a String variable and therefore immutable, which means it can only be assigned a new value and can not be changed otherwise.
The following line causes a problem:
input1[i] = input2.charAt(i);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
so I have to write a program for an assignment, and for that i have to accept a string, make sure it's got the right number of sentences and print the frequency of each word. I've got this almost completely right, but at the end, when I print the words (which I've stored in an array), each word is preceeded by Ljava.lang.String; #xyznumber. I have no idea why this is happening and I can't find a solution on the net. Here's my code:
import java.util.Arrays;
import java.io.*;
class frequency
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of sentences");
int cS = Integer.parseInt(br.readLine());
System.out.println("Enter sentences");
String s = br.readLine();
int cS1 = 0;
int cW = 0;
for(int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if (ch=='.'||ch=='?')
{
cW++;
cS1++;
}
if (ch==' ')
{
cW++;
}
}
if (cS1!=cS)
{
System.out.println("You have entered the wrong number of sentences. Please try again.");
}
else
{
int c = 0;
int d = 0;
String a[] = new String[cW];
System.out.println("Total Number of words: "+cW);
for (int i= 0;i<s.length();i++)
{
char ch=s.charAt(i);
if (ch==' '||ch=='?'||ch=='.')
{
a[c++]=a+s.substring(d,i);
d = i+1;
}
}
int length=0;
firstFor: for(int i=0;i<a.length;i++)
{
for(int j=0;j<i;j++)
{
if (a[j].equalsIgnoreCase(a[i]))
{
continue firstFor;
}
else
{
length++;
}
}
}
String words[] = new String[length];
int counts[] = new int[length];
int k=0;
secondFor: for (int i =0;i<a.length;i++)
{
for(int j = 0; j<i;j++)
{
if (a[j].equalsIgnoreCase(a[i]))
{
continue secondFor;
}
}
words[k]=a[i];
int counter = 0;
for (int j =0;j<a.length;j++)
{
if(a[j].equalsIgnoreCase(a[i]))
{
counter++;
}
}
counts[k]=counter;
k++;
}
for (int i=0;i<words.length;i++)
{
System.out.println(words[i]+"\n"+(counts[i]));
}
}
}
}
The problem stems from this line here:
a[c++]=a+s.substring(d,i);
Since a is a String array, what this does is assigns one of the elements in a to be equal to the String representation of the entire array, plus a substring of s. Arrays don't have a very useful String representation though, which is where the Ljava.lang.String;#xyznumber you see is coming from.
Depending on what you want the first part of a[c] to be, either use an index into the array, or convert the array to a String
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
So I have a method that receives a String[][] and a String(word).The method has to look for the word from the 2dArray and should display one of the other words in the same row. Also I need to ignore(not display) and count(++) the empty spots that are in the same row. I want to know why my counter is looping and it wont let me ignore those empty spaces.
public static void main(String[] args) {
String[][] array2d = {{"joe", "slim", "ed", "george"},
{"soto", "", "", "" },
{"billy", "sanchez", "carlos", "fernando"}};
sort(array2d, "soto");
}
public static void sort(String[][] matrix, String word) {
int counterForArrayLength = 0;
boolean random = true;
boolean exit = true;
String optionFromUser = "";
do {
random = true;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j].equals(word)) {
for (int k = 0; k < matrix[0].length; k++) {
while (random) {
String randomWord = matrix[i][(int) (Math.random() * matrix[0].length)];
String testRandom = "" + randomWord;
if (randomWord.equals(word)) {
random = true;
} else {
if (randomWord.equals("")) {
counterForArrayLength++;
System.out.println("" + counterForArrayLength);
} else {
JOptionPane.showMessageDialog(null, randomWord);
optionFromUser = JOptionPane.showInputDialog("Desea obtener otro sinonimo? si/no \n Digite salir si asi lo desea.");
optionFromUser = optionFromUser.toLowerCase();
if (optionFromUser.equals("si") || optionFromUser.equals("s")) {
random = true;
} else {
random = false;
}
}
}
}
}
}
}
}
if (optionFromUser.equals("salir")) {
exit = false;
} else {
word = JOptionPane.showInputDialog("Digite otra palabra");
}
} while (exit);
}
run:
1
2
3
4
5
6
7
8
9
10
etc.
Your code sample missing essential information. However, the internal loop:
while(random)
{
// . . .
}
can run forever because you don't guarantee to have random variable to be set to false.
It will work only if you call the method with a word that isn't part of the array.
Also if you call it with word = "soto" then a chance is 100% that never leave the loop since out of 4 words there is one that you found and other 3 are empty.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Getting NullPointerException when it tries to access stones[0].length.
Please Help. I have already Initialized Stones Object.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Solution
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
String stones[] = new String[times];
int score = 0;
int counter;
for(int tcase = 0; tcase < times; tcase++)
stones[tcase] = br.readLine();
int s = stones[0].length();
for (int i = 0; i < s ; i++) {
char j = stones[0].charAt(i);
counter = 0;
for (int k = 1; k < times; k++) {
char aa[] = stones[k].toCharArray();
for (int l = 0; l <aa.length ; l++) {
if(aa[l]==j)
{
counter++;
break;
}
}
if (counter==times-1) {
score++;
}
}
}
System.out.println(score);
}
}
Getting NullPointerException when I try to access stones[0].length(). Please help
When you submit your code through some automated service, it's running your code and it's failing because there's no System.in stream to provide any valid data. If you attempt to check for valid data before doing anything, it will catch this condition, and should let you submit, while still working properly on your laptop.
Try this:
Scanner sc = new Scanner(System.in);
int times = 0;
if ( sc.hasNext() ) { // check to make sure there's valid input first
times = sc.nextInt();
String stones[] = new String[times];
int score = 0;
int counter;
for(int tcase = 0; tcase < times; tcase++)
stones[tcase] = br.readLine();
if ( stones[0] != null ) { // check to make sure your array object exists
int s = stones[0].length();
for (int i = 0; i < s ; i++) {
char j = stones[0].charAt(i);
counter = 0;
for (int k = 1; k < times; k++) {
char aa[] = stones[k].toCharArray();
for (int l = 0; l <aa.length ; l++) {
if(aa[l]==j)
{
counter++;
break;
}
}
if (counter==times-1) {
score++;
}
}
}
}
}
The best way to make sense of these sort of problems is to use a debugger. But just for fun, let's do some code analysis...
int s = stones[0].length();
What can be generating a NullPointerException on this line? Well, the stones variable could be referring to null. We can easily rule this out, however, as the stones variable was assigned a new array instance further up in the code, and was never reassigned before reaching the problem line. The only other possibility is that the array component variable stones[0] refers to null.
Why might stones[0] be null? Well, for starters, it's initialized that way, so if you never assign to that component, then it will be null. However, the for loop that you have between array initialization and the problem line is iterating over all of the array components and initializing them, so every component will be assigned to. What else might be the problem?
The loop is assigning to each array component the value returned by br.readLine(). Could that return value possibly be null? Let's take a look at the javadocs...indeed, we find (emphasis added):
Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
And there you have it, it is certainly possible for stones[0] to be null! Now, if that is true, what does it mean? Well, it means that the very first call to br.readLine() returned null, signalling that it had reached the end of the stream. Which fits with what other answerers have noted - if System.in() is not available to provide any data, it would make sense to encounter the 'end of stream' condition right out of the gate.
It works with me, although I would not use two stream readers(a Scanner and a BufferedReader) for the same input.
What is the input that causes the exception?
PS. You should close the Scanner when it is not used.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I'm currently doing a challenge on a website to do with checking if a number is a Happy Number or not. The program is to read in a file with a list of numbers, one on each line and determine if it is a happy number. I'm having some trouble with implementing the check to see if the number is happy or not.
The happy part is fairly straight forward, if it gets to 1 it is a happy number. The problem occurs for me if the number is not happy it will never get to 1 and will stay in an infinite loop so I'm not sure on how to track that successfully
Here is the code:
package com.jconnolly.codeeval;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class HappyNumbers {
public static void main(String[] args) {
HappyNumbers hn = new HappyNumbers();
File file = new File(args[0]);
BufferedReader br;
String[] numbers;
try {
// Read in file
br = new BufferedReader(new FileReader(file));
String line;
// Store each line as a string in an array
while((line = br.readLine()) != null) {
numbers = line.split("\n");
for(int i = 0; i < numbers.length; i++) {
if(hn.isHappy(numbers[i])) {
System.out.println(1);
} else {
System.out.println(0);
}
}
}
System.exit(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(-1);
}
}
// Separates digits, squares them and adds them together
public boolean isHappy(String str) {
int sum = 0;
// Holds numbers after they are squared and added together
ArrayList<Integer> happy = new ArrayList<Integer>();
// Separates the digits to be squared
while((sum != 1) && !happy.contains(sum)) {
for(int i = 0; i < str.length(); i++) {
Character c = new Character(str.charAt(i));
String character = c.toString();
int digit = Integer.parseInt(character);
sum += (digit * digit);
}
happy.add(sum);
}
happy.clear();
return sum == 1;
}
Any advice on a better implementation or correction would be greatly appreciated. It does give results but they are incorrect. Thanks
The only way I can think of to test for "never reaches 1" is to recognize when you're retesting values you've already tested, which would show that you're caught in a loop where all the numbers in that loop are unhappy. Build up a dictionary from there and use it to recognize other unhappy numbers more quickly. I believe that for this formula that's actually practical; for some, it might not be.
Try the following isHappy() method; I think recursion is the most elegant solution, but a list is needed to prevent entering a loop:
ArrayList<Integer> checked = new ArrayList<Integer>(); // used to tell if a number has already been checked
public boolean isHappy(int i) {
if(i == 1)
return true;
for(int j : checked)
if(i == j)
return false
int nextNum = ...; // generate the next number (sum the squared digits of i)
checked.add(nextNum);
return isHappy(nextNum);
}
Hope this helps!