The code below takes user input of 10 integers, uses String.split(" ") on the space, parses them as integers and prints them out.
public class variableGrowth
{
public main variableGrowth()
{
System.out.print('\u000c');
//scanner and variables
Scanner scan = new Scanner(System.in);
String inputInt = scan.nextLine();
System.out.println("These are the integers you entered: "+inputInt);
String[] items = inputInt.split(" ");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
int stuff = Integer.parseInt(items[i]);
System.out.println(stuff);
}
catch (NumberFormatException nfe) {
System.out.println(results);
System.out.println(errorMessage);
}
}
}
}
}
For each iteration of the loop, can the output be accessed so I could complete a sum in the loop and print it out? For example:
System.out.print(stuff(firstInt)); -- the first integer entered,
result= current + (current * (firstInt/ 100)); // or anything like this
System.out.print("something meaningful: "+result);
Your code won't compile unless you declare the variable errorMessage.
You just initialize an array to store your results but you never use it. In your loop, you should store each parsed value.
results[i] = stuff;
Then outside your loop you can access all your integers to do some stuff.
But for a simple sum operation, you can define a variable then sum each new int inside the loop.
int sum;
for ...
// get your stuff here
sum += stuff;
Also I did not notice your method signature at first. But the signature of a main method is
public static void main(String args[])
In Java, your method signature should follow :
[accessor] [static] 'returnType' yourMethodName('yourParams')
All you need to do is create an additional variable which will contain your running total.
int total = 0;
for (...) {
System.out.println(value);
total += value;
System.out.println("Running Total: " + total)
}
Go with streams (Java 8):
import java.util.*;
import java.lang.*;
class Main
{
public static void main(String[] args) {
System.out.print('\u000c');
//scanner and variables
Scanner scan = new Scanner(System.in);
String inputInt = scan.nextLine();
System.out.println("These are the integers you entered: "+inputInt);
String[] items = inputInt.split(" ");
int sum = Arrays.stream(items)
.mapToInt(x -> Integer.parseInt(x))
.sum();
System.out.println(String.format("Sum is: %s", sum));
}
}
There are a few ways you can do this. If you are looking for a direct sum of all the numbers, just keep a sum variable outside of the loop and keep a working sum through all iterations.
int sum = 0;
for (int i = 0; i < items.length; i++) {
try {
int stuff = Integer.parseInt(items[i]);
sum += stuff;
...
}
Another way is to store all of the numbers (especially if you need to perform other operations with them) in a list or an array and perform your operations after the fact.
int[] numbers = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
int stuff = Integer.parseInt(items[i]);
numbers[i] = stuff;
...
}
// Perform operations here
Related
After writing 1 on scanner I want a random dice number generated and after pressing 1 again I want another random number generated but now I want it added with previous number. I want to make a loop, I want to keep pressing 1 and keep adding random numbers till I reach a certain number.
Thank you.
import java.util.Random;
import java.util.Scanner;
public class dice {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int k = 0; k < 100; k++) {
Scanner scan = new Scanner(System.in);
int s = scan.nextInt();
System.out.println(s);
int previous = s;
if (s == 1) {
Random ran = new Random();
int n = ran.nextInt(6) + 1;
System.out.print(n);
int next;
while (true) {
next = scan.nextInt();
if (next == 1) {
System.out.println(previous);
}
previous = n + 10;
}
}
}
}
}
Define previous outside the for loop, and replace
int previous = s;
previous = n + 10;
with
previous += s;
previous += n + 10;
Scanner sc=new Scanner(System.in);
int sum=0;
for(;;)
{
if(sc.nextInt()==1)
{
int num = (int)(Math.random()*6); // using the pre-defined random function in java.lang.Math class
System.out.println("Dice Value: "+num);
sum+=num; // shorthand adding the number for each iteration
}
//if(sum>100)
// break;
//if statement to check if value of sum is greater/lesser than a specific number
}
System.out.println("Final Answer: "+sum)
Something like this might work (not yet tested): an infinite loop that can be terminated as per choice.
If you are looking for a way that the program works as soon as you physically press the '1' key on your keyboard, without having to press the enter key, something like a keyevent might work:
https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
Please do let me know if there are any errors or doubts :)
I am kinda new to Java, please do not tell me to use methods, etc. because I do not know how to do them. But I do know some charAt things, so can anyone help me find the amount of words, and avg of each word, i did the first part. Here is my code.
import java.util.Scanner;
public class FavouriteQuote {
public static void main(String[] args) {
// TODO Auto-generated method stub
String sQuote;
int counter = 0;
Scanner input = new Scanner (System.in);
System.out.print("Enter one of your favourite quotes: ");
sQuote = input.nextLine();
input.close();
for (int i = 0; i < sQuote.length(); i ++) {
counter ++;
}
System.out.println(counter);
}
}
But what average do you need? average word length in quote?
then your code may look like:
...
input.close();
System.out.println("Characters in quote:" + sQuote.length());
String[] words = sQuote.split("\\s");
// or
// String[] words = sQuote.split(" ");
System.out.println("words in quote:" + words.length);
int totalWordsLength =0;
for (String word: words)
{
totalWordsLength = totalWordsLength + word.length();
}
//or with loop counter
// for (int i=0; i < words.length; i++)
// {
// totalWordsLength += words[i].length();
// }
System.out.println("average word length in quote:" + (totalWordsLength/ words.length));
Keep in mind: here average is int so it will be only integer portion of divide result. i.e. 11/3 = 3
BTW (aside of question) - You do not need your for loop. It does not make any sense.
counter = sQuote.length() does the same.
Here is my program which is supposed to create an array and initialize prime numbers to it. The prime numbers should then be printed but the program just keeps running.
import java.util.*;
public class primes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
int[] prime = new int[x];
int div=2,hold=2;
int c=0;
while (prime[x-1]==0)
{
for(int a=2; div>a;a++)
{
if(div>a && div%a==0)
a=div;
else if(div==(a-1))
hold=div;
}
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
div++;
}
for(int f =0; f<x;f++)
System.out.print(" "+prime[f]+" ");
}
}
I tried changing my loops but I just don't know whats wrong
Like the others mentioned your logic is not right, try something like:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
List<Integer> primes = getPrimes(x);
Integer[] primeArray = primes.toArray(new Integer[primes.size()]);
for(int i :primes.toArray(primeArray)){ // you could just use for(int i :primes){ if you don't need array
System.out.print(i + " ");
}
}
private static List<Integer> getPrimes(int upperLimit) {
ArrayList primes = new ArrayList();
for (int i = 2; i < upperLimit; i++) {
boolean isPrime = true;
// Is it prime?
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
primes.add(i);
}
return primes;
}
The above will print out up to the numbers entered so if you type 5 it will print out 2 3 but not 5.
The following is an other example with Java 8, this one will print as many prime numbers based on the input, if you input 5 you will get 2 3 5 7 11
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
long[] prime = primes(x).toArray();
Arrays.stream(prime).forEach(value -> System.out.print(value + " " ));
}
private static LongStream primes(long max) {
return LongStream.iterate(2, i -> i + 1)
.filter(PrimeNumber::isPrime)
.limit(max);
}
private static boolean isPrime(long x) {
return LongStream.rangeClosed(2, (long)(Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
Your code is wrong. First correct it, And i think you want to store prime numbers coming in range of 1 to N where N is user provided number. Use arrayList (growable) to store it.
It will keep on running because you have this: while (prime[x-1]==0). Where x is an input from the user. Say 5 for instance, then prime[5-1] initially is going to contain a 0 always, and you are running your while loop on this condition which is always going to turn true, thus never ending. Also, your prime number generation logic is not right!
I ran your code in debugger mode and I found the problem.
I tested your program with x=5.
At the end of the first while loop iteration you have :
prime[0] = 2
div = 3
hold = 2
c = 1
And here's the problem :
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
This part won't ever be reached anymore because :
div is never decrement, so it will always be superior to 2.
hold is
equal to prime[c-1], and never change value.
So prime will always stick to be : 2 0 0 0 0, and your while loop will never end.
I found what was wrong and rewrote the code, it works now. The program asks the user for the number primes they want to see and it prints them after storing them in a basic integer array.
import java.util.*;
public class Prime
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
int i=0, hold=2, d=2;
boolean flag = true;
System.out.println("Enter the number of primes.");
int[] prime= new int[scan.nextInt()];
for(;flag;){
for(int a=2;d>a;a++){
if(d==(a)||d%a==0){
break;
}
if((d-1)==a){
hold = d;
}
}
d++;
if(hold==2 || hold!=prime[i-1]){
prime[i] = hold;
i++;
}
if(i==prime.length)
flag= false;
}
for(int x=0;x<prime.length;x++)
System.out.print(prime[x]+" ");
System.out.println("");
}
}
I am trying to create a "calculator", except it needs to print each element that was used to compose the sum total. This printing of the array elements needs to happen at the end of the program, when the user inputs 0 twice in a row.
Upon entering an input, the integer values will be stored in an array. Once the end of the program has been reached, the contents of this array will be printed. However, if the end of the program has not been reached, the program continues while the user adds consecutive inputs.
Currently, the program will only print one element at a time, instead of every element that was used to calculate the total. I've spent hours trying to debug, and any guidance would be greatly appreciated!
import java.util.*;
public class AddingMachine {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean justStarting = true;
int total = 0;
int subtotal = 0;
int input;
int last = 1;
int MAXIMUM_NUMBER_OF_INPUTS = 100;
while (true) {
input = scanner.nextInt();
if (input == 0) {
if (last == 0) {
System.out.println("total " + total);
return;
}
System.out.println("subtotal " + subtotal);
total += subtotal;
subtotal = 0;
}
subtotal += input;
last = input;
int[] numbers = new int[args.length];
for (int i = 0; i < args.length; i++) {
numbers[i] = last;
}
System.out.println(Arrays.toString(numbers));
}
}
When summing the input in your loop, you could store the users input into a List of integers. Once you need to reprint them, you can iterate over the List and print the elements you stored.
Example:
List<Integer> storedUserInput = new ArrayList<>();
while (true) {
input = scanner.nextInt();
storedUserInput.add(input);
if (input == 0) {
if (last == 0) {
for(Integer i : storedUserInput){
System.out.print(i + " + ");
}
System.out.println("total " + total);
return;
}
System.out.println("subtotal " + subtotal);
total += subtotal;
subtotal = 0;
}
}
Within the while loop, the array is re-initialized each time:
int[] numbers = new int[args.length];
so any previously entered value is lost. Also, the purpose of the for loop within the while is not clear.
Also, unless using an array is a requirement, you really don't need an array. You could just use a StringBuffer and append the entered values.
I am learning about arrays and I did quiet a few experiments, most of them went well, however now I'm stuck.
What I want to archive is, find if an specific value (String, int or whatever), exists inside an Array and if it does, use that value for something i.e the code below which I basically count how many times that value was present inside the array:
package arraysOnly;
import java.util.*;
public class ArrayContainsString
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int arraySize = 0;
int wordCount = 0;
System.out.println("How many words are you gonna type?: ");
arraySize = sc.nextInt();
String[] words = new String[arraySize]; // Simple array, the size of which will be decided from the user-input
for(int count = 0; count < arraySize; count++)
{
System.out.println("Enter your " + (count+1) + ": ");
words[count] = sc.next();
}
//Basically this is the part I'm having troubles
if(in_array("ubt", $words)
{
wordCount++;
}
}
}
I know about this,
if(Arrays.asList(words).contains("ubt"));
which basically converts the array into an List / ArrayList or whatever, however I want to treat this as an array only if possible.
An array is the wrong data structure; a Set is the weapon of choice:
Set<String> words = new HashSet<>()
for (int count = 0; count < arraySize; count++) {
System.out.println("Enter your " + (count+1) + ": ");
words.add(sc.next());
}
if (words.contains("ubt"))
wordCount++;
}
The contains() method of a HashSet completes in constant time not matter how large the set is. Although performance is irrelevant for small input sizes like this usage, it's good to get in the habit of choosing the right tools for the job. It also makes your code cleaner.
Generally speaking, don't use arrays unless you absolutely have to; they are only rarely used in commercial code.
The simple solution
public static boolean contains(String toFind, String[] strings) {
for (String str : strings) {
if (str.equals(toFind)) return true;
}
return false;
}
EDIT:
To increase it after the user inputs a word, use this in the loop:
System.out.println("Enter your " + (count+1) + ": ");
words[count] = sc.next();
if (words[count].equals("ubt")) wordCount++;
You can just iterate over array
for (String str : array){
if(str.equals("ubt")){
wordCount++;
}
}
Edit:
It's just equivalent to a normal for loop
for(int i=0; i<array.length; i++) {
if(array[i].equals("ubt")){
wordCount++;
}
}