I've just written some code to form some statistics in java:
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
byte[] weekEval = new byte[18];
String weekMatch = "";
byte order = -1;
while (++order < 18) {
byte tmpRes = 10;
byte count = 5;
if (sc.hasNextByte())
weekMatch += sc.nextByte();
Scanner scInScope = new Scanner(weekMatch);
weekMatch = scInScope.findInLine("Week \\d+");
if (weekMatch == null) {
System.err.println("Illegal Argument");
sc.close();
System.exit(-1);
}
String orderMatch = "Week " + (order + 1);
if (!orderMatch.equals(weekMatch)) {
System.err.println("Illegal argument");
sc.close();
System.exit(-1);
}
weekMatch = "";
for (byte readData = 0; readData < 5; ++readData) {
if (sc.hasNext())
weekMatch += sc.next();
else {
System.err.println("Illegal argument");
sc.close();
scInScope.close();
System.exit(-1);
}
weekMatch += ' ';
}
scInScope = new Scanner(weekMatch);
weekMatch = scInScope.findInLine("\\d \\d \\d \\d \\d");
if (weekMatch == null) {
System.err.println("Illegal Argument");
sc.close();
System.exit(-1);
}
scInScope = new Scanner(weekMatch);
while (count-- > 0) {
tmpRes = scInScope.nextByte();
if (weekEval[order] > tmpRes)
weekEval[order] = tmpRes;
}
}
for (int i = 0; i < 18 && weekEval[i] != 10; ++i) {
System.out.print("Week " + (i + 1) + ' ');
while (weekEval[i]-- > 0)
System.out.printf("=");
System.out.println(">");
}
sc.close();
It works, but I need to complete task without arrays. Ok, I have String at least, right? Wrong. Any String concatenation within a loop is forbidden. The only string method I'm allowed to use is string.equals. There are also system.out, system.err and scanner(System.in). I ran out of ideas, what trick i can use...
Well, at first, I want to apologize for not posting subject and so unclear question. So the task is next:
Customer evaluates this progress as a minimal grade for five tests within each week. Each test can be graded between 1 and 9.
The maximum number of weeks for the analysis is 18. Once the program has obtained information for each week, it displays the graph on the console to show minimum grades for a specific week.
And we keep assuming that 42 is the input data limit.
The exact guaranteed number of tests in a week is 5.
However, the order of weekly data input is not guaranteed, so Week 1’s data can be entered after Week 2’s data. If data input order is wrong, IllegalArgument message shall be displayed, and the program shall be shut down with -1 code.
The problem was in the very-very confusing notes
Note:
• There are many options for storing information, and arrays are just one of them. Apply another method for storing data about student tests without the use of arrays.
• String concatenation often results in unexpected program behavior. If there are many iterations of a concatenation operation in a cycle for a single variable, an application may slow down significantly. That is why we should not use string concatenation inside a loop to generate a result.
In before, '->' stands for the user input. So, overall, it should be looked like:
-> Week 1
-> 4 5 2 4 2
-> Week 2
-> 7 7 7 7 6
-> Week 3
-> 4 3 4 9 8
-> Week 4
-> 9 9 4 6 7
-> 42
Week 1 ==>
Week 2 ======>
Week 3 ===>
Week 4 ====>
The core trick hides in java.utils.scanner and some very handy regex formulas. The final solution is below
import java.util.Scanner;
public class Program {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
byte roll = 0;
long multModif = 1;
long result = 0;
sc.useDelimiter("\\u000A");
while (roll < 18) {
byte tool = 0;
if (sc.hasNext("(42)|(Week(\\s)(\\d))")) {
sc.useDelimiter("\\s+");
String verify = sc.next();
if (verify.equals("42"))
break ;
tool = sc.nextByte();
sc.useDelimiter("\\u000A");
}
else {
System.err.println("Illegal Argument");
sc.close();
System.exit(-1);
}
if (tool != ++roll) {
System.err.println("Illegal Argument");
sc.close();
System.exit(-1);
}
tool = 10;
if (sc.hasNext("(\\d)(\\s)(\\d)(\\s)(\\d)(\\s)(\\d)(\\s)(\\d)")) {
sc.useDelimiter("\\s+");
for (byte i = 0; i < 5; ++i) {
byte toolTmp = sc.nextByte();
if (tool > toolTmp)
tool = toolTmp;
}
sc.useDelimiter("\\u000A");
} else {
System.err.println("Illegal Argument");
sc.close();
System.exit(-1);
}
result += tool * multModif;
multModif *= 10;
}
for (byte i = 0; i < roll; ++i) {
byte weekRes;
weekRes = (byte)(result % 10);
result /= 10;
System.out.print("Week ");
System.out.print(i + 1);
System.out.print(' ');
for (byte j = 0; j < weekRes; ++j)
System.out.print('=');
System.out.println('>');
}
}
}
I made it through some tests, but, frankly to say, not 100% sured about accuracy of my solution, but it works and satisfies noted mentioned above. That you guys for assistance, and big sorry for so confusing question...
Related
import java.util.Scanner;
public class Digits {
public static void main(String[] args) {
/*
*
count = 1
temp = n
while (temp > 10)
Increment count.
Divide temp by 10.0.
*/
//Assignment: fix this code to print: 1 2 3 (for 123)
//temp = 3426 -> 3 4 2 6
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int count = 1;
int temp = input.nextInt();
while(temp >= 10){
count++;
temp = temp / 10;
System.out.print(temp + " ");
}
}
}
Need help fixing code.
Example: when you type 123 it becomes 1 2 3.
Your code is dividing by ten each time, that could be used to print the value in reverse. To print it forward you need a bit more math involving logarithms. Sometime like,
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int temp = input.nextInt();
while (temp > 0) {
int p = (int) (Math.log(temp) / Math.log(10));
int v = (int) (temp / Math.pow(10, p));
System.out.print(v + " ");
temp -= v * Math.pow(10, p);
}
Alternatively, read a line of input. Strip out all non digits and then print every character separated by a space. Like,
String temp = input.nextLine().replaceAll("\\D", "");
System.out.println(temp.replaceAll("(.)", "$1 "));
Most of your code is correct, and what you are trying to do is divide by 10 and then print out the value - this probably should have been a modulus operation % to get the remainder of the operation and print that out - but a nice way of thinking about it.
Nevertheless.
You can just use a string and then split the string on each character
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
// we know that we are going to get some input - so we will just grab it as a String
// whilst we are expecting an int - we will test this later.
// we are doing this as it makes it easier to split the contents of a string
String temp = input.next();
// is this an int? - we will test this first
try {
// if this parsing fails - then it will throw a java.lang.NumberFormat exception
// see the catch block below
int test = Integer.parseInt(temp);
// at this point it is an int no exception was thrown- so let's go
// through and start printing out each character with a space after it
// the temp(which is a string).toCharArray returns a char[] which we
// can just iterate through and set the variable of each iteration to 'c'
for (char c : temp.toCharArray()) {
// now we are going to print out the character with a space after it
System.out.print(c + " ");
}
} catch (NumberFormatException ex){
// this is not an int as we got a number format exception...
System.out.println("You did not enter an integer. :(");
}
// be nice and close the resource
input.close();
}
Answering solely your question, you can use this one-line code.
int test = 123;
System.out.println(String.join(" ", Integer.toString(test).split("")));
Output is: 1 2 3
I'm attempting a code abbey problem and i'm very stuck. My goal for the program is to take in numbers with a math operation before the number and to do that math operation such as:
5
+ 3
* 7
+ 10
* 2
* 3
+ 1
% 11
answer:
1
I feel as if i'm very close but cannot seem to get the answer I want to also add my answers up every single time.
import java.util.Scanner;
public class ModularCalculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Initial Number:");
int iN = in.nextInt();
int sum = 0;
for (int i = 0; i <= 1000000; i++) {
String a = in.next();
int b = in.nextInt();
if (a.equalsIgnoreCase("+")) {
System.out.println(b + iN);
} else if (a.equalsIgnoreCase("*")) {
System.out.println(b * iN);
} else {
System.out.println(b % iN);
sum = b + iN;
}
}
}
}
Your issue is that your not doing proper algebra. Remember the order of operations. In your particular case, we can simplify it to only use the operations that you have, which are: Multiply, Modulo, Addition. Technically, Modulo isn't really standardized in where it is ordered, but I think most languages have Modulo as the same as Multiply/Divide, so a safe bet is to order it that way.
Since this is for a homework assignment clearly, I'm not going to fix your code for you. I will tell you though, that is definitely your issue. Think about how you would go about solving this...hint hint...don't read a token at a time...try reading more than that...
this will not work correctly ! because you are not working right , for example :
the answer of 1+2*3 equals to 7
but your program will return 9 as answer
i think you must learn about postfix and prefix and how to use stack to achieve this goal , here is a link for study :
http://www.cs.man.ac.uk/~pjj/cs212/fix.html
The problem you were having was that you weren't storing the value from last calculation properly. Al I did was just storing last calculated value in "iN".
Scanner in = new Scanner(System.in);
System.out.println("Enter Initial Number:");
int iN = in.nextInt();
int sum = 0;
for (int i = 0; i <= 1000000; i++) {
String a = in.next();
int b = in.nextInt();
if (a.equalsIgnoreCase("+")) {
iN = b + iN;
} else if (a.equalsIgnoreCase("*")) {
iN = b * iN;
} else {
iN = b % iN;
sum = b + iN;
}
System.out.println(iN);
}
I am trying to write a program that will check if the user-entered string is a binary number, and if it is, it will output the number of 1s in the number. I had this working fine with an integer value, but since an int can't hold more than 2 billion or whatever the max value is, I am trying to rewrite it to work with Strings.
As of right now, any number I enter will output "Number entered is not binary." and when I enter 0, I will get a StringIndexOutofBoundsException. I am a fairly novice programmer, so forgive any obvious errors I may have missed, I am just asking for a possible solution to my problem or a push in the right direction. Here is my code (after trying to make it work with Strings rather than integers):
import java.util.*;
public class BinaryHW {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String bin = kb.nextLine();
//the method I used to check whether or not user entered a binary
//number requires changing the value of 'bin'.
//Therefore, 'origBin' set equal to 'bin' for later use.
String origBin = bin;
int count = 0;
boolean isBinary = true;
/* if bin = 0, then this loop will be skipped because
* 0 is a binary number and need not be checked.
*/
while (Integer.parseInt(bin) != 0) {
int lastDigit = bin.charAt(bin.length() - 1);
if (lastDigit > 1) {
System.out.println("Number entered is not binary.");
isBinary = false;
break;
} else {
bin = bin.substring(bin.length() - 2);
}
}
//Again, the method I used to count the 1s in the bin number
//requires changing the value of origBin, so origBin2 is introduced
String origBin2 = origBin;
for (int i = 0; i < origBin.length(); i++) {
if (origBin.charAt(origBin.length() - 1) == 1) {
count ++;
origBin2 = origBin.substring(origBin2.length() - 2);
} else {
origBin2 = origBin.substring(origBin2.length() - 2);
}
}
if (isBinary)
if (count == 1)
System.out.println("There is "
+ count + " 1 in the binary number entered.");
else
System.out.println("There are "
+ count + " 1s in the binary number entered.");
}
}
I think you are overcomplicating things... simply iterate through your binary string, and keep track of the number of 1's reached. If a number other than 0 or 1 is found, report that input is a non-binary number. Below is a snippet which accomplishes this:
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String bin = kb.nextLine();
int oneCount = 0;
boolean validBinaryNum = true;
for (int i = 0; i < bin.length() && validBinaryNum; i++) {
char currentChar = bin.charAt(i);
if (currentChar == '1') oneCount++;
else if (currentChar != '0') {
validBinaryNum = false;
}
}
if (validBinaryNum && bin.length() != 0) {
System.out.println("Number of 1's: " + oneCount);
} else {
System.out.println("Number is not binary");
}
}
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two or more numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Print Each number in Separate line which can be used further for summation
Input
2
50 100
100 50 105
Output
50
100
100
50
105
Now this is the code that i've written that is Giving me Output
import java.util.Scanner;
import java.util.StringTokenizer;
public class Generation {
public static void main(String[] str) {
Scanner keyboard = new Scanner(System.in);
int inputSize;
do {
System.out.println("Enter the value of T Size");
inputSize = keyboard.nextInt();
keyboard.nextLine();
if (inputSize < 2 || inputSize > 10) {
System.out.println("Not a Valid Input Size");
}
} while (inputSize < 2 || inputSize > 10);
String[] inputValue = new String[inputSize];
int tokenCount = 0;
for (int i = 0; i < inputSize; i++) {
System.out.println("Enter the inputs");
inputValue[i] = keyboard.nextLine();
StringTokenizer strToken = new StringTokenizer(inputValue[i], " ");
tokenCount += strToken.countTokens();
}
keyboard.close();
//suppose this is 2nd part
int[] splitedString = new int[tokenCount];
int tempTokenCount = 0;
for (int i = 0; i < inputSize; i++) {
String[] tempSplitArray = inputValue[i].split(" ");
for (int j = 0; j < tempSplitArray.length; j++) {
splitedString[tempTokenCount] = Integer
.parseInt(tempSplitArray[j]);
tempTokenCount++;
}
}
/*for (String s : inputValue) {
System.out.println(s);
}*/
for (Integer s : splitedString) {
System.out.println(s);
}
}
}
Now my question is how can i optimize the 2nd part where i have to use two for loop which result in O(npower2) time complexity. What is the workaround for such situations ?
You are concerned with performance, and I see you have some knowledge of the issues (taking about power time complexity) but I think you don't really fully understand what this means.
Just because your program has nested loops, doesn't mean it is (much) less efficient than one with a single loop. The outer loop iterates over each line and the inner loop iterates over the tokens (which vary in number) so the total number of iterations is the total number of tokens and has nothing to do with any power law.
The main problems with performance is that you simply have too much code to do a very simple thing and you are using temporary arrays, scanners, parsers which will all add to the overhead of it. You can read a file containing its with the following code:
import java.util.Scanner;
public class Scan {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int i;
while (keyboard.hasNext()) {
try {
i = keyboard.nextInt();
System.out.println(i);
} catch(Exception e) {
// Whatever
System.err.println(e.getMessage());
System.exit(1);
}
}
}
}
This will do most of what your class does and in addition catches exceptions. The only thing it doesn't do is read the initial count of lines. Actually, counting lines is hard in the scanner as it doesn't really support it, but maybe you can do without that or have another solution.
I'm trying to ask the user to enter any number of numbers up to 5, each number seperated by space.
for example
enter up to 5 numbers : 3 4 5
I'm going to add them in the integer sum and then later divide them by counter
to get the average of these numbers.
However, my loop does not seem to end. What's wrong with my code?
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt());{
counter++;
sum += scan.nextInt();
}
System.out.println(counter);
System.out.println(sum);
You put a ; between while and {, so it loops. Remove it.
Scanner.hasNextInt() does not do what you seem to think it does. It does not tell you whether there is an integer available in already typed input (it does not have any conception of what has "been typed"), but rather whether the input waiting can be read as an integer. If there is no input already waiting, it will block until there is, so your loop is simply sitting there forever, blocking for more input.
What you probably want to do instead is to read a whole line, and then split it explicitly into space-separated parts, and only then parse those as integers. For example, like this:
String input = scan.nextLine();
for(String part : input.split(" "))
sum += Integer.parseInt(part);
Serge Seredenko's answer is also correct, however, but that's another problem.
Everything in your code is fine except the semicolon(;) just after the while loop, of course it will lead to an infinite loop.
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt()){
counter++;
sum += scan.nextInt();
if(counter >=5)
break;
}
System.out.println(counter);
System.out.println(sum);
scan.close();
First, you need to remove ';' located after while(scan.hasNextInt()) and before {; For the ; means the while statement is complete.
Second, when you use your code, you need CTRL + Z to end up your input. By adding
if(counter >=5)
break;
your input will end up when you input 5 numbers.
If you want to read entire line and then do arithmetic operation later then you dont need to have while loop with hasNextInt() method.
I would suggest you to read line then split by space and iterate over string array. Check out code snippet.
package com.gaurangjadia.code.java;
import java.util.Scanner;
public class SO19204901 {
public static void main(String[] args) {
int counter = 0,
sum = 0;
System.out.println("enter up to 5 numbers");
Scanner scan = new Scanner(System.in);
String strInput = scan.nextLine();
String[] arrayNumbers = strInput.split(" ");
for (int i = 0; i < arrayNumbers.length; i++) {
int n;
try {
n = Integer.parseInt(arrayNumbers[i]);
}
catch (NumberFormatException e) {
n = 0;
}
sum = sum + n;
counter++;
}
System.out.println(sum);
}
}
DataInputStream in = new DataInputStream(System.in);
String[]label = {"quiz #","Total","Average"};
int counter = 0;
int theSum = 0;
System.out.print("Enter up to 5 number : ");
String[]tempNum = in.readLine().trim().split("\\s+");
System.out.println();
while (counter <= tempNum.length)
{
if ( counter == tempNum.length)
{
System.out.printf("%10s %12s\n",label[1],label[2]);
counter = 0;
break;
} else {
System.out.printf("%10s",label[0] + (counter+1) );
}
counter++;
}
while(counter <= tempNum.length)
{
if ( counter == tempNum.length)
{System.out.printf("%10d %10.2f\n",theSum,(double)(theSum/counter));
} else
{System.out.printf("%10d",Integer.valueOf(tempNum[counter]));
theSum += Integer.valueOf(tempNum[counter]);
}
counter++;
}