How can I display ZERO, POSITIVE, NEGATIVE string with corresponding array in one JOptionPane message?
Here is the code....
String display="";
int z = 0;
String size = JOptionPane.showInputDialog("Enter Your Prefered Size Of Your Array");
int newsize = Integer.parseInt(size);
JOptionPane.showMessageDialog(null,"You Entered "+newsize+".");
int array[] = new int [newsize];
for (int a=0; a<array.length;a++)
{
array[a] = Integer.parseInt(JOptionPane.showInputDialog("Enter Value For Array["+a+"]."));
}
for (int a=0;a<array.length;a++)
{
display=display+array[a]+"\n";
if (z == array[a])
{
String c=array[a]+" ZERO";
JOptionPane.showMessageDialog(null,"Arrays\n"+display+c);
}
else if (z < array[a])
{
String c =array[a]+" POSITIVE";
JOptionPane.showMessageDialog(null,"Arrays\n"+display+c);
}
else if (z != array[a])
{
String c =array[a]+" NEGATIVE";
JOptionPane.showMessageDialog(null,"Arrays\n"+display+c);
}
JOptionPane.showMessageDialog(null,"Arrays\n"+display+c);
}
Is this what you are after:
public class SO2{
public static void main(String[] args) {
String display="";
int z = 0;
String size = JOptionPane.showInputDialog("Enter Your Prefered Size Of Your Array");
int newsize = Integer.parseInt(size);
JOptionPane.showMessageDialog(null,"You Entered "+newsize+".");
int array[] = new int [newsize]; //Sets array
for (int a=0; a<array.length;a++){//Puts values in array
array[a] = Integer.parseInt(JOptionPane.showInputDialog("Enter Value For Array["+a+"]."));
}
for (int a=0;a<array.length;a++){
display=display+array[a]+"\n";
}
String toShow = ""; //String to build up
for(int i = 0; i < array.length; i++){
if(array[i] == 0){
display = "ZERO";
} else if(array[i] < 0){
display = "NEGATIVE";
} else if(array[i] > 0){
display = "POSITIVE";
}
toShow += "Array element " + i + " is " + array[i] + " and it is " + display + "\n"; //Build string
}
JOptionPane.showMessageDialog(null,"Your numbers...\n\n"+toShow);//show
}}
It shows all the numbers from the array with their POS/NEG/ZERO values next to them. I have added some comments to try and explain a little
Good luck!
Related
I am stuck. I have my array with data the user inputs. After their information is entered the program asks if they want to see items with characters above 10 or below. I can't seem to figure out this section. Below is where I am currently with the code.
import java.util.*;
import java.util.Scanner;
public class CategorizeStrings {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter anything..., or press QUIT to quit.");
for (int i = 0; i < array.length; i++) {
array[i] = s.nextLine();
boolean result = Arrays.stream(array).anyMatch("QUIT"::equals);
if(result)
{
break;
}
}
String str = null;
int len = -1;
System.out.println("Would you like to display strings with above 10 charaters (Above) or below 10 characters (Below)? Type Above or Below:");
String answer = s.nextLine();
if(answer == "Above"){
for (int i = 0; i < array.length; i++) {
if (array[i] != null)
len ++;
if(array[i].charAt(i)>10)
for (int x = 0; x < len; x++) {
if(array[x] == str )
System.out.print(len);
System.out.print(array[x] + " ");
}
}
}
else
{
}
System.out.println();
}
}
The block of code I'm struggling with is:
for (int i = 0; i < array.length; i++) {
if (array[i] != null)
len ++;
if(array[i].charAt(i)>10)
for (int x = 0; x < len; x++) {
if(array[x] == str )
System.out.print(len);
System.out.print(array[x] + " ");
}
Any help is appreciated.
If you just want to print the words that have above 10 characters
for (String value : array) {
if (value != null) {
if (value.length() > 10) {
System.out.print(value + " ");
}
}
}
This is how I would do it
Also note that Strings can't be compared using '=='
You should use equal or contentEquals
For example:
if (string1.equals(string2)) {
// Insert code here
}
or
if (string1.contentEquals(string2)) {
// Insert code here
}
So I have been given a project in where I must validate ISBN-10 and ISBN-13 numbers. My issue is that I want to use an ArrayList based on what the user inputs(the user adds as many numbers as they want to the ArrayList). Here is my code (without an ArrayList). How can I modify this so that the user can put as many ISBN number as they want?
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
//Get the ISBN
System.out.print("Enter an ISBN number ");
isbn = input.nextLine();
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
}else{
isValid = false;
}
//Print check Status
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{
System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
//
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
}
public static List<String> scanNumberToListUntilAppears(String end) {
if(end == null || end.isEmpty())
end = "end";
List<String> numbers = new ArrayList<>();
String message = "Enter an ISBN number: ";
try (Scanner input = new Scanner(System.in)) {
System.out.print(message);
while(input.hasNext()) {
String isbn = input.nextLine();
if(isbn.equalsIgnoreCase(end)) {
if(!numbers.isEmpty())
break;
} else {
numbers.add(isbn);
if(numbers.size() == 1)
message = "Enter the next ISBN number or '" + end + "': ";
}
System.out.print(message);
}
}
return numbers;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String isbn;
String ans;
ArrayList<String> isbns = new ArrayList<String>();
// user will enter at least 1 ISBN
do{
//Get the ISBN
System.out.println("Enter an ISBN number ");
isbns.add(input.nextLine());
//loops till answer is yes or no
while(true){
System.out.println("Would you like to add another ISBN?");
ans = input.nextLine();
if(ans.equalsIgnoreCase("no"))
break;
else if (!(ans.equalsIgnoreCase("yes"))
System.out.println("Please say Yes or No");
}
}while(!(ans.equalsIgnoreCase("yes"));
input.close();
//Strip out the spaces/System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");System.out.println("Press 1 to enter a list of ISBN numbers to verify. ");dashes by replacing with empty character.
for(int i = 0; i<isbns.size(); i++)
isbns.set(i, isbns.get(i).replaceAll("( |-)", ""));
isbn = isbn.replaceAll("( |-)", "");
//Check depending on length.
boolean isValid = false;
for(String isbn : isbns){
if(isbn.length()== 10){
isValid = CheckISBN10(isbn);
print(isbn, isValid);
}else if (isbn.length()== 13){
isValid = CheckISBN13(isbn);
print(isbn, isValid);
}else{
isValid = false;
print(isbn, isValid);
}
}
public static void print(String isbn, boolean isValid){
if(isValid){
System.out.println(isbn + " IS a valid ISBN");
}else{ System.out.println(isbn + " IS NOT a valid ISBN");
}
}
//Checking ISBN-10 numbers are valid
private static boolean CheckISBN10(String isbn){
int sum = 0;
String dStr;
for (int d = 0; d < 10; d++){
dStr = isbn.substring(d, d + 1);
if (d < 9 || dStr != "X"){
sum += Integer.parseInt(dStr) * (10-d);
}else {
sum += 10;
}
}
return (sum %11 == 10);
}
private static boolean CheckISBN13(String isbn){
int sum = 0;
int dVal;
for (int d = 0; d < 13; d++){
dVal = Integer.parseInt(isbn.substring(d, d + 1));
if (d % 2 == 0){
sum += dVal * 1;
}else {
sum += dVal * 3;
}
}
return (sum % 10 == 0);
}
The user will enter the size of the array and its values. If the entered value exists, the user must enter a different number. I can't seem to construct the proper code to check if the inserted value exists.
public static void main(String[] args) {
String holder="", s;
int size;
s=JOptionPane.showInputDialog("Enter the size of the array");
size= Integer.parseInt(s);
String array1[]= new String[size]; //declared and instantiated array1
for (int x=0; x<=array1.length-1;x++)
{
array1[x]=JOptionPane.showInputDialog("Enter value for array[" +x +"]");
int a=0;
if (array1[x].equals(array1[x])){
a=1;
JOptionPane.showMessageDialog(null, "exists");
}
else
JOptionPane.showMessageDialog(null, "continue");
}
for (int x=0; x<=array1.length-1;x++)
{
holder=holder+ "\n"+ array1[x];
}
JOptionPane.showMessageDialog(null,holder);
How about this? Checks if the value exists, otherwise the user needs to re-enter the number.
public static void main(String[] args) {
String holder = "", s;
int size;
s = JOptionPane.showInputDialog("Enter the size of the array");
size = Integer.parseInt(s);
String array1[] = new String[size]; //declared and instantiated array1
for (int x = 0; x <= array1.length - 1; x++) {
String num = JOptionPane.showInputDialog("Enter value for array[" + x + "]");
if (Arrays.asList(array1).contains(num)) {
x = x - 1;
JOptionPane.showMessageDialog(null, "exists");
} else {
array1[x] = num;
JOptionPane.showMessageDialog(null, "continue");
}
}
for (int x = 0; x <= array1.length - 1; x++) {
holder = holder + "\n" + array1[x];
}
JOptionPane.showMessageDialog(null, holder);
}
I'm making a program that counts the frequency of letters from a user-entered string, and have recently encountered the 'Arithmetic Exception' error.
I cannot for the life of me figure out what's causing it, even though I know it's because something is being divided by 0.
Here's my code:
package day1.examples;
import java.util.Scanner;
public class rl_frequency_count {
public static int input;
public static void main(String[] args) {
System.out
.println("Please enter some text that you would like to work out the occurence for.");
System.out
.println("However, do remember that any other characters outside of the alphabet will NOT be counted.");
Scanner stringUser = new Scanner(System.in);
String input = stringUser.nextLine();
input = input.replaceAll("\\s+", "");
input = input.toLowerCase();
// counting occurrence of character with loop
int i;
int charCountA = 0;
int charCountB = 0;
int charCountC = 0;
int charCountD = 0;
int charCountE = 0;
int charCountF = 0;
int charCountG = 0;
int charCountH = 0;
int charCountI = 0;
int charCountJ = 0;
int charCountK = 0;
int charCountL = 0;
int charCountM = 0;
int charCountN = 0;
int charCountO = 0;
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'a') {
charCountA++;
getOccurence(charCountA, "A");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'b') {
charCountB++;
getOccurence(charCountB, "B");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'c') {
charCountC++;
getOccurence(charCountC, "C");
}
}
for (i = 0; i < input.length(); i++) {
if (input.charAt(i) == 'm') {
charCountM++;
getOccurence(charCountM, "M");
}
}
}
// method for the occurrence
public static void getOccurence(int number, String letter) {
double occ = number / input * 10; //
System.out.println();
System.out.println("Number of " + letter + "'s - " + number);
System.out.println("Occurence of " + letter + " - " + occ + "%");
}
}
I know that I only have ABC and M in at the moment but was gonna work those in later.
This is the first time i've posted on here and i'm still newish to Java so any help whatsoever is greatly appreciated!
I ran it and it says line 67. here is the total:
public static void getOccurence(int number,String letter){
double occ = number / input *10; //
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
To fix:
double occ = (number > 0) ? number/input * 10 : 0;
This sets occ to 0 in case of number being set to 0. Good luck.
Hope this helps.
The line of code causing the error is in your method:
public static void getOccurence(int number,String letter){
double occ = number / input *10; // <------ERROR FROM HERE (input is always 0)
System.out.println();
System.out.println("Number of "+ letter +"'s - "+ number);
System.out.println("Occurence of "+ letter +" - "+ occ + "%");
}
The input variable is declared in your class here:
Line 6: public static int input;
Since you didn't initialize it nor does the value is being changed in your codes, the value of input remains as 0 through out the entire program. (Default value for an uninitialized int variable is 0)
Since it is always 0, you are always dividing a number with 0.
double occ = number / 0*10;
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
Why does the array "prevScore" not print the value "points"?
I want it to print out points for prevScore [0], and then null 0
This is the array, after the // is something I thought I could use.
int [] prevScore = new int[10]; //{ 0 };
String [] prevScoreName = new String[10]; //{"John Doe"};
public static int[] scoreChange (int prevScore[], int points)
{
for(int i = 9; i > 0; i--){
prevScore[i] = prevScore[i-1];
}
prevScore[0]= points;
return prevScore;
}
I dont know if the print of prevScore is needed.
//a method that prints high scores
public static void printScores (int prevScore[], String prevScoreName[])
{
for (int i = 10; i > 0; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}
}
Here is the rest of my program I am working on... currently only i get one, 0 John Doe.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
do {
int menuchoice = 0;
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1){
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2){
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName); }
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR"); }
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct){
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ){
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}
Use this loop:
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
I think it should solve your problem.
Update
based on your updated program. Move the following code above the start of the 'do' loop.
int [] prevScore = new int[] { 0 };
String [] prevScoreName = new String[] {"John Doe"};
That is you are moving these lines out of the loop. It should work now.
That is the start of your 'main' method should look something like this:
public static void main(String args[]) throws IOException {
int press = 0;
int[] prevScore = new int[] { 0 };
String[] prevScoreName = new String[] { "John Doe" };
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions," + "3 prev score");
Your printScore() method is trying to access element [10] of an array whose index range is 0 - 9, and is never accessing element [0]. You may want to print the most recent score first:
for (int i = 0; i < 10; i++) {
Or conversely, to print the most recent score last:
for (int i = 9; i >= 0; i--) {
Thank you so much! It Works! The only problem still is that the scorelist prints backwards.
public class Main
{
static BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); // user input
public static void main (String args[]) throws IOException
{
int press = 0;
int[] prevScore = new int[10];
String[] prevScoreName = new String[10];
do {
int menuchoice = 0;
System.out.println("Menu choice: 1 to start game, 2 print instructions,"
+ "3 prev score");
Scanner input = new Scanner(System.in);
int userinput = Integer.parseInt(input.next());
int points;
menuchoice = userinput;
if (menuchoice == 1) {
points = startGame();
String newName = endGame(points);
prevScore = scoreChange(prevScore,points);
prevScoreName = nameChange(prevScoreName, newName);
}
if (menuchoice == 2) {
printInstructions();
}
if(menuchoice == 3) {
printScores(prevScore, prevScoreName);
}
if (menuchoice != 1 && menuchoice != 2 && menuchoice !=3 ) {
System.out.println("ERROR");
}
} while (press !=4 );
}
//a method that initializes a new game
public static int startGame () throws IOException //a method that initializes a new game
{
int lives = 3;
int points = 0;
System.out.println("Good Luck!");
do {
System.out.println("Points: " + points);
System.out.println("Lives: " + lives);
int correct = displayNewQuestion();
Scanner userinput = new Scanner(System.in);
int userAnswer = Integer.parseInt(userinput.nextLine());
if (userAnswer == correct) {
points ++;
System.out.println("Correct");
}
if (userAnswer != correct ) {
lives --;
System.out.println("Incorrect");
}
} while (lives > 0);
return points;
}
public static String endGame (int points) throws IOException // a method that tells the user the game is over
{
System.out.println("GAME OVER");
Scanner nameinput = new Scanner(System.in);
System.out.println("Please enter your name for the score charts!");
String newName = nameinput.next();
return newName;
}
public static int[] scoreChange (int prevScore[], int points)
{
// for(int i = 0; i < 10; i--){
// prevScore[i] = prevScore[i-1];
// }
// prevScore[1]= prevScore[0];
prevScore[0]= points;
return prevScore;
}
public static String[] nameChange (String prevScoreName[], String newName)
{
/*for(int i = 0; i < 10; i++){
prevScoreName[i] = prevScoreName[i-1];
}
//prevScoreName[1] = prevScoreName[0];*/
prevScoreName[0] = newName;
return prevScoreName;
}
public static void printInstructions () //a method that will print the instructions to the user
{
System.out.println("Instructions");
}
public static void printScores (int prevScore[], String prevScoreName[]) //a method that prints high scores
{
/* for (int i = 0; i < 10; i--){
System.out.println(prevScore[i] + " " + prevScoreName[i]);
}*/
System.out.println("Scores: ");
for (int i = prevScore.length; i > 0; i--){
System.out.println(prevScore[i-1] + " " + prevScoreName[i-1]);
}
}
public static int displayNewQuestion () // a method that displays a random arithmetic question
{
int correctAnswer = 0;
int num1 = randInt (12,-12);
int num2 = randInt(12, -12);
Random rand = new Random();
int operator = rand.nextInt((4 - 1) + 1) + 1;
if (operator == 1)
{
System.out.println(num1 + " + " + num2);
correctAnswer = num1 + num2;
}
if (operator == 2)
{
System.out.println(num1 + " - " + num2);
correctAnswer= num1 - num2;
}
if (operator == 3)
{
System.out.println(num1 + " x " + num2);
correctAnswer= num1*num2;
}
if (operator == 4)
{
if (num2 == 0) {
System.out.println(num1*num2 + " / " + num1);
correctAnswer= ((num1*num2)/num1);
}
if (num2 != 0) {
System.out.println(num1*num2 + " / " + num2);
correctAnswer= ((num1*num2)/num2);
}
}
return correctAnswer;
}
public static int randInt(int max , int min) {
Random rand = new Random();
min = -12;
max = 12;
int randnum = rand.nextInt((max - min) + 1) + min;
return randnum;
}
}