I'm trying to create a program that takes each number typed in by the user and sort them out as even, odd and the number zero values.
The result should look like something like this:
User Input: 14005
Output:
Even Numbers: 4
Odd Numbers: 1, 5
Zero's: 0, 0
This is the code I've written, I thought of using string concatination in order to add a new value each time the loop checks for the next character, don't know whether I'm thinking right or not though, would appriciate if someone could tell me where I'm thinking in the wrong way.
package com.craydesign;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
String number = JOptionPane.showInputDialog("Please enter a number: ");
String evenNumbers = "";
String oddNumbers = "";
String numberZero = "";
for(int i = 0; i < number.length(); i++) {
if(number.charAt(i) % 2 == 0) {
evenNumbers.concat(Integer.toString(i) + ", ");
} else if(number.charAt(i) % 2 != 0) {
oddNumbers.concat(Integer.toString(i) + ", ");
} else if (number.charAt(i) == 0){
numberZero.concat(Integer.toString(i) + ", ");
}
}
JOptionPane.showMessageDialog(null, "Even numbers: " + evenNumbers + "\n" + "Odd numbers: " + oddNumbers + "\n" + "Zero's: " + numberZero);
}
}
use Character.getNumericValue() instead of charAt(i)
public static void main(String[] args) throws IOException
{
String number = JOptionPane.showInputDialog("Please enter a number: ");
StringBuffer evenNumbers = new StringBuffer();
StringBuffer oddNumbers =new StringBuffer();
StringBuffer numberZero =new StringBuffer();
for(int i = 0; i < number.length(); i++) {
int value=Character.getNumericValue(number.charAt(i));
if(value!=0 && value % 2 == 0) {
evenNumbers.append(value).append(',');
} else if(value % 2 != 0) {
oddNumbers.append(value).append(',');
} else if (value == 0){
numberZero.append(value).append(',');
}
}
JOptionPane.showMessageDialog(null, "Even numbers: " + evenNumbers + "\n" + "Odd numbers: " + oddNumbers + "\n" + "Zero's: " + numberZero);
}
EDIT:(displaying numbers in sorted order)
String evenNo[]=evenNumbers.toString().split(",");
String oddNo[]=oddNumbers.toString().split(",");
Arrays.sort(evenNo);
Arrays.sort(oddNo);
JOptionPane.showMessageDialog(null, "Even numbers: " + Arrays.toString(evenNo) + "\n" + "Odd numbers: " + Arrays.toString(oddNo) + "\n" + "Zero's: " + Arrays.toString(numberZero.toString().substring(0,
numberZero.length()-1).split(",")));
You are using String for output and appending the output in the string.
Its a bad idea. as String class is immutable so if you do change anything in String it will create a new Object in memory.
So your solution will take extra memory.
Accroding to me you can solve this problem in two ways
Use StringBuffer class instead of String class for appending
Use ArrayList to Store your result. and iterate over the arraylist and show the output as you want.
Thanks,
Aman
Related
First of all here is my code
import java.util.Scanner;
public class Pengulangan {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int i, number, line, total;
int even, b = 0;
double rat;
System.out.print("Input number: ");
number = sc.nextInt();
even = number/2;
System.out.print("Total sum of number from 1 to number " + number + " is " + even + "\n");
i = 2;
line = 1;
while (i <= number) {
System.out.println("Even number-" + line + " is " +i);
line = line+1;
i = i +2;
}
total = ((number/2) * (even+1));
System.out.printf("Total sum of even number from the number " + number + " = " + total + "\n");
rat = 2*(total/number);
System.out.printf("Sum of average number from the number " + number + " = " + rat + "\n");
}
}
On this specific line on top of the second S.O.P
even = number/2;
i would like to put a loop there to find out how many Even numbers are on the input (ex- 10)
So i tried this code
int i = 1;
while (i <= number) {
if (i%2 == 0)
even = even + 1;
else
odd = odd + 1; //Not going to use this..
i++;
}
System.out.println("Total sum of even number is : ")
I tried putting that code in but i can't make it work, i tried it myself with only the code above and the results are exactly what im looking for but i can't put that in my first code ( the top one ), so i ended up using a sneaky way to get the even numbers.
I need help putting that total sum code to my main code
Sounds like a homework. You don't need loops or anything fancy, if you just want to get the sum of even numbers up to the number you input. Let n be the input number from your program and
class Main {
public static void main(String[] args) {
int n = 10;
//This is the math forumla
int total_sum_math = (((n/2)*((n/2)+1)));
System.out.println("Total sum of even number is : "+total_sum_math+"");
}
}
Reference: https://math.stackexchange.com/questions/3285727/sum-of-even-numbers-n
I'm writing a simple vowel-counter and was wondering if there's a cleaner alternative (possibly a loop?) to replace all of the else if's when comparing s to the various vowels.
I can't think of a simple way to do this effectively as the number of each vowel must be shown individually. It would be very simple if it was just a total vowel count.
I'm quite new to Java so I don't know what can be used to clean this up. If this is the best option, then I am contempt -- but I love cleaning up code where it can be!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int A = 0, E = 0, I = 0, O = 0, U = 0;
System.out.print("Type a single word > ");
String word = input.next();
for (int i = 0; i < word.length(); i++) {
String s = word.substring(i, i + 1);
if (s.equalsIgnoreCase("A")) { A++; }
else if (s.equalsIgnoreCase("E")) { E++; }
else if (s.equalsIgnoreCase("I")) { I++; }
else if (s.equalsIgnoreCase("O")) { O++; }
else if (s.equalsIgnoreCase("U")) { U++; }
}
int total = A + E + I + O + U;
System.out.println("\n'" + word + "' has...\n" + A + " A's\n" + E + " E's\n" + I + " I's\n" + O + " O's\n" + U + " U's\nTotal vowels: " + total + "\n");
input.close();
}
}
Input:
Coding
Output:
'Coding' has...
0 A's
0 E's
1 I's
1 O's
0 U's
Total vowels: 2
Here is a less repetitive way to code it, using an int array for the counts, and a string holding the sequence of vowels.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Type a single word > ");
String word = input.next();
String vowels = "AEIOU";
int[] counts = new int[vowels.length()];
int total = 0;
for (int i = 0; i < word.length(); i++) {
int index = vowels.indexOf(Character.toUpperCase(word.charAt(i)));
if (index >= 0) {
++counts[index];
++total;
}
}
System.out.printf("%n'%s' has...%n", word);
for (int i = 0; i < counts.length; ++i) {
System.out.printf("%s %s's%n", counts[i], vowels.charAt(i));
}
System.out.printf("Total vowels: %s%n", total);
}
}
Output:
Type a single word > Coding
'Coding' has...
0 A's
0 E's
1 I's
1 O's
0 U's
Total vowels: 2
You could avoid a lot of repetition by using a Map that associates vowels (keys) to their frequencies within the word passed at runtime (values).
It is worth noting that a LinkedHashMap is used in the below example as to preserve the insertion order of keys for printing at the end of the program - as would not be the case with a HashMap.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Define Map to map vowels to frequencies
Map<Character, Integer> vowels = new LinkedHashMap<Character, Integer>();
vowels.put('A', 0);
vowels.put('E', 0);
vowels.put('I', 0);
vowels.put('O', 0);
vowels.put('U', 0);
// Get input from user
System.out.print("Type a single word > ");
String word = input.next();
// Iterate across word
for (int i = 0; i < word.length(); i++) {
String c = word.substring(i, i+1); // Get current char
for (Character key : vowels.keySet()) { // Iterate across vowels
if (c.equalsIgnoreCase(key.toString())) {
vowels.put(key, vowels.get(key)+1); // Increment vowel frequency if matched
break; // Break inner loop and move to next char in word
}
}
// Sum total
int total = 0;
for (Character key : vowels.keySet()) {
total += vowels.get(key);
}
// Print results to console
System.out.println("\'" + word + "\'" + " has...");
for (Character key : vowels.keySet()) {
System.out.println(vowels.get(key) + " " + key + "\'s");
}
System.out.println("Total vowels: " + total);
input.close();
}
}
}
So the code posted works and seems to give correct values. The only problem is that it prints every line in the loop instead of just the answer. How can I make it just print the answer instead of every line leading up to it?
import java.util.Scanner;
public class CountLoop{
public static void main (String[] args){
Scanner in = new Scanner (System.in);
int i = -1;
int limit = 0;
System.out.println("Please enter a number");
String end1 = in.nextLine();
int end = Integer.parseInt(end1);
while (i < end){
i++;
limit = (i + limit);
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
}
}
}
I'm fine with using other types of loops as well, as I'll need to show an example with all the different types of loops being used anyway, so any help is appreciated.
Move your system.out.println outside of your while loop
while (i < end){
i++;
limit = (i + limit);
}
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
Or the modern version in Java 8:
int sum = IntStream.range(startInclusive,endExclusive).sum();
System.out.println("The sum of the numbers in between " + startInclusive +
" and " + (endExclusive -1) + " is sum = " + sum);
Renamed variables ;-)
limit -> sum
0 -> startInclusive
end -> endExclusive - 1
I want to print multiple lines of a while loop in 1 gui dialog box.
This is the code I have currently
package Tempconv1;
import javax.swing.JOptionPane;
public class TimesTables
{
public static void main(String[] args)
{
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
//Calculating number inputs
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
String multimsg = ("The calculation is " + num1 + " x " + counter + "=" + total);
JOptionPane.showMessageDialog(null, multimsg);
}
JOptionPane.showMessageDialog(null, "All Done");
}
}
It works but prints out "The calculation is 5x1 = 5" and then opens a new message box to show "The calculation is 5x2 = 10".
I want it to print out
The Calculation is 5x1 = 5
The Calculation is 5x2 = 10
etc
All inside 1 textbox
What you are telling your program to do is create a string of the individual calculation, and then create a dialog box. Then do it again for each loop.
You will want to build all of the messages into one string inside your loop, and then create the dialog box outside the loop.
String multimsg = "";
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
multimsg += ("The calculation is " + num1 + " x " + counter + "=" + total);
}
JOptionPane.showMessageDialog(null, multimsg);
you might want to look into using stringbuilder or similar to be more efficient about building the message string. (https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html)
The problem is that you are showing the message inside the while loop. The syntax with the while loop can be a little bit confusing.
If you are using java 8 you can replace the while/counter with an IntStream and you can compose the message by joining the Strings in the collector:
String message = IntStream.rangeClosed(1, 12)
.mapToObj(i -> "The calculation is " + num1 + "x" + i + " = " + i * num1)
.collect(Collectors.joining(", "));
The first line creates a stream of integers from 1 to 12. The second line maps every number to an individual textmessage. The last line concatenates all the individual messages by joining them with a ,
Your main method would look something like this:
public static void main(String[] args){
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
//Calculating number inputs
String message = IntStream.rangeClosed(1, 12)
.mapToObj(i -> "The calculation is " + num1 + "x" + i + " = " + i * num1)
.collect(Collectors.joining(", "));
JOptionPane.showMessageDialog(null, message);
JOptionPane.showMessageDialog(null, "All Done");
}
before loop:String multimsg = "";
in loop after the maths:multimsg=multimsg+"The calculation is " + num1 + " x " + counter + "=" + total;
and after while loop JOptionPane.showMessageDialog(null, multimsg);
Build only the msg inside the loop and save it to StringBuilder.
public static void main(String[] args)
{
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
//Calculating number inputs
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
sb.append("The calculation is ").append(num1).append(" x ").append(counter).append("=").append(total).append(" ");
}
JOptionPane.showMessageDialog(null, sb.toString());
JOptionPane.showMessageDialog(null, "All Done");
}
I need to display an output like this:
Enter an integer: 3
Number Squared Cubed
====== ======= =====
1 1 1
2 4 8
3 9 27
But instead, when I run the code, I get this output:
Number Squared Cubed
====== ======= =====
3 9 27
In other words, I need to display the powers of an integer,including the powers of the numbers less than or equal to the integer. The numbers of the lesser integers need to be listed but are not displayed along with the integer being entered. How do I fix the code to make sure it outputs all of the integers that are less than or equal to the integer being entered? There are no errors (i.e. red exclamation mark circles) but I need to figure out the proper calculation.
Here is the code:
====================
import java.util.Scanner;
public class Powers
{
public static void main(String[] args)
{
System.out.println("Welcome to the Squares and Cubes Table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.println("Enter an Integer: ");
int integerNext = sc.nextInt();
System.out.println("Number" + " " + "Squared" + " " + "Cubed");
System.out.println("======" + " " + "======" + " " + "======");
for(int i = 1; i <= integerNext; i++)
{
i = integerNext;
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow (i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.println(message);
System.out.println();
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
}
Help is always appreciated. Thanks.
Firstly, as Nikhil said: "Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed".
Secondly, move the first closing curly brace to before getting user input - you want to run the loop, and only ask about continuing when that's finished, if I understand correctly.
Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed
Your are almost there. Since you are looping from 1 to integerNext (which is 3 in your text), the looping variable i will get the values [1,2,3] each iteration, so you don't have to set i manually. When you do:
i = integerNext;
you are setting i to 3, so the loop will finish when it reaches the loop condition.
You may also want to put the "Continue?" check outside the loop:
for (int i = 1; i <= integerNext; i++) {
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow(i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.print(message);
}
// see if the user wants to continue
System.out.print("\nContinue? (y/n): ");
choice = sc.next();
System.out.println();
import java.util.Scanner;
public class SquaresAndCubes {
public static void main(String[] args)
{
// Welcome the user
System.out.println("Welcome to the Squares and Cubes table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do
{
// Get input from the user
System.out.print("Enter an integer: ");
int integer = sc.nextInt();
// Create a header
String header = "Number " + "Squared " + "Cubed " + "\n"
+ "====== " + "======= " + "===== ";
System.out.println(header);
int square = 0;
int cube = 0;
String row = "";
for (int i = 1; i <= integer; i++)
{
square = i * i;
cube = i * i * i;
row = i + " " + square + " " + cube;
System.out.println(row);
}
// See if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
while (!choice.equalsIgnoreCase("n"));
}
}
Basic way to do it with foor loop and some printlines
Scanner sc = new Scanner(System.in);
System.out.print("What number would you like to go up to? ");
int userInt = sc.nextInt();
System.out.println("");
System.out.println("Here is your table!");
System.out.println("");
System.out.println("number | squared | cubed");
System.out.println("------ | ------- | -----");
for (int i = 1; i <= userInt; i++){
System.out.println(i + " | " + (i * i) + " |" + " " +(i * i * i));
}